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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a3161b9d91fda21e98961ce2e53963cf2caf7db7 | 430 | h | C | Gene.h | linkzeldagg/evolutionSandbox | ac98a106ce767bb75320fe91e2c93ba0c36a778f | [
"MIT"
] | null | null | null | Gene.h | linkzeldagg/evolutionSandbox | ac98a106ce767bb75320fe91e2c93ba0c36a778f | [
"MIT"
] | null | null | null | Gene.h | linkzeldagg/evolutionSandbox | ac98a106ce767bb75320fe91e2c93ba0c36a778f | [
"MIT"
] | null | null | null | #pragma once
#include "utils.h"
#include <vector>
#include <random>
#include <iostream>
class Gene
{
public:
Gene();
Gene(Gene& g);
~Gene();
std::vector< VertexNode > vertices;
std::vector< std::vector< EdgeNode > > edges;
static Gene& BreedAndMutate(Gene& a, Gene& b);
std::random_device* rd;
std::mt19937* gen;
std::normal_distribution<float>* normal_dist;
std::normal_distribution<float>* big_normal_dist;
};
| 15.357143 | 50 | 0.695349 | [
"vector"
] |
a316b4d2ab4c6bb62ce778b23f6acd35932585ce | 10,859 | c | C | sdk/sdk/driver/usb/usb/usb.c | doyaGu/C0501Q_HWJL01 | 07a71328bd9038453cbb1cf9c276a3dd1e416d63 | [
"MIT"
] | 1 | 2021-10-09T08:05:50.000Z | 2021-10-09T08:05:50.000Z | sdk/sdk/driver/usb/usb/usb.c | doyaGu/C0501Q_HWJL01 | 07a71328bd9038453cbb1cf9c276a3dd1e416d63 | [
"MIT"
] | null | null | null | sdk/sdk/driver/usb/usb/usb.c | doyaGu/C0501Q_HWJL01 | 07a71328bd9038453cbb1cf9c276a3dd1e416d63 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2008 SMedia Technology Corp. All Rights Reserved.
*/
/** @file
* USB helper routines for real drivers.
*
* @author Irene Lin
*/
/*
* NOTE! This is not actually a driver at all, rather this is
* just a collection of helper routines that implement the
* generic USB things that the real drivers can use..
*
* Think of this as a "USB library" rather than anything else.
* It should be considered a slave, with no callbacks. Callbacks
* are evil.
*/
//=============================================================================
// Include Files
//=============================================================================
#include "usb/config.h"
#include "usb/usb/host.h"
/*-------------------------------------------------------------------*
/**
* usb_find_alt_setting() - Given a configuration, find the alternate setting
* for the given interface.
* @config: the configuration to search (not necessarily the current config).
* @iface_num: interface number to search in
* @alt_num: alternate interface setting number to search for.
*
* Search the configuration's interface cache for the given alt setting.
*
* Return: The alternate setting, if found. %NULL otherwise.
*/
struct usb_host_interface *usb_find_alt_setting(
struct usb_host_config *config,
unsigned int iface_num,
unsigned int alt_num)
{
struct usb_interface_cache *intf_cache = NULL;
int i;
for (i = 0; i < config->desc.bNumInterfaces; i++) {
if (config->intf_cache[i]->altsetting[0].desc.bInterfaceNumber
== iface_num) {
intf_cache = config->intf_cache[i];
break;
}
}
if (!intf_cache)
return NULL;
for (i = 0; i < intf_cache->num_altsetting; i++)
if (intf_cache->altsetting[i].desc.bAlternateSetting == alt_num)
return &intf_cache->altsetting[i];
printk(KERN_DEBUG "Did not find alt setting %u for intf %u, "
"config %u\n", alt_num, iface_num,
config->desc.bConfigurationValue);
return NULL;
}
/**
* usb_ifnum_to_if - get the interface object with a given interface number
* @dev: the device whose current configuration is considered
* @ifnum: the desired interface
*
* This walks the device descriptor for the currently active configuration
* to find the interface object with the particular interface number.
*
* Note that configuration descriptors are not required to assign interface
* numbers sequentially, so that it would be incorrect to assume that
* the first interface in that descriptor corresponds to interface zero.
* This routine helps device drivers avoid such mistakes.
* However, you should make sure that you do the right thing with any
* alternate settings available for this interfaces.
*
* Don't call this function unless you are bound to one of the interfaces
* on this device or you have locked the device!
*
* Return: A pointer to the interface that has @ifnum as interface number,
* if found. %NULL otherwise.
*/
struct usb_interface *usb_ifnum_to_if(const struct usb_device *dev,
unsigned ifnum)
{
struct usb_host_config *config = dev->actconfig;
int i;
if (!config)
return NULL;
for (i = 0; i < config->desc.bNumInterfaces; i++)
if (config->interface[i]->altsetting[0]
.desc.bInterfaceNumber == ifnum)
return config->interface[i];
return NULL;
}
/**
* usb_altnum_to_altsetting - get the altsetting structure with a given alternate setting number.
* @intf: the interface containing the altsetting in question
* @altnum: the desired alternate setting number
*
* This searches the altsetting array of the specified interface for
* an entry with the correct bAlternateSetting value.
*
* Note that altsettings need not be stored sequentially by number, so
* it would be incorrect to assume that the first altsetting entry in
* the array corresponds to altsetting zero. This routine helps device
* drivers avoid such mistakes.
*
* Don't call this function unless you are bound to the intf interface
* or you have locked the device!
*
* Return: A pointer to the entry of the altsetting array of @intf that
* has @altnum as the alternate setting number. %NULL if not found.
*/
struct usb_host_interface *usb_altnum_to_altsetting(
const struct usb_interface *intf,
unsigned int altnum)
{
int i;
for (i = 0; i < intf->num_altsetting; i++) {
if (intf->altsetting[i].desc.bAlternateSetting == altnum)
return &intf->altsetting[i];
}
return NULL;
}
/*-------------------------------------------------------------------*
* USB Device Function Definition
*-------------------------------------------------------------------*/
struct usb_device* usb_alloc_dev(struct usb_device* parent, struct usb_bus* bus)
{
struct usb_device* dev = NULL;
dev = (struct usb_device*)malloc(sizeof(struct usb_device));
if(!dev)
goto end;
memset(dev, 0, sizeof(struct usb_device));
pthread_mutex_init(&dev->mutex, NULL);
dev->state = USB_STATE_ATTACHED;
atomic_set(&dev->urbnum, 0);
INIT_LIST_HEAD(&dev->ep0.urb_list);
dev->ep0.desc.bLength = USB_DT_ENDPOINT_SIZE;
dev->ep0.desc.bDescriptorType = USB_DT_ENDPOINT;
/* ep0 maxpacket comes later, from device descriptor */
usb_enable_endpoint(dev, &dev->ep0, false);
dev->can_submit = 1;
dev->bus = bus;
dev->parent = parent;
end:
return dev;
}
/**
* usb_release_dev - free a usb device structure when all users of it are finished.
* @dev: device that's been disconnected
*
* Will be called only by the device core when all users of this usb device are
* done.
*/
void usb_release_dev(struct usb_device* udev)
{
struct usb_hcd *hcd = bus_to_hcd(udev->bus);
hcd = bus_to_hcd(udev->bus);
usb_destroy_configuration(udev);
pthread_mutex_destroy(&udev->mutex);
usb_put_hcd(hcd);
free(udev->product);
free(udev->manufacturer);
free(udev->serial);
free(udev);
}
/* USB device locking
*
* USB devices and interfaces are locked using the semaphore in their
* embedded struct device. The hub driver guarantees that whenever a
* device is connected or disconnected, drivers are called with the
* USB device locked as well as their particular interface.
*
* Complications arise when several devices are to be locked at the same
* time. Only hub-aware drivers that are part of usbcore ever have to
* do this; nobody else needs to worry about it. The rule for locking
* is simple:
*
* When locking both a device and its parent, always lock the
* the parent first.
*/
/**
* usb_lock_device_for_reset - cautiously acquire the lock for a usb device structure
* @udev: device that's being locked
* @iface: interface bound to the driver making the request (optional)
*
* Attempts to acquire the device lock, but fails if the device is
* NOTATTACHED or SUSPENDED, or if iface is specified and the interface
* is neither BINDING nor BOUND. Rather than sleeping to wait for the
* lock, the routine polls repeatedly. This is to prevent deadlock with
* disconnect; in some drivers (such as usb-storage) the disconnect()
* or suspend() method will block waiting for a device reset to complete.
*
* Return: A negative error code for failure, otherwise 0.
*/
int usb_lock_device_for_reset(struct usb_device *udev,
const struct usb_interface *iface)
{
unsigned long jiffies_expire = jiffies + HZ;
if (udev->state == USB_STATE_NOTATTACHED)
return -ENODEV;
if (udev->state == USB_STATE_SUSPENDED)
return -EHOSTUNREACH;
if (iface && (iface->condition == USB_INTERFACE_UNBINDING ||
iface->condition == USB_INTERFACE_UNBOUND))
return -EINTR;
while (!usb_trylock_device(udev)) {
/* If we can't acquire the lock after waiting one second,
* we're probably deadlocked */
if (time_after(jiffies, jiffies_expire))
return -EBUSY;
msleep(15);
if (udev->state == USB_STATE_NOTATTACHED)
return -ENODEV;
if (udev->state == USB_STATE_SUSPENDED)
return -EHOSTUNREACH;
if (iface && (iface->condition == USB_INTERFACE_UNBINDING ||
iface->condition == USB_INTERFACE_UNBOUND))
return -EINTR;
}
return 0;
}
/**
* usb_get_current_frame_number - return current bus frame number
* @dev: the device whose bus is being queried
*
* Return: The current frame number for the USB host controller used
* with the given USB device. This can be used when scheduling
* isochronous requests.
*
* Note: Different kinds of host controller have different "scheduling
* horizons". While one type might support scheduling only 32 frames
* into the future, others could support scheduling up to 1024 frames
* into the future.
*
*/
int usb_get_current_frame_number(struct usb_device *dev)
{
return usb_hcd_get_frame_number(dev);
}
int usb_dev_exist(struct usb_device* usb_dev)
{
return usb_hcd_dev_exist(usb_dev);
}
/**
* usb_alloc_coherent - allocate dma-consistent buffer for URB_NO_xxx_DMA_MAP
* @dev: device the buffer will be used with
* @size: requested buffer size
* @mem_flags: affect whether allocation may block
* @dma: used to return DMA address of buffer
*
* Return value is either null (indicating no buffer could be allocated), or
* the cpu-space pointer to a buffer that may be used to perform DMA to the
* specified device. Such cpu-space buffers are returned along with the DMA
* address (through the pointer provided).
*
* These buffers are used with URB_NO_xxx_DMA_MAP set in urb->transfer_flags
* to avoid behaviors like using "DMA bounce buffers", or thrashing IOMMU
* hardware during URB completion/resubmit. The implementation varies between
* platforms, depending on details of how DMA will work to this device.
* Using these buffers also eliminates cacheline sharing problems on
* architectures where CPU caches are not DMA-coherent. On systems without
* bus-snooping caches, these buffers are uncached.
*
* When the buffer is no longer used, free it with usb_free_coherent().
*/
void *usb_alloc_coherent(struct usb_device *dev, size_t size, gfp_t mem_flags,
dma_addr_t *dma)
{
uint32_t addr;
if (!dev || !dev->bus)
return NULL;
addr = itpVmemAlloc(size);
if(addr) {
if(dma)
(*dma) = (dma_addr_t)addr;
} else
LOG_ERROR " %s: failed (size: %d) \n", __func__, size LOG_END
return (void *)addr;
}
/**
* usb_free_coherent - free memory allocated with usb_alloc_coherent()
* @dev: device the buffer was used with
* @size: requested buffer size
* @addr: CPU address of buffer
* @dma: DMA address of buffer
*
* This reclaims an I/O buffer, letting it be reused. The memory must have
* been allocated using usb_alloc_coherent(), and the parameters must match
* those provided in that allocation request.
*/
void usb_free_coherent(struct usb_device *dev, size_t size, void *addr,
dma_addr_t dma)
{
if (!dev || !dev->bus)
return;
if (!addr)
return;
itpVmemFree((uint32_t)addr);
}
| 31.844575 | 97 | 0.699604 | [
"object"
] |
a31dbd3cf7f96785a491b5f5b351f1380ce1edfe | 1,222 | h | C | Code/Tools/AssetProcessor/native/utilities/SpecializedDependencyScanner.h | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-09-13T00:01:12.000Z | 2021-09-13T00:01:12.000Z | Code/Tools/AssetProcessor/native/utilities/SpecializedDependencyScanner.h | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | null | null | null | Code/Tools/AssetProcessor/native/utilities/SpecializedDependencyScanner.h | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-07-20T11:07:25.000Z | 2021-07-20T11:07:25.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#include <AzCore/Math/Crc.h>
#include <AzCore/std/smart_ptr/enable_shared_from_this.h>
#include <AzCore/std/smart_ptr/shared_ptr.h>
#include <AzCore/std/string/string.h>
namespace AZ
{
namespace IO
{
class GenericStream;
}
}
namespace AssetProcessor
{
class PotentialDependencies;
class SpecializedDependencyScanner : public AZStd::enable_shared_from_this<SpecializedDependencyScanner>
{
public:
virtual ~SpecializedDependencyScanner() {}
virtual bool ScanFileForPotentialDependencies(AZ::IO::GenericStream& fileStream, PotentialDependencies& potentialDependencies, int maxScanIteration) = 0;
virtual bool DoesScannerMatchFileData(AZ::IO::GenericStream& fileStream) = 0;
virtual bool DoesScannerMatchFileExtension(const AZStd::string& fullPath) = 0;
virtual AZStd::string GetVersion() const = 0;
virtual AZStd::string GetName() const = 0;
virtual AZ::Crc32 GetScannerCRC() const = 0;
};
}
| 31.333333 | 161 | 0.727496 | [
"3d"
] |
a32059085cb62a1d02426ffc635ed708db7ad916 | 699 | h | C | src/GC/Q2_Evaluate.h | karannewatia/SCALE-MAMBA | 467b33a6c80050789204ea3ee3b5cf0113354f85 | [
"BSD-2-Clause"
] | 196 | 2018-05-25T11:41:56.000Z | 2022-03-12T05:49:50.000Z | src/GC/Q2_Evaluate.h | karannewatia/SCALE-MAMBA | 467b33a6c80050789204ea3ee3b5cf0113354f85 | [
"BSD-2-Clause"
] | 49 | 2018-07-17T15:49:41.000Z | 2021-01-19T11:35:31.000Z | src/GC/Q2_Evaluate.h | karannewatia/SCALE-MAMBA | 467b33a6c80050789204ea3ee3b5cf0113354f85 | [
"BSD-2-Clause"
] | 90 | 2018-05-25T11:41:42.000Z | 2022-03-23T19:15:10.000Z | /*
Copyright (c) 2017, The University of Bristol, Senate House, Tyndall Avenue, Bristol, BS8 1TH, United Kingdom.
Copyright (c) 2021, COSIC-KU Leuven, Kasteelpark Arenberg 10, bus 2452, B-3001 Leuven-Heverlee, Belgium.
All rights reserved
*/
#ifndef _Q2Eval
#define _Q2Eval
/*
* Evaluate a circuit using the Q2 Mod2Engine machinary
*/
#include "Circuit.h"
#include "LSSS/Open_Protocol2.h"
// Note: The vector output is resized by this function
// and so can be blank on entry
void Evaluate(vector<vector<Share2>> &output,
const vector<vector<Share2>> &input,
const Circuit &C,
Player &P,
unsigned int online_thread_num);
#endif
| 25.888889 | 110 | 0.682403 | [
"vector"
] |
a322fd7ff02c196c99978392a76b917993fdd1d0 | 2,264 | c | C | kubernetes/unit-test/test_io_k8s_api_core_v1_client_ip_config.c | zouxiaoliang/nerv-kubernetes-client-c | 07528948c643270fd757d38edc68da8c9628ee7a | [
"Apache-2.0"
] | null | null | null | kubernetes/unit-test/test_io_k8s_api_core_v1_client_ip_config.c | zouxiaoliang/nerv-kubernetes-client-c | 07528948c643270fd757d38edc68da8c9628ee7a | [
"Apache-2.0"
] | null | null | null | kubernetes/unit-test/test_io_k8s_api_core_v1_client_ip_config.c | zouxiaoliang/nerv-kubernetes-client-c | 07528948c643270fd757d38edc68da8c9628ee7a | [
"Apache-2.0"
] | null | null | null | #ifndef io_k8s_api_core_v1_client_ip_config_TEST
#define io_k8s_api_core_v1_client_ip_config_TEST
// the following is to include only the main from the first c file
#ifndef TEST_MAIN
#define TEST_MAIN
#define io_k8s_api_core_v1_client_ip_config_MAIN
#endif // TEST_MAIN
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
#include "../external/cJSON.h"
#include "../model/io_k8s_api_core_v1_client_ip_config.h"
io_k8s_api_core_v1_client_ip_config_t* instantiate_io_k8s_api_core_v1_client_ip_config(int include_optional);
io_k8s_api_core_v1_client_ip_config_t* instantiate_io_k8s_api_core_v1_client_ip_config(int include_optional) {
io_k8s_api_core_v1_client_ip_config_t* io_k8s_api_core_v1_client_ip_config = NULL;
if (include_optional) {
io_k8s_api_core_v1_client_ip_config = io_k8s_api_core_v1_client_ip_config_create(
56
);
} else {
io_k8s_api_core_v1_client_ip_config = io_k8s_api_core_v1_client_ip_config_create(
56
);
}
return io_k8s_api_core_v1_client_ip_config;
}
#ifdef io_k8s_api_core_v1_client_ip_config_MAIN
void test_io_k8s_api_core_v1_client_ip_config(int include_optional) {
io_k8s_api_core_v1_client_ip_config_t* io_k8s_api_core_v1_client_ip_config_1 = instantiate_io_k8s_api_core_v1_client_ip_config(include_optional);
cJSON* jsonio_k8s_api_core_v1_client_ip_config_1 = io_k8s_api_core_v1_client_ip_config_convertToJSON(io_k8s_api_core_v1_client_ip_config_1);
printf("io_k8s_api_core_v1_client_ip_config :\n%s\n", cJSON_Print(jsonio_k8s_api_core_v1_client_ip_config_1));
io_k8s_api_core_v1_client_ip_config_t* io_k8s_api_core_v1_client_ip_config_2 = io_k8s_api_core_v1_client_ip_config_parseFromJSON(jsonio_k8s_api_core_v1_client_ip_config_1);
cJSON* jsonio_k8s_api_core_v1_client_ip_config_2 = io_k8s_api_core_v1_client_ip_config_convertToJSON(io_k8s_api_core_v1_client_ip_config_2);
printf("repeating io_k8s_api_core_v1_client_ip_config:\n%s\n", cJSON_Print(jsonio_k8s_api_core_v1_client_ip_config_2));
}
int main() {
test_io_k8s_api_core_v1_client_ip_config(1);
test_io_k8s_api_core_v1_client_ip_config(0);
printf("Hello world \n");
return 0;
}
#endif // io_k8s_api_core_v1_client_ip_config_MAIN
#endif // io_k8s_api_core_v1_client_ip_config_TEST
| 38.372881 | 173 | 0.856007 | [
"model"
] |
a3267ab4442b40871c2880b0f520fe4339e57f89 | 1,845 | h | C | flattype/object/Copy.h | Yeolar/flattype | f52ef2e96ae5ea0888473e386a84f15ac6db5f4e | [
"Apache-2.0"
] | null | null | null | flattype/object/Copy.h | Yeolar/flattype | f52ef2e96ae5ea0888473e386a84f15ac6db5f4e | [
"Apache-2.0"
] | null | null | null | flattype/object/Copy.h | Yeolar/flattype | f52ef2e96ae5ea0888473e386a84f15ac6db5f4e | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2018 Yeolar
*
* 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 "flattype/CommonIDLs.h"
namespace ftt {
::flatbuffers::Offset<void>
copy(::flatbuffers::FlatBufferBuilder& fbb, fbs::Json type, const void* obj);
// Pair
inline ::flatbuffers::Offset<fbs::Pair>
copy(::flatbuffers::FlatBufferBuilder& fbb, const fbs::Pair& obj) {
return fbs::CreatePair(
fbb,
obj.value_type(),
copy(fbb, obj.value_type(), obj.value()),
fbb.CreateString(obj.name()));
}
// Array
inline ::flatbuffers::Offset<fbs::Array>
copy(::flatbuffers::FlatBufferBuilder& fbb, const fbs::Array& obj) {
std::vector<uint8_t> types;
std::vector<flatbuffers::Offset<void>> values;
for (size_t i = 0; i < obj.value()->size(); i++) {
fbs::Json type = obj.value_type()->GetEnum<fbs::Json>(i);
types.push_back(acc::to<uint8_t>(type));
values.push_back(copy(fbb, type, obj.value()->GetAs<void>(i)));
}
return fbs::CreateArrayDirect(fbb, &types, &values);
}
// Object
inline ::flatbuffers::Offset<fbs::Object>
copy(::flatbuffers::FlatBufferBuilder& fbb, const fbs::Object& obj) {
std::vector<flatbuffers::Offset<fbs::Pair>> values;
for (const fbs::Pair* i : *obj.value()) {
values.push_back(copy(fbb, *i));
}
return fbs::CreateObjectDirect(fbb, &values);
}
} // namespace ftt
| 30.75 | 77 | 0.692141 | [
"object",
"vector"
] |
a32a7526144d00547fc1aa0d807dc8ed698f2475 | 1,840 | h | C | HIRT_Multichannel_Convolution/MonoConvolve.h | flucoma/HISSTools_Library | 973873599101463073dc64358dd772fe2e4c734a | [
"BSD-3-Clause"
] | 2 | 2020-01-22T01:53:46.000Z | 2020-09-30T07:54:50.000Z | HIRT_Multichannel_Convolution/MonoConvolve.h | flucoma/HISSTools_Library | 973873599101463073dc64358dd772fe2e4c734a | [
"BSD-3-Clause"
] | null | null | null | HIRT_Multichannel_Convolution/MonoConvolve.h | flucoma/HISSTools_Library | 973873599101463073dc64358dd772fe2e4c734a | [
"BSD-3-Clause"
] | null | null | null |
#pragma once
#include "PartitionedConvolve.h"
#include "TimeDomainConvolve.h"
#include "ConvolveErrors.h"
#include "MemorySwap.h"
#include <cstdint>
#include <memory>
#include <vector>
enum LatencyMode
{
kLatencyZero,
kLatencyShort,
kLatencyMedium,
} ;
namespace HISSTools
{
class MonoConvolve
{
public:
MonoConvolve(uintptr_t maxLength, LatencyMode latency);
MonoConvolve(uintptr_t maxLength, bool zeroLatency, uint32_t A, uint32_t B = 0, uint32_t C = 0, uint32_t D = 0);
// Moveable but not copyable
MonoConvolve(MonoConvolve& obj) = delete;
MonoConvolve& operator = (MonoConvolve& obj) = delete;
MonoConvolve(MonoConvolve&& obj);
MonoConvolve& operator = (MonoConvolve&& obj);
void setResetOffset(intptr_t offset = -1);
ConvolveError resize(uintptr_t length);
ConvolveError set(const float *input, uintptr_t length, bool requestResize);
ConvolveError reset();
void process(const float *in, float *temp, float *out, uintptr_t numSamples, bool accumulate = false);
void setPartitions(uintptr_t maxLength, bool zeroLatency, uint32_t A, uint32_t B = 0, uint32_t C = 0, uint32_t D = 0);
private:
size_t numSizes() { return mSizes.size(); }
MemorySwap<PartitionedConvolve>::AllocFunc mAllocator;
std::vector<uint32_t> mSizes;
std::unique_ptr<TimeDomainConvolve> mTime1;
std::unique_ptr<PartitionedConvolve> mPart1;
std::unique_ptr<PartitionedConvolve> mPart2;
std::unique_ptr<PartitionedConvolve> mPart3;
MemorySwap<PartitionedConvolve> mPart4;
uintptr_t mLength;
intptr_t mPart4Offset;
bool mReset;
};
}
| 27.058824 | 126 | 0.642935 | [
"vector"
] |
a332535a4dd10ef7da2ef6195156b4748444d269 | 8,345 | h | C | wznmopd2/Wznmopd.h | mpsitech/wznm-WhizniumSBE | 4911d561b28392d485c46e98fb915168d82b3824 | [
"MIT"
] | 3 | 2020-09-20T16:24:48.000Z | 2021-12-01T19:44:51.000Z | wznmopd2/Wznmopd.h | mpsitech/wznm-WhizniumSBE | 4911d561b28392d485c46e98fb915168d82b3824 | [
"MIT"
] | null | null | null | wznmopd2/Wznmopd.h | mpsitech/wznm-WhizniumSBE | 4911d561b28392d485c46e98fb915168d82b3824 | [
"MIT"
] | null | null | null | /**
* \file Wznmcmbd.h
* inter-thread exchange object for Wznm combined daemon (declarations)
* \copyright (C) 2016-2020 MPSI Technologies GmbH
* \author Alexander Wirthmueller (auto-generation)
* \date created: 28 Nov 2020
*/
// IP header --- ABOVE
#ifndef WZNMOPD_H
#define WZNMOPD_H
#ifdef __CYGWIN__
#include <sys/select.h>
#endif
#include <unistd.h>
#ifndef _WIN32
#include <sys/socket.h>
#endif
#ifdef _WIN32
#include <windows.h>
#include <winsock.h>
typedef int socklen_t;
#endif
#include <sys/stat.h>
#ifdef _WIN32
#include <pthread.h>
#endif
#include <microhttpd.h>
#if MHD_VERSION < 0x0097002
#define MHD_Result int
#endif
#include <curl/curl.h>
#include "Wznm.h"
class XchgWznmopd;
typedef XchgWznmopd XchgWznm;
/**
* DpchWznmdReg (written by dOpengsrv, read by opd_exe)
*/
class DpchWznmdReg : public DpchWznm {
public:
static const Sbecore::uint SCRNREF = 1;
public:
DpchWznmdReg();
public:
std::string scrNref;
public:
static bool all(const std::set<Sbecore::uint>& items);
void readXML(xmlXPathContext* docctx, std::string basexpath = "", bool addbasetag = false);
};
/**
* DpchWznmopdAck (written by opd_exe, identified by d_exe)
*/
namespace DpchWznmopdAck {
void writeXML(xmlTextWriter* wr);
};
/**
* DpchWznmopdReg (written by opd_exe, read by dOpengsrv)
*/
namespace DpchWznmopdReg {
void writeXML(xmlTextWriter* wr, const Sbecore::usmallint port = 0, const Sbecore::uint ixWznmVOpengtype = 0, const Sbecore::usmallint opprcn = 0);
};
/**
* DpchWznmopdUnreg (written by opd_exe, read by dOpengsrv)
*/
namespace DpchWznmopdUnreg {
void writeXML(xmlTextWriter* wr, const std::string& scrNref = "");
};
/**
* StgWznmDatabase
*/
class StgWznmDatabase : public Sbecore::Block {
public:
static const Sbecore::uint IXDBSVDBSTYPE = 1;
static const Sbecore::uint DBSPATH = 2;
static const Sbecore::uint DBSNAME = 3;
static const Sbecore::uint USERNAME = 4;
static const Sbecore::uint PASSWORD = 5;
static const Sbecore::uint IP = 6;
static const Sbecore::uint PORT = 7;
public:
StgWznmDatabase(const Sbecore::uint ixDbsVDbstype = 0, const std::string& dbspath = "./DbsWznm.sql", const std::string& dbsname = "DbsWznm", const std::string& username = "default", const std::string& password = "asdf1234", const std::string& ip = "127.0.0.1", const Sbecore::usmallint port = 3306);
public:
Sbecore::uint ixDbsVDbstype;
std::string dbspath;
std::string dbsname;
std::string username;
std::string password;
std::string ip;
Sbecore::usmallint port;
public:
bool readXML(xmlXPathContext* docctx, std::string basexpath = "", bool addbasetag = false);
void writeXML(xmlTextWriter* wr, std::string difftag = "", bool shorttags = true);
std::set<Sbecore::uint> comm(const StgWznmDatabase* comp);
std::set<Sbecore::uint> diff(const StgWznmDatabase* comp);
};
/**
* StgWznmopd
*/
class StgWznmopd : public Sbecore::Block {
public:
static const Sbecore::uint ENGIP = 1;
static const Sbecore::uint ENGPORT = 2;
static const Sbecore::uint ENGSRVPORTBASE = 3;
static const Sbecore::uint ENGSRVPORTOFS = 4;
static const Sbecore::uint OPPRCN = 5;
public:
StgWznmopd(const std::string& engip = "127.0.0.1", const Sbecore::usmallint engport = 0, const Sbecore::usmallint engsrvportbase = 13140, const Sbecore::usmallint engsrvportofs = 0, const Sbecore::usmallint opprcn = 4);
public:
std::string engip;
Sbecore::usmallint engport;
Sbecore::usmallint engsrvportbase;
Sbecore::usmallint engsrvportofs;
Sbecore::usmallint opprcn;
public:
bool readXML(xmlXPathContext* docctx, std::string basexpath = "", bool addbasetag = false);
void writeXML(xmlTextWriter* wr, std::string difftag = "", bool shorttags = true);
std::set<Sbecore::uint> comm(const StgWznmopd* comp);
std::set<Sbecore::uint> diff(const StgWznmopd* comp);
};
/**
* StgWznmPath
*/
class StgWznmPath : public Sbecore::Block {
public:
static const Sbecore::uint ACVPATH = 1;
static const Sbecore::uint KEYPATH = 2;
static const Sbecore::uint MONPATH = 3;
static const Sbecore::uint TMPPATH = 4;
static const Sbecore::uint WEBPATH = 5;
static const Sbecore::uint HELPURL = 6;
public:
StgWznmPath(const std::string& acvpath = "${WHIZROOT}/acv/wznm", const std::string& keypath = "", const std::string& monpath = "${WHIZROOT}/mon/wznm", const std::string& tmppath = "${WHIZROOT}/tmp/wznm", const std::string& webpath = "${WHIZROOT}/web/appwznm", const std::string& helpurl = "/wznm");
public:
std::string acvpath;
std::string keypath;
std::string monpath;
std::string tmppath;
std::string webpath;
std::string helpurl;
public:
bool readXML(xmlXPathContext* docctx, std::string basexpath = "", bool addbasetag = false);
void writeXML(xmlTextWriter* wr, std::string difftag = "", bool shorttags = true);
std::set<Sbecore::uint> comm(const StgWznmPath* comp);
std::set<Sbecore::uint> diff(const StgWznmPath* comp);
};
/**
* ReqopWznm
*/
class ReqopWznm {
public:
/**
* VecVBasetype
*/
class VecVBasetype {
public:
static const Sbecore::uint NONE = 0; // invalid
static const Sbecore::uint DPCHINV = 1; // engine triggered Dpch request (POST+DpchInv)
static const Sbecore::uint POLL = 2; // engine triggered Dpch poll request (GET)
};
/**
* VecVState
*/
class VecVState {
public:
static const Sbecore::uint RECEIVE = 0; // during data reception - engsrv internal
static const Sbecore::uint WAITPRC = 1; // before caught by op processor that is idle - in reqs list
static const Sbecore::uint PRC = 2; // while being processesd by op processor - in prcreqs list ; engsrv thread waiting on cReply until timeout
static const Sbecore::uint REPLY = 3; // after being processed by job processor ; in prcreqs list until sent by engsrv
};
public:
ReqopWznm(const Sbecore::uint ixVBasetype = VecVBasetype::NONE, const Sbecore::uint ixVState = VecVState::RECEIVE);
~ReqopWznm();
public:
Sbecore::uint ixVBasetype;
Sbecore::uint ixVState;
Sbecore::utinyint pdone;
MHD_PostProcessor* pp;
Sbecore::Cond cReady; // also protects compare/set of ixVState to REPLY, and pdone
char* request;
size_t requestlen;
DpchInvWznm* dpchinv;
DpchRetWznm* dpchret;
char* reply;
size_t replylen;
public:
void setStateReply();
};
/**
* ShrdatWznm
*/
class ShrdatWznm {
public:
ShrdatWznm(const std::string& srefSupclass, const std::string& srefObject);
~ShrdatWznm();
public:
std::string srefSupclass;
std::string srefObject;
Sbecore::Rwmutex rwmAccess;
public:
virtual void init(XchgWznm* xchg, DbsWznm* dbswznm);
virtual void term(XchgWznm* xchg);
void rlockAccess(const std::string& srefObject, const std::string& srefMember);
void runlockAccess(const std::string& srefObject, const std::string& srefMember);
void wlockAccess(const std::string& srefObject, const std::string& srefMember);
void wunlockAccess(const std::string& srefObject, const std::string& srefMember);
};
/**
* XchgWznmopd
*/
class XchgWznmopd {
public:
/**
* ShrdatOpprc
*/
class ShrdatOpprc : public ShrdatWznm {
public:
// IP ShrdatOpprc.subs --- INSERT
public:
ShrdatOpprc();
public:
// IP ShrdatOpprc.vars --- INSERT
public:
void init(XchgWznm* xchg, DbsWznm* dbswznm);
void term(XchgWznm* xchg);
};
public:
XchgWznmopd();
~XchgWznmopd();
public:
StgWznmDatabase stgwznmdatabase;
StgWznmopd stgwznmopd;
StgWznmPath stgwznmpath;
ShrdatOpprc shrdatOpprc;
public:
// IP cust --- INSERT
public:
// executable/archive/temporary folder paths and help URL
std::string exedir;
std::string acvpath;
std::string tmppath;
std::string helpurl;
// condition for thread start-up
Sbecore::Cond cStable;
// node reference as assigned by engine
std::string scrNref;
// mutex for log file
Sbecore::Mutex mLogfile;
// condition for termination
Sbecore::Cond cTerm;
// condition for op processors
Sbecore::Cond cOpprcs;
// request list and active request list
Sbecore::Mutex mReqs;
std::list<ReqopWznm*> reqs;
std::map<std::string, ReqopWznm*> prcreqs;
public:
// log file methods
void appendToLogfile(const std::string& str);
// request list methods
void addReq(ReqopWznm* req);
ReqopWznm* pullFirstReq();
ReqopWznm* getPrcreqByScrOref(const std::string& scrOref);
void pullPrcreq(const std::string& scrOref);
void setPdone(const std::string& scrOref, const Sbecore::utinyint pdone);
};
#endif
| 24.329446 | 300 | 0.722588 | [
"object"
] |
a33aa8062f520415642b00c99fc2c71bf90467d1 | 7,495 | h | C | source/mutableSources64/plaits/dsp/drums/hi_hat.h | nodesetc/vb.mi-dev | 461ef0031d41818ff94e3d05e3e4b96d2f7f30a0 | [
"MIT"
] | 47 | 2020-05-11T09:45:44.000Z | 2022-03-17T22:12:53.000Z | source/mutableSources64/plaits/dsp/drums/hi_hat.h | robtherich/vb.mi-dev | 4497b5917ed9680a170d3c9b87ac34e525e65978 | [
"MIT"
] | 2 | 2021-04-07T09:14:37.000Z | 2022-01-25T09:00:07.000Z | source/mutableSources64/plaits/dsp/drums/hi_hat.h | robtherich/vb.mi-dev | 4497b5917ed9680a170d3c9b87ac34e525e65978 | [
"MIT"
] | 6 | 2020-08-06T11:09:18.000Z | 2021-12-10T14:37:02.000Z | // Copyright 2016 Emilie Gillet.
//
// Author: Emilie Gillet (emilie.o.gillet@gmail.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// See http://creativecommons.org/licenses/MIT/ for more information.
//
// -----------------------------------------------------------------------------
//
// 808 HH, with a few extra parameters to push things to the CY territory...
// The template parameter MetallicNoiseSource allows another kind of "metallic
// noise" to be used, for results which are more similar to KR-55 or FM hi-hats.
#ifndef PLAITS_DSP_DRUMS_HI_HAT_H_
#define PLAITS_DSP_DRUMS_HI_HAT_H_
#include <algorithm>
#include "stmlib/dsp/dsp.h"
#include "stmlib/dsp/filter.h"
#include "stmlib/dsp/parameter_interpolator.h"
#include "stmlib/dsp/units.h"
#include "stmlib/utils/random.h"
#include "plaits/dsp/dsp.h"
#include "plaits/dsp/oscillator/oscillator.h"
namespace plaits {
// 808 style "metallic noise" with 6 square oscillators.
class SquareNoise {
public:
SquareNoise() { }
~SquareNoise() { }
void Init() {
std::fill(&phase_[0], &phase_[6], 0);
}
void Render(double f0, double* temp_1, double* temp_2, double* out, size_t size) {
const double ratios[6] = {
// Nominal f0: 414 Hz
1.0, 1.304, 1.466, 1.787, 1.932, 2.536
};
uint32_t increment[6];
uint32_t phase[6];
for (int i = 0; i < 6; ++i) {
double f = f0 * ratios[i];
if (f >= 0.499) f = 0.499;
increment[i] = static_cast<uint32_t>(f * 4294967296.0);
phase[i] = phase_[i];
}
while (size--) {
phase[0] += increment[0];
phase[1] += increment[1];
phase[2] += increment[2];
phase[3] += increment[3];
phase[4] += increment[4];
phase[5] += increment[5];
uint32_t noise = 0;
noise += (phase[0] >> 31);
noise += (phase[1] >> 31);
noise += (phase[2] >> 31);
noise += (phase[3] >> 31);
noise += (phase[4] >> 31);
noise += (phase[5] >> 31);
*out++ = 0.33 * static_cast<double>(noise) - 1.0;
}
for (int i = 0; i < 6; ++i) {
phase_[i] = phase[i];
}
}
private:
uint32_t phase_[6];
DISALLOW_COPY_AND_ASSIGN(SquareNoise);
};
class RingModNoise {
public:
RingModNoise() { }
~RingModNoise() { }
void Init() {
for (int i = 0; i < 6; ++i) {
oscillator_[i].Init();
}
}
void Render(double f0, double* temp_1, double* temp_2, double* out, size_t size) {
const double ratio = f0 / (0.01 + f0);
const double f1a = 200.0 / kSampleRate * ratio;
const double f1b = 7530.0 / kSampleRate * ratio;
const double f2a = 510.0 / kSampleRate * ratio;
const double f2b = 8075.0 / kSampleRate * ratio;
const double f3a = 730.0 / kSampleRate * ratio;
const double f3b = 10500.0 / kSampleRate * ratio;
std::fill(&out[0], &out[size], 0.0);
RenderPair(&oscillator_[0], f1a, f1b, temp_1, temp_2, out, size);
RenderPair(&oscillator_[2], f2a, f2b, temp_1, temp_2, out, size);
RenderPair(&oscillator_[4], f3a, f3b, temp_1, temp_2, out, size);
}
private:
void RenderPair(
Oscillator* osc,
double f1,
double f2,
double* temp_1,
double* temp_2,
double* out,
size_t size) {
osc[0].Render<OSCILLATOR_SHAPE_SQUARE>(f1, 0.5, temp_1, size);
osc[1].Render<OSCILLATOR_SHAPE_SAW>(f2, 0.5, temp_2, size);
while (size--) {
*out++ += *temp_1++ * *temp_2++;
}
}
Oscillator oscillator_[6];
DISALLOW_COPY_AND_ASSIGN(RingModNoise);
};
class SwingVCA {
public:
double operator()(double s, double gain) {
s *= s > 0.0 ? 10.0 : 0.1;
s = s / (1.0 + fabs(s));
return (s + 1.0) * gain;
}
};
class LinearVCA {
public:
double operator()(double s, double gain) {
return s * gain;
}
};
template<typename MetallicNoiseSource, typename VCA, bool resonance>
class HiHat {
public:
HiHat() { }
~HiHat() { }
void Init() {
envelope_ = 0.0;
noise_clock_ = 0.0;
noise_sample_ = 0.0;
sustain_gain_ = 0.0;
metallic_noise_.Init();
noise_coloration_svf_.Init();
hpf_.Init();
}
void Render(
bool sustain,
bool trigger,
double accent,
double f0,
double tone,
double decay,
double noisiness,
double* temp_1,
double* temp_2,
double* out,
size_t size) {
const double envelope_decay = 1.0 - 0.003 * stmlib::SemitonesToRatio(
-decay * 84.0);
const double cut_decay = 1.0 - 0.0025 * stmlib::SemitonesToRatio(
-decay * 36.0);
if (trigger) {
envelope_ = (1.5 + 0.5 * (1.0 - decay)) * (0.3 + 0.7 * accent);
}
// Render the metallic noise.
metallic_noise_.Render(2.0 * f0, temp_1, temp_2, out, size);
// Apply BPF on the metallic noise.
double cutoff = 150.0 / kSampleRate * stmlib::SemitonesToRatio(
tone * 72.0);
CONSTRAIN(cutoff, 0.0, 16000.0 / kSampleRate);
noise_coloration_svf_.set_f_q<stmlib::FREQUENCY_ACCURATE>(
cutoff, resonance ? 3.0 + 6.0 * tone : 1.0);
noise_coloration_svf_.Process<stmlib::FILTER_MODE_BAND_PASS>(
out, out, size);
// This is not at all part of the 808 circuit! But to add more variety, we
// add a variable amount of clocked noise to the output of the 6 schmitt
// trigger oscillators.
noisiness *= noisiness;
double noise_f = f0 * (16.0 + 16.0 * (1.0 - noisiness));
CONSTRAIN(noise_f, 0.0, 0.5);
for (size_t i = 0; i < size; ++i) {
noise_clock_ += noise_f;
if (noise_clock_ >= 1.0) {
noise_clock_ -= 1.0;
noise_sample_ = stmlib::Random::GetDouble() - 0.5;
}
out[i] += noisiness * (noise_sample_ - out[i]);
}
// Apply VCA.
stmlib::ParameterInterpolator sustain_gain(
&sustain_gain_,
accent * decay,
size);
for (size_t i = 0; i < size; ++i) {
VCA vca;
envelope_ *= envelope_ > 0.5 ? envelope_decay : cut_decay;
out[i] = vca(out[i], sustain ? sustain_gain.Next() : envelope_);
}
hpf_.set_f_q<stmlib::FREQUENCY_ACCURATE>(cutoff, 0.5);
hpf_.Process<stmlib::FILTER_MODE_HIGH_PASS>(out, out, size);
}
private:
double envelope_;
double noise_clock_;
double noise_sample_;
double sustain_gain_;
MetallicNoiseSource metallic_noise_;
stmlib::Svf noise_coloration_svf_;
stmlib::Svf hpf_;
DISALLOW_COPY_AND_ASSIGN(HiHat);
};
} // namespace plaits
#endif // PLAITS_DSP_DRUMS_HI_HAT_H_
| 28.716475 | 84 | 0.621881 | [
"render"
] |
a3411d014037b44a3c220735c10582ccd7601f34 | 246 | c | C | src/hack.c | SamBWarren/Rok | da1267488eb9503ab5c00250514d26f1e7050e60 | [
"MIT",
"Zlib",
"Unlicense"
] | null | null | null | src/hack.c | SamBWarren/Rok | da1267488eb9503ab5c00250514d26f1e7050e60 | [
"MIT",
"Zlib",
"Unlicense"
] | null | null | null | src/hack.c | SamBWarren/Rok | da1267488eb9503ab5c00250514d26f1e7050e60 | [
"MIT",
"Zlib",
"Unlicense"
] | null | null | null | /*
* This is a hacky way to make sure all of the included files
* are part of the same translation unit.
*/
#include "main.c"
#include "game.c"
#include "gameloop.c"
#include "input.c"
#include "render.c"
#include "update.c"
#include "console.c" | 20.5 | 60 | 0.703252 | [
"render"
] |
a343cf815f24f9bcb31839abb025c28b44736168 | 653 | h | C | tensorflow/Tacotron2/utils/common.h | Coastchb/tensorflow | cabefb9f98502c739aa2761a9fc654004a993d58 | [
"Apache-2.0"
] | null | null | null | tensorflow/Tacotron2/utils/common.h | Coastchb/tensorflow | cabefb9f98502c739aa2761a9fc654004a993d58 | [
"Apache-2.0"
] | null | null | null | tensorflow/Tacotron2/utils/common.h | Coastchb/tensorflow | cabefb9f98502c739aa2761a9fc654004a993d58 | [
"Apache-2.0"
] | null | null | null | #ifndef _COMMON_H
#define _COMMON_H
#include <string>
#include <iostream>
#include <vector>
#include <stdlib.h>
#include <regex>
#include <map>
#include <algorithm>
#include <fstream>
#include <exception>
#include <stdio.h>
#include <stdlib.h>
//#include "tensorflow/core/platform/logging.h"
using std::vector;
using std::string;
using std::cout;
using std::endl;
using std::regex;
using std::regex_match;
using std::regex_search;
using std::smatch;
using std::to_string;
using std::map;
using std::find;
using std::ifstream;
using std::ofstream;
using std::fstream;
using std::ios;
using std::ios_base;
using std::exception;
using std::cerr;
#endif | 17.648649 | 47 | 0.739663 | [
"vector"
] |
a35b1a726fef5b360d28f5226b3bee083e81f060 | 2,989 | h | C | nasm/include/nasm/module.h | Engineev/mocker | 9d3006419ea04683d0b2e6f5ccd21d464e6704e3 | [
"MIT"
] | 14 | 2019-02-18T01:41:50.000Z | 2021-08-11T00:27:51.000Z | nasm/include/nasm/module.h | Engineev/mocker | 9d3006419ea04683d0b2e6f5ccd21d464e6704e3 | [
"MIT"
] | null | null | null | nasm/include/nasm/module.h | Engineev/mocker | 9d3006419ea04683d0b2e6f5ccd21d464e6704e3 | [
"MIT"
] | 1 | 2021-08-11T00:28:39.000Z | 2021-08-11T00:28:39.000Z | // An NASM module contains
// * directives such as global and extern,
// * sections such as .text and .data.
// Each section contains one or more lines and a line consists of a label, an
// instruction and some operands. All of these components are optional.
#ifndef MOCKER_NASM_MODULE_H
#define MOCKER_NASM_MODULE_H
#include <list>
#include <memory>
#include <unordered_map>
#include <vector>
#include "inst.h"
namespace mocker {
namespace nasm {
struct Line {
Line(std::string label, std::shared_ptr<Inst> inst)
: label(std::move(label)), inst(std::move(inst)) {}
explicit Line(std::string label) : label(std::move(label)) {}
explicit Line(std::shared_ptr<Inst> inst) : inst(std::move(inst)) {}
std::string label;
std::shared_ptr<Inst> inst;
};
class Section {
public:
using LineIter = std::list<Line>::const_iterator;
explicit Section(std::string name) : name(std::move(name)) {}
void labelThisLine(const std::string &label) { lines.emplace_back(label); }
template <class Type, class... Args>
void emplaceLine(std::string label, Args &&... args) {
lines.emplace_back(std::move(label),
std::make_shared<Type>(std::forward<Args>(args)...));
}
template <class Type, class... Args> void emplaceInst(Args &&... args) {
emplaceLine<Type>("", std::forward<Args>(args)...);
}
void appendInst(std::shared_ptr<nasm::Inst> inst) {
lines.emplace_back("", std::move(inst));
}
void appendLine(Line line) { lines.emplace_back(std::move(line)); }
void appendLine(LineIter pos, Line line) {
lines.emplace(pos, std::move(line));
}
LineIter erase(LineIter beg, LineIter end) { return lines.erase(beg, end); }
LineIter erase(LineIter pos) { return lines.erase(pos); }
public:
const std::string &getName() const { return name; }
const std::list<Line> &getLines() const { return lines; }
std::list<Line> &getLines() { return lines; }
private:
std::string name;
std::list<Line> lines;
};
class Module {
public:
Module() = default;
Module(const Module &) = default;
Module(Module &&) = default;
Module &operator=(const Module &) = default;
Module &operator=(Module &&) = default;
template <class Type, class... Args> void emplaceDirective(Args &&... args) {
directives.emplace_back(
std::make_shared<Type>(std::forward<Args>(args)...));
}
Section &newSection(const std::string &name);
public:
const std::vector<std::shared_ptr<Directive>> getDirectives() const {
return directives;
}
const std::unordered_map<std::string, Section> &getSections() const {
return sections;
}
Section &getSection(const std::string &name) { return sections.at(name); }
const Section &getSection(const std::string &name) const {
return sections.at(name);
}
private:
std::vector<std::shared_ptr<Directive>> directives;
std::unordered_map<std::string, Section> sections;
};
} // namespace nasm
} // namespace mocker
#endif // MOCKER_NASM_MODULE_H
| 26.451327 | 79 | 0.67648 | [
"vector"
] |
0d2a48cd734e4954765f7a84cc572ba2131f088d | 925 | h | C | aiarena/connect4/src/CGameState.h | clement-masson/aiarena | 5e9f6ffa23ae6acd5fd1d415254f94e66f05d3c8 | [
"MIT"
] | null | null | null | aiarena/connect4/src/CGameState.h | clement-masson/aiarena | 5e9f6ffa23ae6acd5fd1d415254f94e66f05d3c8 | [
"MIT"
] | null | null | null | aiarena/connect4/src/CGameState.h | clement-masson/aiarena | 5e9f6ffa23ae6acd5fd1d415254f94e66f05d3c8 | [
"MIT"
] | 1 | 2020-04-22T13:38:57.000Z | 2020-04-22T13:38:57.000Z | #pragma once
//#include <memory> // include std::unique_ptr
#include <vector>
#include <string>
#include <utility> // include std::pair
#include "CCell.h"
#include "CMove.h"
namespace Connect4 {
const int DEFAULT_WIDTH = 7;
const int DEFAULT_HEIGHT = 6;
class CGameState {
public:
//
int width;
int height;
bool isWhiteTurn;
int turnCounter;
std::vector<CCell> cells;
CGameState(int width=DEFAULT_WIDTH, int height=DEFAULT_HEIGHT);
void initBoard();
void reverse();
std::string toString();
bool isValidIndex(const int i);
bool isValidRC(const int r, const int c);
int RCtoIndex(const int r, const int c);
std::pair<int,int> indexToRC(const int i);
CCell getCell(const int i);
CCell getCell(const int r, const int c);
void setCell(const int i, const CCell c);
void setCell(const int r, const int c, const CCell cell);
std::vector<CMove*> findPossibleMoves();
void doMove(const CMove& move);
int checkTermination();
};
}
| 22.02381 | 63 | 0.737297 | [
"vector"
] |
0d2a7e04a41cf8a52e343cb917bf9b77aa9d6a58 | 23,442 | h | C | src/ftacmp/analyze_fta.h | o-ran-sc/com-gs-lite | 2bc6bde491e4ae54fb54302c052f23a98482eb92 | [
"Apache-2.0"
] | null | null | null | src/ftacmp/analyze_fta.h | o-ran-sc/com-gs-lite | 2bc6bde491e4ae54fb54302c052f23a98482eb92 | [
"Apache-2.0"
] | null | null | null | src/ftacmp/analyze_fta.h | o-ran-sc/com-gs-lite | 2bc6bde491e4ae54fb54302c052f23a98482eb92 | [
"Apache-2.0"
] | null | null | null | /* ------------------------------------------------
Copyright 2014 AT&T Intellectual Property
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 __ANALYZE_FTA_H_DEFINED__
#define __ANALYZE_FTA_H_DEFINED__
#include "parse_fta.h"
#include "parse_schema.h"
#include"type_objects.h"
#include "parse_ext_fcns.h"
#include "iface_q.h"
#include<set>
#include<algorithm>
using namespace std;
// Represent a component of a predicate,
// these components are ANDed together.
// Often they are simple enough to analyze.
class cnf_elem{
public:
int is_atom; // i.e., is an atomic predicate
int eq_pred; // And, it is a test for equality
int in_pred; // Or, it is a an IN predicate
int pr_gb; // the predicate refs a gb column.
int pr_attr; // the predicate refs a table column.
int pr_aggr; // the predicate refs an aggregate
int l_simple; // the lhs is simple (just a colref)
int l_gb; // the lhs refs a gb var
int l_attr; // the lhs refs a table column
int l_aggr; // the lhs refs an aggregate.
int r_simple; // the rhs is simple (just a colref)
int r_gb; // the rhs refs a gb var
int r_attr; // the rhs refs a table column
int r_aggr; // the rhs refs an aggregate.
int cost; // an estiamte of the evaluation cost.
predicate_t *pr;
cnf_elem(predicate_t *p){
is_atom = 0;
eq_pred = 0; in_pred = 0;
pr_gb = pr_attr = pr_aggr = 0;
l_simple = l_gb = l_attr = l_aggr = 0;
r_simple = r_gb = r_attr = r_aggr = 0;
pr = p;
};
cnf_elem(){ is_atom = 0;
eq_pred = 0; in_pred = 0;
pr_gb = pr_attr = pr_aggr = 0;
l_simple = l_gb = l_attr = l_aggr = 0;
r_simple = r_gb = r_attr = r_aggr = 0;
pr = NULL;
};
void swap_scalar_operands(){
int tmp;
if(in_pred) return; // can't swap IN predicates, se list always on right.
if(! is_atom) return; // can only swap scalar expressions.
tmp = l_simple; l_simple = r_simple; r_simple = tmp;
tmp = l_gb; l_gb = r_gb; r_gb = tmp;
tmp = l_attr; l_attr = r_attr; r_attr = tmp;
tmp = l_aggr; l_aggr = r_aggr; r_aggr = tmp;
pr->swap_scalar_operands();
}
};
// Make visible for predicate insertion
void make_cnf_from_pr(predicate_t *pr, std::vector<cnf_elem *> &clist);
// A GB variable is identified by its name and
// its source table variable -- so that joins can be expressed.
// GB Vars defined AS a scalar expression have a null tableref.
struct col_id{
std::string field;
int tblvar_ref;
// Also carry the schema ref -- used to get data type info
// when defining variables.
int schema_ref;
col_id(){tblvar_ref = -1;};
col_id(colref_t *cr){
field = cr->field;
tblvar_ref = cr-> get_tablevar_ref();
schema_ref = cr->get_schema_ref();
};
void load_from_colref(colref_t *cr){
field = cr->field;
tblvar_ref = cr-> get_tablevar_ref();
schema_ref = cr->get_schema_ref();
};
};
struct lt_col_id{
bool operator()(const col_id &cr1, const col_id &cr2) const{
if(cr1.tblvar_ref < cr2.tblvar_ref) return(1);
if(cr1.tblvar_ref == cr2.tblvar_ref)
return (cr1.field < cr2.field);
return(0);
}
};
bool operator<(const col_id &cr1, const col_id &cr2);
// Every GB variable is represented by its name
// (defined above) and the scalar expression which
// defines its value. If the GB var is devlared as a
// colref, the add_gb_attr method of gb_table will
// create an SE consisting of the colref.
// NOTE : using col_id is dangerous when the
// agregation operator is defiend over a self-join
#define GBVAR_COLREF 1
#define GBVAR_SE 2
struct gb_table_entry{
col_id name; // tblref in col_id refers to the tablevar.
scalarexp_t *definition;
int ref_type;
gb_table_entry(){
definition = NULL;
};
data_type *get_data_type(){
return(definition->get_data_type());
};
void reset_temporal(){
if(definition) definition->reset_temporal();
}
};
// The GB table is the symbol table containing
// the GB vars. This object puts a wrapper around
// access to the table.
class gb_table{
private:
std::vector<gb_table_entry *> gtbl;
public:
std::vector<vector<bool> > gb_patterns;
// rollup, cube, and grouping_sets cannot be readily reconstructed by
// analyzing the patterns, so explicitly record them here.
// used only so that sgah_qpn::to_query_string produces
// something meaningful.
std::vector<std::string> gb_entry_type;
std::vector<int> gb_entry_count;
std::vector<std::vector<std::vector<bool> > > pattern_components;
gb_table(){};
int add_gb_attr(gb_t *c, tablevar_list_t *fm, table_list *schema,
table_exp_t *fta_tree, ext_fcn_list *Ext_fcns);
void add_gb_var(std::string n, int t, scalarexp_t *d, int rt){
gb_table_entry *entry = new gb_table_entry();
entry->name.field = n;
entry->name.tblvar_ref = t;
entry->definition = d;
entry->ref_type = rt;
gtbl.push_back(entry);
};
data_type *get_data_type(int g){return(gtbl[g]->get_data_type()); };
int find_gb(colref_t *c, tablevar_list_t *fm, table_list *schema);
scalarexp_t *get_def(int i){return gtbl[i]->definition; };
std::string get_name(int i){return gtbl[i]->name.field; };
int get_tblvar_ref(int i){return gtbl[i]->name.tblvar_ref; };
int get_reftype(int i){return gtbl[i]->ref_type; };
int size(){return(gtbl.size()); };
void set_pattern_info(gb_table *g){
gb_patterns = g->gb_patterns;
gb_entry_type = g->gb_entry_type;
gb_entry_count = g->gb_entry_count;
pattern_components = g->pattern_components;
}
void reset_temporal(int i){
gtbl[i]->reset_temporal();
}
};
// Represent an aggregate to be calculated.
// The unique identifier is the aggregate fcn, and the
// expression aggregated over.
// TODO: unify udaf with built-in better
// (but then again, the core dumps help with debugging)
struct aggr_table_entry{
std::string op;
scalarexp_t *operand;
std::vector<scalarexp_t *> oplist;
int fcn_id; // -1 for built-in aggrs.
data_type *sdt; // storage data type.
data_type *rdt; // return value data type.
bool is_superag;
bool is_running;
bool bailout;
aggr_table_entry(){ sdt = NULL; rdt = NULL; is_superag = false;};
aggr_table_entry(std::string o, scalarexp_t *se, bool s){
op = o; operand = se; fcn_id = -1; sdt = NULL;
if(se){
rdt = new data_type();
rdt->set_aggr_data_type(o,se->get_data_type());
}else{
rdt = new data_type("INT");
}
is_superag = s;
is_running = false;
bailout = false;
};
aggr_table_entry(std::string o, int f, std::vector<scalarexp_t *> s, data_type *st, bool spr, bool r, bool b_o){
op = o;
fcn_id = f;
operand = NULL;
oplist = s;
sdt = st;
rdt = NULL;
is_superag = spr;
is_running = r;
bailout = b_o;
}
bool fta_legal(ext_fcn_list *Ext_fcns);
bool is_star_aggr(){return operand==NULL;};
bool is_builtin(){return fcn_id < 0;};
int get_fcn_id(){return fcn_id;};
bool is_superaggr(){return is_superag;};
bool is_running_aggr(){return is_running;};
bool has_bailout(){return bailout;};
void set_super(bool s){is_superag = s;};
std::vector<std::string> get_subaggr_fcns(std::vector<bool> &use_se);
std::vector<data_type *> get_subaggr_dt();
scalarexp_t *make_superaggr_se(std::vector<scalarexp_t *> se_refs);
data_type *get_storage_type(){return sdt;};
std::vector<scalarexp_t *> get_operand_list(){return oplist;};
aggr_table_entry *duplicate(){
aggr_table_entry *dup = new aggr_table_entry();
dup->op = op;
dup->operand = operand;
dup->oplist = oplist;
dup->fcn_id = fcn_id;
dup->sdt = sdt;
dup->rdt = rdt;
dup->is_superag = is_superag;
dup->is_running = is_running;
dup->bailout = bailout;
return dup;
}
static bool superaggr_allowed(std::string op, ext_fcn_list *Ext_fcns){
if(op == "SUM" || op == "COUNT" || op == "MIN" || op=="MAX")
return true;
return false;
}
bool superaggr_allowed(){
if(is_builtin())
return aggr_table_entry::superaggr_allowed(op,NULL);
// Currently, no UDAFS allowed as superaggregates
return false;
}
static bool multiple_return_allowed(bool is_built_in, ext_fcn_list *Ext_fcns, int fcn_id){
if(is_built_in)
return true;
// Currently, no UDAFS allowed as stateful fcn params.
// in cleaning_when, cleaning_by clauses.
if(Ext_fcns->is_running_aggr(fcn_id) || Ext_fcns->multiple_returns(fcn_id))
return true;
return false;
}
};
class aggregate_table{
public:
std::vector<aggr_table_entry *> agr_tbl;
aggregate_table(){};
int add_aggr(std::string op, scalarexp_t *se, bool is_spr);
int add_aggr(std::string op, int fcn_id, std::vector<scalarexp_t *> opl, data_type *sdt, bool is_spr, bool is_running, bool has_lfta_bailout);
int add_aggr(aggr_table_entry *a){agr_tbl.push_back(a); return agr_tbl.size(); };
int size(){return(agr_tbl.size()); };
scalarexp_t *get_aggr_se(int i){return agr_tbl[i]->operand; };
data_type *get_data_type(int i){
// if(agr_tbl[i]->op == "COUNT")
// return new data_type("uint");
// else
if(! agr_tbl[i]->rdt){
fprintf(stderr,"INTERNAL ERROR in aggregate_table::get_data_type : rdt is NULL.\n");
exit(1);
}
return agr_tbl[i]->rdt;
};
std::string get_op(int i){return agr_tbl[i]->op;};
bool fta_legal(int i,ext_fcn_list *Ext_fcns){return agr_tbl[i]->fta_legal(Ext_fcns); };
bool is_star_aggr(int i){return agr_tbl[i]->is_star_aggr(); };
bool is_builtin(int i){return agr_tbl[i]->is_builtin(); };
int get_fcn_id(int i){return agr_tbl[i]->get_fcn_id();};
bool is_superaggr(int i){return agr_tbl[i]->is_superaggr();};
bool is_running_aggr(int i){return agr_tbl[i]->is_running_aggr();};
bool has_bailout(int i){return agr_tbl[i]->has_bailout();};
// bool multiple_return_allowed(int i){
// return agr_tbl[i]->multiple_return_allowed(agr_tbl[i]->is_builtin(),NULL);
// };
bool superaggr_allowed(int i){return agr_tbl[i]->superaggr_allowed();};
std::vector<scalarexp_t *> get_operand_list(int i){
return agr_tbl[i]->get_operand_list();
}
std::vector<std::string> get_subaggr_fcns(int i, std::vector<bool> &use_se){
return(agr_tbl[i]->get_subaggr_fcns(use_se) );
};
std::vector<data_type *> get_subaggr_dt(int i){
return(agr_tbl[i]->get_subaggr_dt() );
}
data_type *get_storage_type(int i){
return( agr_tbl[i]->get_storage_type());
}
aggr_table_entry *duplicate(int i){
return agr_tbl[i]->duplicate();
};
scalarexp_t *make_superaggr_se(int i, std::vector<scalarexp_t *> se_refs){
return(agr_tbl[i]->make_superaggr_se(se_refs) );
};
};
class cplx_lit_table{
std::vector<literal_t *> cplx_lit_tbl;
std::vector<bool> hdl_ref_tbl;
public:
cplx_lit_table(){};
int add_cpx_lit(literal_t *, bool);
int size(){return cplx_lit_tbl.size();};
literal_t *get_literal(int i){return cplx_lit_tbl[i];};
bool is_handle_ref(int i){return hdl_ref_tbl[i];};
};
enum param_handle_type { cplx_lit_e, litval_e, param_e};
class handle_param_tbl_entry{
private:
public:
std::string fcn_name;
int param_slot;
literal_t *litval;
int complex_literal_idx;
std::string param_name;
param_handle_type val_type;
std::string type_name;
handle_param_tbl_entry(std::string fname, int slot,
literal_t *l, std::string tnm){
fcn_name = fname; param_slot = slot;
val_type = litval_e;
litval = l;
type_name = tnm;
};
handle_param_tbl_entry(std::string fname, int slot, std::string p, std::string tnm){
fcn_name = fname; param_slot = slot;
val_type = param_e;
param_name = p;
type_name = tnm;
};
handle_param_tbl_entry(std::string fname, int slot, int ci, std::string tnm){
fcn_name = fname; param_slot = slot;
val_type = cplx_lit_e;
complex_literal_idx = ci;
type_name = tnm;
};
std::string lfta_registration_fcn(){
char tmps[500];
sprintf(tmps,"register_handle_for_%s_slot_%d",fcn_name.c_str(),param_slot);
return(tmps);
};
std::string hfta_registration_fcn(){return lfta_registration_fcn();};
std::string lfta_deregistration_fcn(){
char tmps[500];
sprintf(tmps,"deregister_handle_for_%s_slot_%d",fcn_name.c_str(),param_slot);
return(tmps);
};
std::string hfta_rdeegistration_fcn(){return lfta_registration_fcn();};
};
class param_table{
// Store the data in vectors to preserve
// listing order.
std::vector<std::string> pname;
std::vector<data_type *> pdtype;
std::vector<bool> phandle;
int find_name(std::string n){
int p;
for(p=0;p<pname.size();++p){
if(pname[p] == n) break;
}
if(p == pname.size()) return(-1);
return(p);
};
public:
param_table(){};
// Add the param with the given name and associated
// data type and handle use.
// if its a new name, return true.
// Else, take OR of use_handle, return false.
// (builds param table and collects handle references).
bool add_param(std::string pnm, data_type *pdt, bool use_handle){
int p = find_name(pnm);
if(p == -1){
pname.push_back(pnm);
pdtype.push_back(pdt);
phandle.push_back(use_handle);
return(true);
}else{
if(use_handle) phandle[p] = use_handle;
return(false);
}
};
int size(){return pname.size(); };
std::vector<std::string> get_param_names(){
return(pname);
};
data_type *get_data_type(std::string pnm){
int p = find_name(pnm);
if(p >= 0){
return(pdtype[p]);
}
return(new data_type("undefined_type"));
};
bool handle_access(std::string pnm){
int p = find_name(pnm);
if(p >= 0){
return(phandle[p]);
}
return(false);
};
};
// Two columns are the same if they come from the
// same source, and have the same field name.
// (use to determine which fields must be unpacked).
// NOTE : dangerous in the presence of self-joins.
typedef std::set<col_id, lt_col_id> col_id_set;
bool contains_gb_pr(predicate_t *pr, std::set<int> &gref_set);
bool contains_gb_se(scalarexp_t *se, std::set<int> &gref_set);
void gather_se_col_ids(scalarexp_t *se, col_id_set &cid_set, gb_table *gtbl);
void gather_pr_col_ids(predicate_t *pr, col_id_set &cid_set, gb_table *gtbl);
void gather_se_opcmp_fcns(scalarexp_t *se, std::set<std::string> &fcn_set);
void gather_pr_opcmp_fcns(predicate_t *pr, std::set<std::string> &fcn_set);
////////////////////////////////////////////
// Structures to record usage of operator views.
class opview_entry{
public:
std::string parent_qname;
std::string root_name;
std::string view_name;
std::string exec_fl; // name of executable file (if any)
std::string udop_alias; // unique ID of the UDOP
std::string mangler;
int liveness_timeout; // maximum delay between hearbeats from udop
int pos;
std::vector<std::string> subq_names;
opview_entry(){mangler="";};
};
class opview_set{
public:
std::vector<opview_entry *> opview_list;
int append(opview_entry *opv){opview_list.push_back(opv);
return opview_list.size()-1;};
int size(){return opview_list.size();};
opview_entry *get_entry(int i){ return opview_list[i];};
};
/////////////////////////////////////////////////////////////////
// Wrap up all of the analysis of the FTA into this package.
//
// There is some duplication between query_summary_class,
// but I'd rather avoid pushing analysis structures
// into the parse modules.
//
// TODO: revisit the issue when nested subqueries are implemented.
// One possibility: implement accessor methods to hide the
// complexity
// For now: this class contains data structures not in table_exp_t
// (with a bit of duplication)
struct query_summary_class{
std::string query_name; // the name of the query, becomes the name
// of the output.
int query_type; // e.g. SELECT, MERGE, etc.
gb_table *gb_tbl; // Table of all group-by attributes.
std::set<int> sg_tbl; // Names of the superGB attributes
aggregate_table *aggr_tbl; // Table of all referenced aggregates.
std::set<std::string> states_refd; // states ref'd by stateful fcns.
// copied from parse tree, then into query node.
// interpret the string representation of data type into a type_object
param_table *param_tbl; // Table of all query parameters.
// There is stuff that is not copied over by analyze_fta,
// it still resides in fta_tree.
table_exp_t *fta_tree; // The (decorated) parse tree.
// This is copied from the parse tree (except for "query_name")
// then copied to the query node in query_plan.cc:145
std::map<std::string, std::string> definitions; // additional definitions.
// CNF representation of the where and having predicates.
std::vector<cnf_elem *> wh_cnf;
std::vector<cnf_elem *> hav_cnf;
std::vector<cnf_elem *> cb_cnf;
std::vector<cnf_elem *> cw_cnf;
std::vector<cnf_elem *> closew_cnf;
// For MERGE type queries.
std::vector<colref_t *> mvars;
scalarexp_t *slack;
//////// Constructors
query_summary_class(){
init();
}
query_summary_class(table_exp_t *f){
fta_tree = f;
init();
}
///// Methods
bool add_query_param(std::string pnm, data_type *pdt, bool use_handle){
return( param_tbl->add_param(pnm,pdt,use_handle));
};
private:
void init(){
// Create the gb_tbl, aggr_tbl, and param_tbl objects
gb_tbl = new gb_table();
aggr_tbl = new aggregate_table();
param_tbl = new param_table();
}
};
int verify_colref(scalarexp_t *se, tablevar_list_t *fm,
table_list *schema, gb_table *gtbl);
std::string impute_query_name(table_exp_t *fta_tree, std::string default_nm);
query_summary_class *analyze_fta(table_exp_t *fta_tree, table_list *schema, ext_fcn_list *Ext_fcns, std::string qname);
bool is_equivalent_se(scalarexp_t *se1, scalarexp_t *se2);
bool is_equivalent_se_base(scalarexp_t *se1, scalarexp_t *se2, table_list *Schema);
bool is_equivalent_pred_base(predicate_t *p1, predicate_t *p2, table_list *Schema);
bool is_equivalent_class_pred_base(predicate_t *p1, predicate_t *p2, table_list *Schema,ext_fcn_list *Ext_fcns);
void analyze_cnf(cnf_elem *c);
void find_partial_fcns(scalarexp_t *se, std::vector<scalarexp_t *> *pf_list, std::vector<int> *fcn_ref_cnt, std::vector<bool> *is_partial_fcn, ext_fcn_list *Ext_fcns);
void find_partial_fcns_pr(predicate_t *pr, std::vector<scalarexp_t *> *pf_list,std::vector<int> *fcn_ref_cnt, std::vector<bool> *is_partial_fcn, ext_fcn_list *Ext_fcns);
void collect_partial_fcns(scalarexp_t *se, std::set<int> &pfcn_refs);
void collect_partial_fcns_pr(predicate_t *pr, std::set<int> &pfcn_refs);
void find_combinable_preds(predicate_t *pr, vector<predicate_t *> *pr_list,
table_list *Schema, ext_fcn_list *Ext_fcns);
void collect_agg_refs(scalarexp_t *se, std::set<int> &agg_refs);
void collect_aggr_refs_pr(predicate_t *pr, std::set<int> &agg_refs);
int bind_to_schema_pr(predicate_t *pr, tablevar_list_t *fm, table_list *schema);
int bind_to_schema_se(scalarexp_t *se, tablevar_list_t *fm, table_list *schema);
temporal_type compute_se_temporal(scalarexp_t *se, std::map<col_id, temporal_type> &tcol);
bool find_complex_literal_se(scalarexp_t *se, ext_fcn_list *Ext_fcns,
cplx_lit_table *complex_literals);
void find_complex_literal_pr(predicate_t *pr, ext_fcn_list *Ext_fcns,
cplx_lit_table *complex_literals);
void find_param_handles_se(scalarexp_t *se, ext_fcn_list *Ext_fcns,
std::vector<handle_param_tbl_entry *> &handle_tbl);
void find_param_handles_pr(predicate_t *pr, ext_fcn_list *Ext_fcns,
std::vector<handle_param_tbl_entry *> &handle_tbl);
// Copy a scalar expression / predicate tree
scalarexp_t *dup_se(scalarexp_t *se, aggregate_table *aggr_tbl);
select_element *dup_select(select_element *sl, aggregate_table *aggr_tbl);
predicate_t *dup_pr(predicate_t *pr, aggregate_table *aggr_tbl);
// Expand gbvars
void expand_gbvars_pr(predicate_t *pr, gb_table &gb_tbl);
scalarexp_t *expand_gbvars_se(scalarexp_t *se, gb_table &gb_tbl);
// copy a query
table_exp_t *dup_table_exp(table_exp_t *te);
// Tie colrefs to a new range var
void bind_colref_se(scalarexp_t *se,
std::vector<tablevar_t *> &fm,
int prev_ref, int new_ref
);
void bind_colref_pr(predicate_t *pr,
std::vector<tablevar_t *> &fm,
int prev_ref, int new_ref
);
std::string impute_colname(std::vector<select_element *> &sel_list, scalarexp_t *se);
std::string impute_colname(std::set<std::string> &curr_names, scalarexp_t *se);
bool is_literal_or_param_only(scalarexp_t *se);
void build_aggr_tbl_fm_pred(predicate_t *pr, aggregate_table *agr_tbl);
void build_aggr_tbl_fm_se(scalarexp_t *se, aggregate_table *agr_tbl);
void compute_cnf_cost(cnf_elem *cm, ext_fcn_list *Ext_fcns);
struct compare_cnf_cost{
bool operator()(const cnf_elem *c1, const cnf_elem *c2) const{
if(c1->cost < c2->cost) return(true);
return(false);
}
};
void get_tablevar_ref_se(scalarexp_t *se, std::vector<int> &reflist);
void get_tablevar_ref_pr(predicate_t *pr, std::vector<int> &reflist);
long long int find_temporal_divisor(scalarexp_t *se, gb_table *gbt, std::string &fnm);
int count_se_ifp_refs(scalarexp_t *se, std::set<std::string> &ifpnames);
int count_pr_ifp_refs(predicate_t *pr, std::set<std::string> &ifpnames);
int resolve_se_ifp_refs(scalarexp_t *se, std::string ifm, std::string ifn, ifq_t *ifdb, std::string &err);
int resolve_pr_ifp_refs(predicate_t *pr, std::string ifm, std::string ifn, ifq_t *ifdb, std::string &err);
int pred_refs_sfun(predicate_t *pr);
int se_refs_sfun(scalarexp_t *se);
// Represent preds for the prefilter, and
// the LFTAs which reference them.
struct cnf_set{
predicate_t *pr;
std::set<int> lfta_id;
std::set<unsigned int> pred_id;
cnf_set(){};
cnf_set(predicate_t *p, unsigned int l, unsigned int i){
pr = dup_pr(p,NULL); // NEED TO UPDATE dup_se TO PROPAGATE
lfta_id.insert(l);
pred_id.insert((l << 16)+i);
}
void subsume(cnf_set *c){
std::set<int>::iterator ssi;
for(ssi=c->lfta_id.begin();ssi!=c->lfta_id.end();++ssi){
lfta_id.insert((*ssi));
}
std::set<unsigned int >::iterator spi;
for(spi=c->pred_id.begin();spi!=c->pred_id.end();++spi){
pred_id.insert((*spi));
}
}
void combine_pred(cnf_set *c){
pr = new predicate_t("AND",pr,c->pr);
std::set<unsigned int >::iterator spi;
for(spi=c->pred_id.begin();spi!=c->pred_id.end();++spi){
pred_id.insert((*spi));
}
}
void add_pred_ids(set<unsigned int> &pred_set){
std::set<unsigned int >::iterator spi;
for(spi=pred_id.begin();spi!=pred_id.end();++spi){
pred_set.insert((*spi));
}
}
static unsigned int make_lfta_key(unsigned int l){
return l << 16;
}
~cnf_set(){};
};
struct compare_cnf_set{
bool operator()(const cnf_set *c1, const cnf_set *c2) const{
if(c1->lfta_id.size() > c2->lfta_id.size()) return(true);
return(false);
}
};
bool operator<(const cnf_set &c1, const cnf_set &c2);
void find_common_filter(std::vector< std::vector<cnf_elem *> > &where_list, table_list *Schema, ext_fcn_list *Ext_fcns, std::vector<cnf_set *> &prefilter_preds, std::set<unsigned int> &pred_ids);
cnf_elem *find_common_filter(std::vector< std::vector<cnf_elem *> > &where_list, table_list *Schema);
std::string int_to_string(int i);
void insert_gb_def_pr(predicate_t *pr, gb_table *gtbl);
void insert_gb_def_se(scalarexp_t *se, gb_table *gtbl);
#endif
| 29.748731 | 195 | 0.707363 | [
"object",
"vector"
] |
0d427d3e539ad537d52842479c31bf0e2df2dbb5 | 831 | c | C | src/builtins.c | jcmdln/ploy | 9dbb681de3b6d7c31693ce24aa29523c4c5fc14a | [
"0BSD"
] | null | null | null | src/builtins.c | jcmdln/ploy | 9dbb681de3b6d7c31693ce24aa29523c4c5fc14a | [
"0BSD"
] | null | null | null | src/builtins.c | jcmdln/ploy | 9dbb681de3b6d7c31693ce24aa29523c4c5fc14a | [
"0BSD"
] | null | null | null | // SPDX-License-Identifier: ISC
#include <stdio.h>
#include <stdlib.h>
#include "builtins.h"
#include "types.h"
struct object *
fn_add(struct object *obj)
{
int64_t sum = 0;
while (obj && obj->type != nil_t) {
if (obj->type != number_t) {
fputs("error: '+': invalid argument(s)", stderr);
exit(1);
}
sum += obj->number;
obj = obj->list->cdr;
}
return object_new_number(sum);
}
struct object *
fn_car(struct object *obj)
{
return obj->list->car;
}
struct object *
fn_cdr(struct object *obj)
{
return obj->list->cdr;
}
struct object *
fn_cons(struct object *obj)
{
return object_new_list(list_new(fn_car(obj), fn_cdr(fn_car(obj))));
}
struct object *
fn_eval(struct object *obj)
{
return obj;
}
struct object *
fn_typeof(struct object *obj)
{
return object_new_string(object_typename(obj->type));
}
| 14.839286 | 68 | 0.67148 | [
"object"
] |
0d444035fe88cfa1507f0920aba0231eb0108cc9 | 4,348 | h | C | src/reloc_table.h | lePerdu/tixasm | e0f89f07b63fe1b2a27ec99595e28927e6230104 | [
"MIT"
] | null | null | null | src/reloc_table.h | lePerdu/tixasm | e0f89f07b63fe1b2a27ec99595e28927e6230104 | [
"MIT"
] | null | null | null | src/reloc_table.h | lePerdu/tixasm | e0f89f07b63fe1b2a27ec99595e28927e6230104 | [
"MIT"
] | null | null | null | /**
* @file reloc_table.h
* @author Zach Peltzer
* @date Created: Mon, 05 Feb 2018
* @date Last Modified: Tue, 06 Feb 2018
*/
#ifndef RELOC_TABLE_H_
#define RELOC_TABLE_H_
#include "expr.h"
#include "section.h"
#include "symbol_table.h"
#include "vector.h"
enum reloc_type {
RT_UNDEF = 0,
/**
* For jr and djnz.
* The relocation entry's value is set to the address directly after the
* instruction. This is subtracted from the symbol's location to get the
* final value; the result must be representable as a signed byte.
*/
RT_REL_JUMP = 1,
/* 8 and 16-bit integers. U means unsigned, S means signed, neither means
* the value can be interpreted as either signed or unnsigned (for an 8-bit
* integer, this means the value could range from -128 to +255).
*/
RT_8_BIT = 2,
RT_U_8_BIT = 3,
RT_S_8_BIT = 4,
RT_16_BIT = 5,
RT_U_16_BIT = 6,
RT_S_16_BIT = 7,
RT_RST,
RT_IM,
/**
* For use only in assembling.
* Indicates that the relocation points to an expression, not a symbol.
*/
RT_EXPR = 0x80,
};
struct reloc_ent {
enum reloc_type type;
enum section sec;
int offset;
/**
* Type-dependent value used to calculate relocation values.
* For symbols, this is an addend to the symbol.
* For RT_REL_JUMP, this is the program counter which the relative jump is
* relative to.
* For RT_RST and RT_IM, this is the instruction byte without the value
* applied.
*/
int value;
union {
const struct symbol_ent *sym;
struct expr_node *expr;
};
};
struct reloc_table {
struct vector relocs;
};
/**
* Determines whether a value is in the allowed range for a specified relocation
* type.
* @param type Relocation type.
* @param value Value to check.
* @return true if the value is in range, false otherwise.
*/
int reltab_in_range(enum reloc_type type, int value);
/**
* Initialize a relocation table.
* @param rt Table to initialize.
* @return 0 on success, -1 on failure.
*/
int reltab_init(struct reloc_table *rt);
/**
* Destroys (frees) a relocation table and all of its entries.
* @param rt Table to destroy.
*/
void reltab_destroy(struct reloc_table *rt);
/**
* Gets the number of elements in a relocation table.
* @param rt Table to get the size of.
* @return Number of elements in @p rt.
*/
size_t reltab_get_size(const struct reloc_table *rt);
/**
* Gets the relocation entry at an index in a table.
* @param rt Relocation table to look in.
* @param idx Index of the entry.
* @param The entry at @p idx, or NULL if the index is out of range.
*/
const struct reloc_ent *reltab_get(const struct reloc_table *rt, int idx);
/**
* Removes a relocation entry at an index.
* This should only be done once the relocation was retrieved and resolved.
* @param rt Relocation table to remove from.
* @param idx Index to remove.
* @return 0 if the entry was removed, -1 if the index is out of range.
*/
int reltab_remove(struct reloc_table *rt, int idx);
/**
* Adds an entry to a relocation table referencing a symbol.
* @param rt Relocation table to add to.
* @param type Type of the relocation.
* @param sec Section of the relocation.
* @param offset Offset in the section of the data to relocate.
* @param value Value used to calculate offsets/values depending on the
* relocation type.
* @param symbol Symbol the relocation references.
*/
int reltab_add_sym(struct reloc_table *rt,
enum reloc_type type, enum section sec, int offset, int value,
const struct symbol_ent *symbol);
/**
* Adds an entry to a relocation table referencing an expression.
* A deep clone of the expression will be made, so the original one can be freed
* and/or modified.
* @param rt Relocation table to add to.
* @param type Type of the relocation.
* @param sec Section of the relocation.
* @param offset Offset in the section of the data to relocate.
* @param value Value used to calculate offsets/values depending on the
* relocation type.
* @param expr Expression the relocation references.
*/
int reltab_add_expr(struct reloc_table *rt,
enum reloc_type type, enum section sec, int offset, int value,
const struct expr_node *expr);
#endif /* RELOC_TABLE_H_ */
/* vim: set tw=80 ft=c: */
| 28.418301 | 80 | 0.689052 | [
"vector"
] |
0d472eb960e8b324c47487c85f7f1fa9651d1b14 | 1,902 | h | C | Pepe Internal/internal.h | msmaiaa/Pepe-Internal | 2a98f139adc862b533c5c1d6eeae224407b56fb1 | [
"MIT"
] | null | null | null | Pepe Internal/internal.h | msmaiaa/Pepe-Internal | 2a98f139adc862b533c5c1d6eeae224407b56fb1 | [
"MIT"
] | null | null | null | Pepe Internal/internal.h | msmaiaa/Pepe-Internal | 2a98f139adc862b533c5c1d6eeae224407b56fb1 | [
"MIT"
] | 1 | 2021-12-31T11:12:21.000Z | 2021-12-31T11:12:21.000Z | #pragma once
#include <windows.h>
#include <TlHelp32.h>
#include <vector>
#include <memory>
#include <string>
#define INRANGE(x,a,b) (x >= a && x <= b)
#define getBits( x ) (INRANGE((x&(~0x20)),'A','F') ? ((x&(~0x20)) - 'A' + 0xa) : (INRANGE(x,'0','9') ? x - '0' : 0))
#define getByte( x ) (getBits(x[0]) << 4 | getBits(x[1]))
uintptr_t GetModuleBaseAddress(const wchar_t* modName);
uintptr_t FindDynamicAddress(uintptr_t ptr, std::vector<unsigned int> offsets);
void PatchInternal(BYTE* dst, BYTE* src, size_t size);
class ManagedPatch {
BYTE* dst; //address of the code to patch
size_t size; //size of the patch
BYTE* originalCode; //backup of the original code
BYTE* newCode; //new functionality
public:
ManagedPatch(BYTE* dst, BYTE* src, size_t size); //constructor
~ManagedPatch(); //destructor
void enable(); //enable the patch
void disable(); //disable the patch
};
class NopInternal { //class for replacing code with code that does nothing
private:
BYTE* dst; //address of the code to patch
size_t size; //size of the patch
BYTE* originalCode; //backup of the original code
BYTE* nopCode; //code that does nothing
public:
NopInternal(BYTE* dst, size_t size); //constructor
~NopInternal(); //destructor
void enable(); //enable the patch
void disable(); //disable the patch
};
class Hook {
void* tToHook;
std::unique_ptr<char[]> oldOpcodes;
int tLen;
bool enabled;
public:
Hook(void* toHook, void* ourFunct, int len);
~Hook();
void enable();
void disable();
bool isEnabled();
};
class TrampHook { //easy to use class for hooking functions
void* gateWay;
Hook* managedHook;
public:
TrampHook(void* toHook, void* ourFunct, int len);
~TrampHook(); //restores original code
void enable();
void disable();
bool isEnabled();
void* getGateway();
};
unsigned int FindPattern(std::string moduleName, std::string pattern, bool relativeOffset = false);
| 26.788732 | 119 | 0.694006 | [
"vector"
] |
0d4c1e6a53e107480ab353fc690fd13bcfa06d8d | 2,112 | h | C | source/iozeug/include/iozeug/directorytraversal.h | kateyy/libzeug | ffb697721cd8ef7d6e685fd5e2c655d711565634 | [
"MIT"
] | null | null | null | source/iozeug/include/iozeug/directorytraversal.h | kateyy/libzeug | ffb697721cd8ef7d6e685fd5e2c655d711565634 | [
"MIT"
] | null | null | null | source/iozeug/include/iozeug/directorytraversal.h | kateyy/libzeug | ffb697721cd8ef7d6e685fd5e2c655d711565634 | [
"MIT"
] | null | null | null |
#pragma once
#include <string>
#include <vector>
#include <functional>
#include <iozeug/iozeug_api.h>
namespace iozeug
{
/**
* @brief
* List all files in a directory
*
* @param[in] dirName
* Path to directory (exluding a trailing '/'!)
* @param[in] recursive
* Search recursively in sub-directories?
* @param[out] files
* List of files
*
* @remarks
* Lists all files in the directory, including all
* files in sub-directories if recursive is true.
* Only files are listed, directories are not included.
* The search path is included in the file name, e.g.,
* getFile("dir") may result in ["dir/file1.txt", "dir/file2.png", ...].
*/
IOZEUG_API void getFiles(const std::string & directory, bool recursive, std::vector<std::string> & files);
/**
* @brief
* List all files in a directory
*
* @param[in] dirName
* Path to directory (exluding a trailing '/'!)
* @param[in] recursive
* Search recursively in sub-directories?
*
* @return
* List of files
*/
IOZEUG_API std::vector<std::string> getFiles(const std::string & directory, bool recursive);
/**
* @brief
* Scan directory for files with a specific filename extension
*
* @param[in] directory
* Path to directory
* @param[in] fileExtension
* File extension ("*" for all files)
* @param[in] recursive
* Search recursively in sub-directories?
*
* @return
* List of found files, including the directory name
*/
IOZEUG_API std::vector<std::string> scanDirectory(const std::string & directory, const std::string & fileExtension, bool recursive = false);
/**
* @brief
* Scan directory for files with a specific filename extension
*
* @param[in] directory
* Path to directory
* @param[in] fileExtension
* File extension ("*" for all files)
* @param[in] recursive
* Search recursively in sub-directories?
* @param[in] callback
* Function that is called for each found file
*/
IOZEUG_API void scanDirectory(const std::string & directory, const std::string & fileExtension, bool recursive, const std::function<void(const std::string &)> & callback);
} // namespace iozeug
| 25.445783 | 171 | 0.689394 | [
"vector"
] |
0d58c258c73a77d52a1147b79ad655d0255c5184 | 1,295 | h | C | ace/tao/tests/Exposed_Policies/RT_Properties.h | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | 46 | 2015-12-04T17:12:58.000Z | 2022-03-11T04:30:49.000Z | ace/tao/tests/Exposed_Policies/RT_Properties.h | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | null | null | null | ace/tao/tests/Exposed_Policies/RT_Properties.h | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | 23 | 2016-10-24T09:18:14.000Z | 2022-02-25T02:11:35.000Z | //RT_Properties.h,v 1.3 2001/06/13 15:23:50 fhunleth Exp
//
// ============================================================================
//
// = LIBRARY
// TAO
//
// = FILENAME
// RT_Properties.h
//
// = DESCRIPTION
// Defines a series of "real time" property that an Object
// or a POA created on a RT-ORB can have.
//
// = AUTHOR
// Angelo Corsaro <corsaro@cs.wustl.edu>
//
// ============================================================================
#ifndef RT_PROPERTIES_H_
#define RT_PROPERTIES_H_
#include "tao/RTCORBA/RTCORBA.h"
class RT_Properties
{
public:
// -- Ctor/Dtor --
RT_Properties (void);
~RT_Properties (void);
static RT_Properties * read_from (const char *file_name,
CORBA::Environment &ACE_TRY_ENV);
// -- Accessor Methods --
void priority (RTCORBA::Priority priority);
RTCORBA::Priority priority (void);
void priority_bands (const RTCORBA::PriorityBands& priority_bands);
const RTCORBA::PriorityBands& priority_bands (void);
void ior_source (const char *s);
const char* ior_source (void);
private:
RTCORBA::Priority priority_;
RTCORBA::PriorityBands priority_bands_;
char ior_source_[256];
};
#endif /* RT_PROPERTIES_H_ */
| 24.433962 | 80 | 0.563707 | [
"object"
] |
0d5fd94997bbf6f02107b31652030af842777744 | 7,135 | h | C | aws-cpp-sdk-glue/include/aws/glue/model/RegisterSchemaVersionRequest.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-glue/include/aws/glue/model/RegisterSchemaVersionRequest.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-glue/include/aws/glue/model/RegisterSchemaVersionRequest.h | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/glue/Glue_EXPORTS.h>
#include <aws/glue/GlueRequest.h>
#include <aws/glue/model/SchemaId.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Glue
{
namespace Model
{
/**
*/
class AWS_GLUE_API RegisterSchemaVersionRequest : public GlueRequest
{
public:
RegisterSchemaVersionRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "RegisterSchemaVersion"; }
Aws::String SerializePayload() const override;
Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;
/**
* <p>This is a wrapper structure to contain schema identity fields. The structure
* contains:</p> <ul> <li> <p>SchemaId$SchemaArn: The Amazon Resource Name (ARN) of
* the schema. Either <code>SchemaArn</code> or <code>SchemaName</code> and
* <code>RegistryName</code> has to be provided.</p> </li> <li>
* <p>SchemaId$SchemaName: The name of the schema. Either <code>SchemaArn</code> or
* <code>SchemaName</code> and <code>RegistryName</code> has to be provided.</p>
* </li> </ul>
*/
inline const SchemaId& GetSchemaId() const{ return m_schemaId; }
/**
* <p>This is a wrapper structure to contain schema identity fields. The structure
* contains:</p> <ul> <li> <p>SchemaId$SchemaArn: The Amazon Resource Name (ARN) of
* the schema. Either <code>SchemaArn</code> or <code>SchemaName</code> and
* <code>RegistryName</code> has to be provided.</p> </li> <li>
* <p>SchemaId$SchemaName: The name of the schema. Either <code>SchemaArn</code> or
* <code>SchemaName</code> and <code>RegistryName</code> has to be provided.</p>
* </li> </ul>
*/
inline bool SchemaIdHasBeenSet() const { return m_schemaIdHasBeenSet; }
/**
* <p>This is a wrapper structure to contain schema identity fields. The structure
* contains:</p> <ul> <li> <p>SchemaId$SchemaArn: The Amazon Resource Name (ARN) of
* the schema. Either <code>SchemaArn</code> or <code>SchemaName</code> and
* <code>RegistryName</code> has to be provided.</p> </li> <li>
* <p>SchemaId$SchemaName: The name of the schema. Either <code>SchemaArn</code> or
* <code>SchemaName</code> and <code>RegistryName</code> has to be provided.</p>
* </li> </ul>
*/
inline void SetSchemaId(const SchemaId& value) { m_schemaIdHasBeenSet = true; m_schemaId = value; }
/**
* <p>This is a wrapper structure to contain schema identity fields. The structure
* contains:</p> <ul> <li> <p>SchemaId$SchemaArn: The Amazon Resource Name (ARN) of
* the schema. Either <code>SchemaArn</code> or <code>SchemaName</code> and
* <code>RegistryName</code> has to be provided.</p> </li> <li>
* <p>SchemaId$SchemaName: The name of the schema. Either <code>SchemaArn</code> or
* <code>SchemaName</code> and <code>RegistryName</code> has to be provided.</p>
* </li> </ul>
*/
inline void SetSchemaId(SchemaId&& value) { m_schemaIdHasBeenSet = true; m_schemaId = std::move(value); }
/**
* <p>This is a wrapper structure to contain schema identity fields. The structure
* contains:</p> <ul> <li> <p>SchemaId$SchemaArn: The Amazon Resource Name (ARN) of
* the schema. Either <code>SchemaArn</code> or <code>SchemaName</code> and
* <code>RegistryName</code> has to be provided.</p> </li> <li>
* <p>SchemaId$SchemaName: The name of the schema. Either <code>SchemaArn</code> or
* <code>SchemaName</code> and <code>RegistryName</code> has to be provided.</p>
* </li> </ul>
*/
inline RegisterSchemaVersionRequest& WithSchemaId(const SchemaId& value) { SetSchemaId(value); return *this;}
/**
* <p>This is a wrapper structure to contain schema identity fields. The structure
* contains:</p> <ul> <li> <p>SchemaId$SchemaArn: The Amazon Resource Name (ARN) of
* the schema. Either <code>SchemaArn</code> or <code>SchemaName</code> and
* <code>RegistryName</code> has to be provided.</p> </li> <li>
* <p>SchemaId$SchemaName: The name of the schema. Either <code>SchemaArn</code> or
* <code>SchemaName</code> and <code>RegistryName</code> has to be provided.</p>
* </li> </ul>
*/
inline RegisterSchemaVersionRequest& WithSchemaId(SchemaId&& value) { SetSchemaId(std::move(value)); return *this;}
/**
* <p>The schema definition using the <code>DataFormat</code> setting for the
* <code>SchemaName</code>.</p>
*/
inline const Aws::String& GetSchemaDefinition() const{ return m_schemaDefinition; }
/**
* <p>The schema definition using the <code>DataFormat</code> setting for the
* <code>SchemaName</code>.</p>
*/
inline bool SchemaDefinitionHasBeenSet() const { return m_schemaDefinitionHasBeenSet; }
/**
* <p>The schema definition using the <code>DataFormat</code> setting for the
* <code>SchemaName</code>.</p>
*/
inline void SetSchemaDefinition(const Aws::String& value) { m_schemaDefinitionHasBeenSet = true; m_schemaDefinition = value; }
/**
* <p>The schema definition using the <code>DataFormat</code> setting for the
* <code>SchemaName</code>.</p>
*/
inline void SetSchemaDefinition(Aws::String&& value) { m_schemaDefinitionHasBeenSet = true; m_schemaDefinition = std::move(value); }
/**
* <p>The schema definition using the <code>DataFormat</code> setting for the
* <code>SchemaName</code>.</p>
*/
inline void SetSchemaDefinition(const char* value) { m_schemaDefinitionHasBeenSet = true; m_schemaDefinition.assign(value); }
/**
* <p>The schema definition using the <code>DataFormat</code> setting for the
* <code>SchemaName</code>.</p>
*/
inline RegisterSchemaVersionRequest& WithSchemaDefinition(const Aws::String& value) { SetSchemaDefinition(value); return *this;}
/**
* <p>The schema definition using the <code>DataFormat</code> setting for the
* <code>SchemaName</code>.</p>
*/
inline RegisterSchemaVersionRequest& WithSchemaDefinition(Aws::String&& value) { SetSchemaDefinition(std::move(value)); return *this;}
/**
* <p>The schema definition using the <code>DataFormat</code> setting for the
* <code>SchemaName</code>.</p>
*/
inline RegisterSchemaVersionRequest& WithSchemaDefinition(const char* value) { SetSchemaDefinition(value); return *this;}
private:
SchemaId m_schemaId;
bool m_schemaIdHasBeenSet;
Aws::String m_schemaDefinition;
bool m_schemaDefinitionHasBeenSet;
};
} // namespace Model
} // namespace Glue
} // namespace Aws
| 43.242424 | 138 | 0.677926 | [
"model"
] |
0d6369eebf6b63253cde49d3cde32b05dff8cdbf | 24,943 | c | C | src/libpfm-3.y/lib/pfmlib_common.c | tcreech/papi-4.0.0-64-solaris11.2 | b5e66422fb31bc4017b7728e16e4953f3c5ec9d7 | [
"BSD-3-Clause"
] | null | null | null | src/libpfm-3.y/lib/pfmlib_common.c | tcreech/papi-4.0.0-64-solaris11.2 | b5e66422fb31bc4017b7728e16e4953f3c5ec9d7 | [
"BSD-3-Clause"
] | null | null | null | src/libpfm-3.y/lib/pfmlib_common.c | tcreech/papi-4.0.0-64-solaris11.2 | b5e66422fb31bc4017b7728e16e4953f3c5ec9d7 | [
"BSD-3-Clause"
] | null | null | null | /*
* pfmlib_common.c: set of functions common to all PMU models
*
* Copyright (c) 2001-2006 Hewlett-Packard Development Company, L.P.
* Contributed by Stephane Eranian <eranian@hpl.hp.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE /* for getline */
#endif
#include <sys/types.h>
#include <ctype.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <limits.h>
#include <perfmon/pfmlib.h>
#include "pfmlib_priv.h"
static pfm_pmu_support_t *supported_pmus[]=
{
#ifdef CONFIG_PFMLIB_ARCH_IA64
&montecito_support,
&itanium2_support,
&itanium_support,
&generic_ia64_support, /* must always be last for IA-64 */
#endif
#ifdef CONFIG_PFMLIB_ARCH_X86_64
&amd64_support,
&pentium4_support,
&core_support,
&intel_atom_support,
&intel_nhm_support,
&gen_ia32_support, /* must always be last for x86-64 */
#endif
#ifdef CONFIG_PFMLIB_ARCH_I386
&i386_pii_support,
&i386_ppro_support,
&i386_p6_support,
&i386_pm_support,
&coreduo_support,
&amd64_support,
&pentium4_support,
&core_support,
&intel_atom_support,
&intel_nhm_support,
&gen_ia32_support, /* must always be last for i386 */
#endif
#ifdef CONFIG_PFMLIB_ARCH_MIPS64
&generic_mips64_support,
#endif
#ifdef CONFIG_PFMLIB_ARCH_SICORTEX
&sicortex_support,
#endif
#ifdef CONFIG_PFMLIB_ARCH_POWERPC
&gen_powerpc_support,
#endif
#ifdef CONFIG_PFMLIB_ARCH_SPARC
&sparc_support,
#endif
#ifdef CONFIG_PFMLIB_ARCH_CRAYX2
&crayx2_support,
#endif
#ifdef CONFIG_PFMLIB_CELL
&cell_support,
#endif
NULL
};
/*
* contains runtime configuration options for the library.
* mostly for debug purposes.
*/
pfm_config_t pfm_config = {
.current = NULL
};
int forced_pmu = PFMLIB_NO_PMU;
/*
* check environment variables for:
* LIBPFM_VERBOSE : enable verbose output (must be 1)
* LIBPFM_DEBUG : enable debug output (must be 1)
*/
static void
pfm_check_debug_env(void)
{
char *str;
libpfm_fp = stderr;
str = getenv("LIBPFM_VERBOSE");
if (str && *str >= '0' && *str <= '9') {
pfm_config.options.pfm_verbose = *str - '0';
pfm_config.options_env_set = 1;
}
str = getenv("LIBPFM_DEBUG");
if (str && *str >= '0' && *str <= '9') {
pfm_config.options.pfm_debug = *str - '0';
pfm_config.options_env_set = 1;
}
str = getenv("LIBPFM_DEBUG_STDOUT");
if (str)
libpfm_fp = stdout;
str = getenv("LIBPFM_FORCE_PMU");
if (str)
forced_pmu = atoi(str);
}
int
pfm_initialize(void)
{
pfm_pmu_support_t **p = supported_pmus;
int ret;
pfm_check_debug_env();
/*
* syscall mapping, no failure on error
*/
pfm_init_syscalls();
while(*p) {
DPRINT("trying %s\n", (*p)->pmu_name);
/*
* check for forced_pmu
* pmu_type can never be zero
*/
if ((*p)->pmu_type == forced_pmu) {
__pfm_vbprintf("PMU forced to %s\n", (*p)->pmu_name);
goto found;
}
if (forced_pmu == PFMLIB_NO_PMU && (*p)->pmu_detect() == PFMLIB_SUCCESS)
goto found;
p++;
}
return PFMLIB_ERR_NOTSUPP;
found:
DPRINT("found %s\n", (*p)->pmu_name);
/*
* run a few sanity checks
*/
if ((*p)->pmc_count >= PFMLIB_MAX_PMCS)
return PFMLIB_ERR_NOTSUPP;
if ((*p)->pmd_count >= PFMLIB_MAX_PMDS)
return PFMLIB_ERR_NOTSUPP;
if ((*p)->pmu_init) {
ret = (*p)->pmu_init();
if (ret != PFMLIB_SUCCESS)
return ret;
}
pfm_current = *p;
return PFMLIB_SUCCESS;
}
int
pfm_set_options(pfmlib_options_t *opt)
{
if (opt == NULL)
return PFMLIB_ERR_INVAL;
/*
* environment variables override program presets
*/
if (pfm_config.options_env_set == 0)
pfm_config.options = *opt;
return PFMLIB_SUCCESS;
}
/*
* return the name corresponding to the pmu type. Only names
* of PMU actually compiled in the library will be returned.
*/
int
pfm_get_pmu_name_bytype(int type, char *name, size_t maxlen)
{
pfm_pmu_support_t **p = supported_pmus;
if (name == NULL || maxlen < 1) return PFMLIB_ERR_INVAL;
while (*p) {
if ((*p)->pmu_type == type) goto found;
p++;
}
return PFMLIB_ERR_INVAL;
found:
strncpy(name, (*p)->pmu_name, maxlen-1);
/* make sure the string is null terminated */
name[maxlen-1] = '\0';
return PFMLIB_SUCCESS;
}
int
pfm_list_supported_pmus(int (*pf)(const char *fmt,...))
{
pfm_pmu_support_t **p;
if (pf == NULL) return PFMLIB_ERR_INVAL;
(*pf)("supported PMU models: ");
for (p = supported_pmus; *p; p++) {
(*pf)("[%s] ", (*p)->pmu_name);;
}
(*pf)("\ndetected host PMU: %s\n", pfm_current ? pfm_current->pmu_name : "not detected yet");
return PFMLIB_SUCCESS;
}
int
pfm_get_pmu_name(char *name, int maxlen)
{
if (PFMLIB_INITIALIZED() == 0) return PFMLIB_ERR_NOINIT;
if (name == NULL || maxlen < 1) return PFMLIB_ERR_INVAL;
strncpy(name, pfm_current->pmu_name, maxlen-1);
name[maxlen-1] = '\0';
return PFMLIB_SUCCESS;
}
int
pfm_get_pmu_type(int *type)
{
if (PFMLIB_INITIALIZED() == 0) return PFMLIB_ERR_NOINIT;
if (type == NULL) return PFMLIB_ERR_INVAL;
*type = pfm_current->pmu_type;
return PFMLIB_SUCCESS;
}
/*
* boolean return value
*/
int
pfm_is_pmu_supported(int type)
{
pfm_pmu_support_t **p = supported_pmus;
if (PFMLIB_INITIALIZED() == 0) return PFMLIB_ERR_NOINIT;
while (*p) {
if ((*p)->pmu_type == type) return PFMLIB_SUCCESS;
p++;
}
return PFMLIB_ERR_NOTSUPP;
}
int
pfm_force_pmu(int type)
{
pfm_pmu_support_t **p = supported_pmus;
while (*p) {
if ((*p)->pmu_type == type) goto found;
p++;
}
return PFMLIB_ERR_NOTSUPP;
found:
pfm_current = *p;
return PFMLIB_SUCCESS;
}
int
pfm_find_event_byname(const char *n, unsigned int *idx)
{
char *p, *e;
unsigned int i;
size_t len;
if (PFMLIB_INITIALIZED() == 0)
return PFMLIB_ERR_NOINIT;
if (n == NULL || idx == NULL)
return PFMLIB_ERR_INVAL;
/*
* this function ignores any ':' separator
*/
p = strchr(n, ':');
if (!p)
len = strlen(n);
else
len = p - n;
/*
* we do case insensitive comparisons
*
* event names must match completely
*/
for(i=0; i < pfm_current->pme_count; i++) {
e = pfm_current->get_event_name(i);
if (!e)
continue;
if (!strncasecmp(e, n, len)
&& len == strlen(e))
goto found;
}
return PFMLIB_ERR_NOTFOUND;
found:
*idx = i;
return PFMLIB_SUCCESS;
}
int
pfm_find_event_bycode(int code, unsigned int *idx)
{
pfmlib_regmask_t impl_cnt;
unsigned int i, j, num_cnt;
int code2;
if (PFMLIB_INITIALIZED() == 0) return PFMLIB_ERR_NOINIT;
if (idx == NULL) return PFMLIB_ERR_INVAL;
if (pfm_current->flags & PFMLIB_MULT_CODE_EVENT) {
pfm_current->get_impl_counters(&impl_cnt);
num_cnt = pfm_current->num_cnt;
for(i=0; i < pfm_current->pme_count; i++) {
for(j=0; num_cnt; j++) {
if (pfm_regmask_isset(&impl_cnt, j)) {
pfm_current->get_event_code(i, j, &code2);
if (code2 == code)
goto found;
num_cnt--;
}
}
}
} else {
for(i=0; i < pfm_current->pme_count; i++) {
pfm_current->get_event_code(i, PFMLIB_CNT_FIRST, &code2);
if (code2 == code) goto found;
}
}
return PFMLIB_ERR_NOTFOUND;
found:
*idx = i;
return PFMLIB_SUCCESS;
}
int
pfm_find_event(const char *v, unsigned int *ev)
{
unsigned long number;
char *endptr = NULL;
int ret = PFMLIB_ERR_INVAL;
if (PFMLIB_INITIALIZED() == 0)
return PFMLIB_ERR_NOINIT;
if (v == NULL || ev == NULL)
return PFMLIB_ERR_INVAL;
if (isdigit((int)*v)) {
number = strtoul(v,&endptr, 0);
/* check for errors */
if (*endptr!='\0')
return PFMLIB_ERR_INVAL;
if (number <= INT_MAX) {
int the_int_number = (int)number;
ret = pfm_find_event_bycode(the_int_number, ev);
}
} else
ret = pfm_find_event_byname(v, ev);
return ret;
}
int
pfm_find_event_bycode_next(int code, unsigned int i, unsigned int *next)
{
int code2;
if (PFMLIB_INITIALIZED() == 0)
return PFMLIB_ERR_NOINIT;
if (!next)
return PFMLIB_ERR_INVAL;
for(++i; i < pfm_current->pme_count; i++) {
pfm_current->get_event_code(i, PFMLIB_CNT_FIRST, &code2);
if (code2 == code) goto found;
}
return PFMLIB_ERR_NOTFOUND;
found:
*next = i;
return PFMLIB_SUCCESS;
}
static int
pfm_do_find_event_mask(unsigned int ev, const char *str, unsigned int *mask_idx)
{
unsigned int i, c, num_masks = 0;
unsigned long mask_val = -1;
char *endptr = NULL;
char *mask_name;
/* empty mask name */
if (*str == '\0')
return PFMLIB_ERR_UMASK;
num_masks = pfm_num_masks(ev);
for (i = 0; i < num_masks; i++) {
mask_name = pfm_current->get_event_mask_name(ev, i);
if (!mask_name)
continue;
if (strcasecmp(mask_name, str))
continue;
*mask_idx = i;
return PFMLIB_SUCCESS;
}
/* don't give up yet; check for a exact numerical value */
mask_val = strtoul(str, &endptr, 0);
if (mask_val != ULONG_MAX && endptr && *endptr == '\0') {
for (i = 0; i < num_masks; i++) {
pfm_current->get_event_mask_code(ev, i, &c);
if (mask_val == c) {
*mask_idx = i;
return PFMLIB_SUCCESS;
}
}
}
return PFMLIB_ERR_UMASK;
}
int
pfm_find_event_mask(unsigned int ev, const char *str, unsigned int *mask_idx)
{
if (PFMLIB_INITIALIZED() == 0)
return PFMLIB_ERR_NOINIT;
if (str == NULL || mask_idx == NULL || ev >= pfm_current->pme_count)
return PFMLIB_ERR_INVAL;
return pfm_do_find_event_mask(ev, str, mask_idx);
}
/*
* check if unit mask is not already present
*/
static inline int
pfm_check_duplicates(pfmlib_event_t *e, unsigned int u)
{
unsigned int j;
for(j=0; j < e->num_masks; j++) {
if (e->unit_masks[j] == u)
return PFMLIB_ERR_UMASK;
}
return PFMLIB_SUCCESS;
}
static int
pfm_add_numeric_masks(pfmlib_event_t *e, const char *str)
{
unsigned int i, j, c;
unsigned int num_masks = 0;
unsigned long mask_val = -1, m = 0;
char *endptr = NULL;
int ret = PFMLIB_ERR_UMASK;
/* empty mask name */
if (*str == '\0')
return PFMLIB_ERR_UMASK;
num_masks = pfm_num_masks(e->event);
/*
* add to the existing list of unit masks
*/
j = e->num_masks;
/*
* use unsigned long to benefit from radix wildcard
* and error checking of strtoul()
*/
mask_val = strtoul(str, &endptr, 0);
if (endptr && *endptr != '\0')
return PFMLIB_ERR_UMASK;
/*
* look for a numerical match
*/
for (i = 0; i < num_masks; i++) {
pfm_current->get_event_mask_code(e->event, i, &c);
if ((mask_val & c) == (unsigned long)c) {
/* ignore duplicates */
if (pfm_check_duplicates(e, i) == PFMLIB_SUCCESS) {
if (j == PFMLIB_MAX_MASKS_PER_EVENT) {
ret = PFMLIB_ERR_TOOMANY;
break;
}
e->unit_masks[j++] = i;
}
m |= c;
}
}
/*
* all bits accounted for
*/
if (mask_val == m) {
e->num_masks = j;
return PFMLIB_SUCCESS;
}
/*
* extra bits left over;
* reset and flag error
*/
for (i = e->num_masks; i < j; i++)
e->unit_masks[i] = 0;
return ret;
}
int
pfm_get_event_name(unsigned int i, char *name, size_t maxlen)
{
size_t l, j;
char *str;
if (PFMLIB_INITIALIZED() == 0)
return PFMLIB_ERR_NOINIT;
if (i >= pfm_current->pme_count || name == NULL || maxlen < 1)
return PFMLIB_ERR_INVAL;
str = pfm_current->get_event_name(i);
if (!str)
return PFMLIB_ERR_BADHOST;
l = strlen(str);
/*
* we fail if buffer is too small, simply because otherwise we
* get partial names which are useless for subsequent calls
* users mus invoke pfm_get_event_name_max_len() to correctly size
* the buffer for this call
*/
if ((maxlen-1) < l)
return PFMLIB_ERR_INVAL;
for(j=0; j < l; j++)
name[j] = (char)toupper(str[j]);
name[l] = '\0';
return PFMLIB_SUCCESS;
}
int
pfm_get_event_code(unsigned int i, int *code)
{
if (PFMLIB_INITIALIZED() == 0) return PFMLIB_ERR_NOINIT;
if (i >= pfm_current->pme_count || code == NULL) return PFMLIB_ERR_INVAL;
return pfm_current->get_event_code(i, PFMLIB_CNT_FIRST, code);
}
int
pfm_get_event_code_counter(unsigned int i, unsigned int cnt, int *code)
{
if (PFMLIB_INITIALIZED() == 0) return PFMLIB_ERR_NOINIT;
if (i >= pfm_current->pme_count || code == NULL) return PFMLIB_ERR_INVAL;
return pfm_current->get_event_code(i, cnt, code);
}
int
pfm_get_event_counters(unsigned int i, pfmlib_regmask_t *counters)
{
if (PFMLIB_INITIALIZED() == 0) return PFMLIB_ERR_NOINIT;
if (i >= pfm_current->pme_count) return PFMLIB_ERR_INVAL;
pfm_current->get_event_counters(i, counters);
return PFMLIB_SUCCESS;
}
int
pfm_get_event_mask_name(unsigned int ev, unsigned int mask, char *name, size_t maxlen)
{
char *str;
unsigned int num;
size_t l, j;
if (PFMLIB_INITIALIZED() == 0)
return PFMLIB_ERR_NOINIT;
if (ev >= pfm_current->pme_count || name == NULL || maxlen < 1)
return PFMLIB_ERR_INVAL;
num = pfm_num_masks(ev);
if (num == 0)
return PFMLIB_ERR_NOTSUPP;
if (mask >= num)
return PFMLIB_ERR_INVAL;
str = pfm_current->get_event_mask_name(ev, mask);
if (!str)
return PFMLIB_ERR_BADHOST;
l = strlen(str);
if (l >= (maxlen-1))
return PFMLIB_ERR_FULL;
strcpy(name, str);
/*
* present nice uniform names
*/
l = strlen(name);
for(j=0; j < l; j++)
if (islower(name[j]))
name[j] = (char)toupper(name[j]);
return PFMLIB_SUCCESS;
}
int
pfm_get_num_events(unsigned int *count)
{
if (PFMLIB_INITIALIZED() == 0) return PFMLIB_ERR_NOINIT;
if (count == NULL) return PFMLIB_ERR_INVAL;
*count = pfm_current->pme_count;
return PFMLIB_SUCCESS;
}
int
pfm_get_num_event_masks(unsigned int ev, unsigned int *count)
{
if (PFMLIB_INITIALIZED() == 0)
return PFMLIB_ERR_NOINIT;
if (ev >= pfm_current->pme_count || count == NULL)
return PFMLIB_ERR_INVAL;
*count = pfm_num_masks(ev);
return PFMLIB_SUCCESS;
}
#if 0
/*
* check that the unavailable PMCs registers correspond
* to implemented PMC registers
*/
static int
pfm_check_unavail_pmcs(pfmlib_regmask_t *pmcs)
{
pfmlib_regmask_t impl_pmcs;
pfm_current->get_impl_pmcs(&impl_pmcs);
unsigned int i;
for (i=0; i < PFMLIB_REG_BV; i++) {
if ((pmcs->bits[i] & impl_pmcs.bits[i]) != pmcs->bits[i])
return PFMLIB_ERR_INVAL;
}
return PFMLIB_SUCCESS;
}
#endif
/*
* we do not check if pfp_unavail_pmcs contains only implemented PMC
* registers. In other words, invalid registers are ignored
*/
int
pfm_dispatch_events(
pfmlib_input_param_t *inp, void *model_in,
pfmlib_output_param_t *outp, void *model_out)
{
unsigned count;
unsigned int i;
int ret;
if (PFMLIB_INITIALIZED() == 0)
return PFMLIB_ERR_NOINIT;
/* at least one input and one output set must exist */
if (!inp && !model_in)
return PFMLIB_ERR_INVAL;
if (!outp && !model_out)
return PFMLIB_ERR_INVAL;
if (!inp)
count = 0;
else if (inp->pfp_dfl_plm == 0)
/* the default priv level must be set to something */
return PFMLIB_ERR_INVAL;
else if (inp->pfp_event_count >= PFMLIB_MAX_PMCS)
return PFMLIB_ERR_INVAL;
else if (inp->pfp_event_count > pfm_current->num_cnt)
return PFMLIB_ERR_NOASSIGN;
else
count = inp->pfp_event_count;
/*
* check that event and unit masks descriptors are correct
*/
for (i=0; i < count; i++) {
ret = __pfm_check_event(inp->pfp_events+i);
if (ret != PFMLIB_SUCCESS)
return ret;
}
/* reset output data structure */
if (outp)
memset(outp, 0, sizeof(*outp));
return pfm_current->dispatch_events(inp, model_in, outp, model_out);
}
/*
* more or less obosleted by pfm_get_impl_counters()
*/
int
pfm_get_num_counters(unsigned int *num)
{
if (PFMLIB_INITIALIZED() == 0) return PFMLIB_ERR_NOINIT;
if (num == NULL) return PFMLIB_ERR_INVAL;
*num = pfm_current->num_cnt;
return PFMLIB_SUCCESS;
}
int
pfm_get_num_pmcs(unsigned int *num)
{
if (PFMLIB_INITIALIZED() == 0) return PFMLIB_ERR_NOINIT;
if (num == NULL) return PFMLIB_ERR_INVAL;
*num = pfm_current->pmc_count;
return PFMLIB_SUCCESS;
}
int
pfm_get_num_pmds(unsigned int *num)
{
if (PFMLIB_INITIALIZED() == 0) return PFMLIB_ERR_NOINIT;
if (num == NULL) return PFMLIB_ERR_INVAL;
*num = pfm_current->pmd_count;
return PFMLIB_SUCCESS;
}
int
pfm_get_impl_pmcs(pfmlib_regmask_t *impl_pmcs)
{
if (PFMLIB_INITIALIZED() == 0) return PFMLIB_ERR_NOINIT;
if (impl_pmcs == NULL) return PFMLIB_ERR_INVAL;
memset(impl_pmcs , 0, sizeof(*impl_pmcs));
pfm_current->get_impl_pmcs(impl_pmcs);
return PFMLIB_SUCCESS;
}
int
pfm_get_impl_pmds(pfmlib_regmask_t *impl_pmds)
{
if (PFMLIB_INITIALIZED() == 0) return PFMLIB_ERR_NOINIT;
if (impl_pmds == NULL) return PFMLIB_ERR_INVAL;
memset(impl_pmds, 0, sizeof(*impl_pmds));
pfm_current->get_impl_pmds(impl_pmds);
return PFMLIB_SUCCESS;
}
int
pfm_get_impl_counters(pfmlib_regmask_t *impl_counters)
{
if (PFMLIB_INITIALIZED() == 0) return PFMLIB_ERR_NOINIT;
if (impl_counters == NULL) return PFMLIB_ERR_INVAL;
memset(impl_counters, 0, sizeof(*impl_counters));
pfm_current->get_impl_counters(impl_counters);
return PFMLIB_SUCCESS;
}
int
pfm_get_hw_counter_width(unsigned int *width)
{
if (PFMLIB_INITIALIZED() == 0) return PFMLIB_ERR_NOINIT;
if (width == NULL) return PFMLIB_ERR_INVAL;
pfm_current->get_hw_counter_width(width);
return PFMLIB_SUCCESS;
}
/* sorry, only English supported at this point! */
static char *pfmlib_err_list[]=
{
"success",
"not supported",
"invalid parameters",
"pfmlib not initialized",
"event not found",
"cannot assign events to counters",
"buffer is full or too small",
"event used more than once",
"invalid model specific magic number",
"invalid combination of model specific features",
"incompatible event sets",
"incompatible events combination",
"too many events or unit masks",
"code range too big",
"empty code range",
"invalid code range",
"too many code ranges",
"invalid data range",
"too many data ranges",
"not supported by host cpu",
"code range is not bundle-aligned",
"code range requires some flags in rr_flags",
"invalid or missing unit mask",
"out of memory"
};
static size_t pfmlib_err_count = sizeof(pfmlib_err_list)/sizeof(char *);
char *
pfm_strerror(int code)
{
code = -code;
if (code <0 || code >= pfmlib_err_count) return "unknown error code";
return pfmlib_err_list[code];
}
int
pfm_get_version(unsigned int *version)
{
if (version == NULL) return PFMLIB_ERR_INVAL;
*version = PFMLIB_VERSION;
return 0;
}
int
pfm_get_max_event_name_len(size_t *len)
{
unsigned int i, j, num_masks;
size_t max = 0, l;
char *str;
if (PFMLIB_INITIALIZED() == 0)
return PFMLIB_ERR_NOINIT;
if (len == NULL)
return PFMLIB_ERR_INVAL;
for(i=0; i < pfm_current->pme_count; i++) {
str = pfm_current->get_event_name(i);
if (!str)
continue;
l = strlen(str);
if (l > max) max = l;
num_masks = pfm_num_masks(i);
/*
* we need to add up all length because unit masks can
* be combined typically. We add 1 to account for ':'
* which is inserted as the unit mask separator
*/
for (j = 0; j < num_masks; j++) {
str = pfm_current->get_event_mask_name(i, j);
if (!str)
continue;
l += 1 + strlen(str);
}
if (l > max) max = l;
}
*len = max;
return PFMLIB_SUCCESS;
}
/*
* return the index of the event that counts elapsed cycles
*/
int
pfm_get_cycle_event(pfmlib_event_t *e)
{
if (PFMLIB_INITIALIZED() == 0)
return PFMLIB_ERR_NOINIT;
if (e == NULL)
return PFMLIB_ERR_INVAL;
if (!pfm_current->get_cycle_event)
return PFMLIB_ERR_NOTSUPP;
memset(e, 0, sizeof(*e));
return pfm_current->get_cycle_event(e);
}
/*
* return the index of the event that retired instructions
*/
int
pfm_get_inst_retired_event(pfmlib_event_t *e)
{
if (PFMLIB_INITIALIZED() == 0)
return PFMLIB_ERR_NOINIT;
if (e == NULL)
return PFMLIB_ERR_INVAL;
if (!pfm_current->get_inst_retired_event)
return PFMLIB_ERR_NOTSUPP;
memset(e, 0, sizeof(*e));
return pfm_current->get_inst_retired_event(e);
}
int
pfm_get_event_description(unsigned int i, char **str)
{
if (PFMLIB_INITIALIZED() == 0) return PFMLIB_ERR_NOINIT;
if (i >= pfm_current->pme_count || str == NULL) return PFMLIB_ERR_INVAL;
if (pfm_current->get_event_desc == NULL) {
*str = strdup("no description available");
return PFMLIB_SUCCESS;
}
return pfm_current->get_event_desc(i, str);
}
int
pfm_get_event_mask_description(unsigned int event_idx, unsigned int mask_idx, char **desc)
{
if (PFMLIB_INITIALIZED() == 0) return PFMLIB_ERR_NOINIT;
if (event_idx >= pfm_current->pme_count || desc == NULL) return PFMLIB_ERR_INVAL;
if (pfm_current->get_event_mask_desc == NULL) {
*desc = strdup("no description available");
return PFMLIB_SUCCESS;
}
if (mask_idx >= pfm_current->get_num_event_masks(event_idx))
return PFMLIB_ERR_INVAL;
return pfm_current->get_event_mask_desc(event_idx, mask_idx, desc);
}
int
pfm_get_event_mask_code(unsigned int event_idx, unsigned int mask_idx, unsigned int *code)
{
if (PFMLIB_INITIALIZED() == 0) return PFMLIB_ERR_NOINIT;
if (event_idx >= pfm_current->pme_count || code == NULL) return PFMLIB_ERR_INVAL;
if (pfm_current->get_event_mask_code == NULL) {
*code = 0;
return PFMLIB_SUCCESS;
}
if (mask_idx >= pfm_current->get_num_event_masks(event_idx))
return PFMLIB_ERR_INVAL;
return pfm_current->get_event_mask_code(event_idx, mask_idx, code);
}
int
pfm_get_full_event_name(pfmlib_event_t *e, char *name, size_t maxlen)
{
char *str;
size_t l, j;
int ret;
if (PFMLIB_INITIALIZED() == 0)
return PFMLIB_ERR_NOINIT;
if (e == NULL || name == NULL || maxlen < 1)
return PFMLIB_ERR_INVAL;
ret = __pfm_check_event(e);
if (ret != PFMLIB_SUCCESS)
return ret;
/*
* make sure the string is at least empty
* important for programs that do not check return value
* from this function!
*/
*name = '\0';
str = pfm_current->get_event_name(e->event);
if (!str)
return PFMLIB_ERR_BADHOST;
l = strlen(str);
if (l > (maxlen-1))
return PFMLIB_ERR_FULL;
strcpy(name, str);
maxlen -= l + 1;
for(j=0; j < e->num_masks; j++) {
str = pfm_current->get_event_mask_name(e->event, e->unit_masks[j]);
if (!str)
continue;
l = strlen(str);
if (l > (maxlen-1))
return PFMLIB_ERR_FULL;
strcat(name, ":");
strcat(name, str);
maxlen -= l + 1;
}
/*
* present nice uniform names
*/
l = strlen(name);
for(j=0; j < l; j++)
if (islower(name[j]))
name[j] = (char)toupper(name[j]);
return PFMLIB_SUCCESS;
}
int
pfm_find_full_event(const char *v, pfmlib_event_t *e)
{
char *str, *p, *q;
unsigned int j, mask;
int ret = PFMLIB_SUCCESS;
if (PFMLIB_INITIALIZED() == 0)
return PFMLIB_ERR_NOINIT;
if (v == NULL || e == NULL)
return PFMLIB_ERR_INVAL;
memset(e, 0, sizeof(*e));
/*
* must copy string because we modify it when parsing
*/
str = strdup(v);
if (!str)
return PFMLIB_ERR_NOMEM;
/*
* find event. this function ignores ':' separator
*/
ret = pfm_find_event_byname(str, &e->event);
if (ret)
goto error;
/*
* get number of unit masks for event
*/
j = pfm_num_masks(e->event);
/*
* look for colon (unit mask separator)
*/
p = strchr(str, ':');
/* If no unit masks available and none specified, we're done */
if ((j == 0) && (p == NULL)) {
free(str);
return PFMLIB_SUCCESS;
}
ret = PFMLIB_ERR_UMASK;
/*
* error if:
* - event has no unit mask and at least one is passed
*/
if (p && !j)
goto error;
/*
* error if:
* - event has unit masks, no default unit mask, and none is passed
*/
if (j && !p) {
if (pfm_current->has_umask_default
&& pfm_current->has_umask_default(e->event)) {
free(str);
return PFMLIB_SUCCESS;
}
goto error;
}
/* skip : */
p++;
/*
* separator is passed but there is nothing behind it
*/
if (!*p)
goto error;
/* parse unit masks */
for( q = p; q ; p = q) {
q = strchr(p,':');
if (q)
*q++ = '\0';
/*
* text or exact unit mask value match
*/
ret = pfm_do_find_event_mask(e->event, p, &mask);
if (ret == PFMLIB_ERR_UMASK) {
ret = pfm_add_numeric_masks(e, p);
if (ret != PFMLIB_SUCCESS)
break;
} else if (ret == PFMLIB_SUCCESS) {
/*
* ignore duplicates
*/
ret = pfm_check_duplicates(e, mask);
if (ret != PFMLIB_SUCCESS) {
ret = PFMLIB_SUCCESS;
continue;
}
if (e->num_masks == PFMLIB_MAX_MASKS_PER_EVENT) {
ret = PFMLIB_ERR_TOOMANY;
break;
}
e->unit_masks[e->num_masks] = mask;
e->num_masks++;
}
}
error:
free(str);
return ret;
}
| 20.960504 | 94 | 0.688209 | [
"model"
] |
0d64d170f471453f9ecd93c5688122a629f76c57 | 45,488 | h | C | sandbox/dpfusion/Group.h | rcodin/polymage | 653487be125dec4950d1c65da4f736fa05fb938f | [
"Apache-2.0"
] | null | null | null | sandbox/dpfusion/Group.h | rcodin/polymage | 653487be125dec4950d1c65da4f736fa05fb938f | [
"Apache-2.0"
] | null | null | null | sandbox/dpfusion/Group.h | rcodin/polymage | 653487be125dec4950d1c65da4f736fa05fb938f | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <Python.h>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <algorithm>
#include <queue>
#include <regex>
#include <fstream>
#include <string>
#include <boost/multiprecision/cpp_int.hpp>
#include <functional>
#include <cctype>
#include <locale>
#include <math.h>
#include <map>
#include <numeric>
using boost::multiprecision::uint128_t;
using namespace boost;
using namespace std;
#ifndef __GROUP_H__
#define __GROUP_H__
uint64_t globalID = -1, runningTime = 0, maxID = 0, foundInDict = 0;
struct uint128Hasher
{
uint64_t operator()(const uint128_t i) const
{
//printf ("hash_id %ld\n", g->hashID());
return (uint64_t)i;
}
};
struct uint128Comparer
{
uint64_t operator()(const uint128_t i, const uint128_t j) const
{
//printf ("hash_id %ld\n", g->hashID());
return i < j;
}
};
class OptGroup;
class Group
{
public:
struct GroupComparer
{
bool operator()(const Group* g1, const Group* g2) const
{
return g1->hashID() < g2->hashID();
}
};
struct GroupHasher
{
uint64_t operator()(const Group* g1) const
{
return (uint64_t)g1->hashID();
}
};
protected:
uint64_t id;
uint128_t hash_id;
vector<uint128_t> next_groups_int;
vector<uint128_t> prev_groups_int;
bool is_last;
PyObject* pyGroup;
PyObject* comps;
set<Group*, Group::GroupComparer> next_groups, prev_groups;
set<OptGroup*, Group::GroupComparer> parent_groups;
public:
static std::unordered_map<uint128_t, Group*, uint128Hasher> hashIDToGroup;
Group ()
{
setHashID ();
pyGroup = NULL;
comps = NULL;
}
Group (PyObject* pyGroup, PyObject* comps)
{
this->pyGroup = pyGroup;
this->comps = comps;
setHashID ();
}
Group (uint128_t hash_id)
{
setHashID (hash_id);
pyGroup = NULL;
comps = NULL;
}
Group (set<Group*, GroupComparer>& next_groups, set<Group*, GroupComparer>& prev_groups)
{
this->next_groups = next_groups;
this->prev_groups = prev_groups;
if (nextGroups().size() == 0)
is_last = true;
else
is_last = false;
id = ++globalID;
setHashID ();
}
void setHashID ()
{
id = ++globalID;
if (id < maxID)
{
hash_id = 1L;
hash_id = (hash_id << id);
hashIDToGroup[hash_id] = this;
}
}
PyObject* getPyGroup ()
{
return pyGroup;
}
PyObject* getComps ()
{
return comps;
}
PyObject* getCompAtIndex (int i)
{
return PyList_GetItem (comps, i);
}
set<OptGroup*, GroupComparer>& parentGroups()
{
return parent_groups;
}
set<Group*, GroupComparer>& nextGroups()
{
return next_groups;
}
set<Group*, GroupComparer>& prevGroups ()
{
return prev_groups;
}
void setHashID (uint128_t _hash_id)
{
hash_id = _hash_id;
}
uint128_t hashID () const
{
return hash_id;
}
bool isSingleGroup () const
{
if (hash_id && (!(hash_id & (hash_id-1))))
return true;
return false;
}
vector<uint128_t>* prevGroupsHashID ()
{
if (prev_groups_int.size () != 0)
{
return &prev_groups_int;
}
for (auto it = prevGroups().begin(); it != prevGroups().end(); ++it)
{
prev_groups_int.push_back ((*it)->hashID());
}
return &prev_groups_int;
}
vector<uint128_t>* nextGroupsHashID ()
{
if (next_groups_int.size () != 0)
{
return &next_groups_int;
}
for (auto it = nextGroups().begin(); it != nextGroups().end(); ++it)
{
next_groups_int.push_back ((*it)->hashID());
}
return &next_groups_int;
}
bool operator==(const Group& other) const
{
return other.hash_id == hash_id;
}
};
class OptGroup : public Group
{
protected:
set<OptGroup*, Group::GroupComparer> children;
OptGroup (uint128_t hash_id) : Group (hash_id)
{
//setChildren ();
}
public:
static std::unordered_map<uint128_t, OptGroup*, uint128Hasher> optHashIDToGroup;
static std::unordered_map<uint128_t, OptGroup*, uint128Hasher> parentOptGroupsToHashID;
static vector <OptGroup*> vectorOptGroups;
//Find if removing a child will make graph disconnected
//If true, then fill the vector components with 2 disconnected components
bool isDisconnected2 (OptGroup* toRemove, std::vector< std::vector <OptGroup*> >& components)
{
//Using Kosaraju’s DFS to find if removing the child would make
//the group disconnected
////std::cout<<"isDisconnected "<< std::bitset<41>((uint64_t)(hashID())) << " toremove " <<std::bitset<41>((uint64_t)toRemove->hashID()) << std::endl;
stack<OptGroup*> s;
unordered_map<uint128_t, bool, uint128Hasher> visited;
OptGroup* start = NULL;
bool _isDisconnected = false;
for (auto it = children.begin(); it != children.end (); it++)
{
if ((*it)->hashID() != toRemove->hashID())
start = *it;
visited[(*it)->hashID ()] = false;
}
////std::cout<<"start " << std::bitset<41>((uint64_t)(start->hashID()))<<std::endl;
s.push (start);
while (s.size () != 0)
{
OptGroup* g = s.top ();
s.pop ();
visited[g->hashID()] = true;
for (auto it = g->nextGroups ().begin ();
it != g->nextGroups().end (); it++)
{
if (((*it)->hashID() & hashID ()) == (*it)->hashID () &&
(*it)->hashID () != toRemove->hashID () &&
visited[(*it)->hashID()] == false)
{
s.push ((OptGroup*)*it);
}
}
}
unordered_map<uint128_t, bool, uint128Hasher> reverseVisited;
for (auto it = children.begin(); it != children.end (); it++)
{
reverseVisited[(*it)->hashID ()] = false;
}
s.push (start);
while (s.size () != 0)
{
OptGroup* g = s.top ();
s.pop ();
reverseVisited[g->hashID ()] = true;
for (auto it = g->prevGroups ().begin ();
it != g->prevGroups().end (); it++)
{
if (((*it)->hashID() & hashID ()) == (*it)->hashID () &&
(*it)->hashID () != toRemove->hashID () &&
reverseVisited[(*it)->hashID()] == false)
{
s.push ((OptGroup*)*it);
}
}
}
for (auto it = children.begin (); it != children.end (); it++)
{
if ((*it)->hashID() != toRemove->hashID ())
{
if (visited[(*it)->hashID ()] == false &&
reverseVisited[(*it)->hashID()] == false)
{
_isDisconnected = true;
components[1].push_back (*it);
}
else
{
components[0].push_back (*it);
}
}
}
return _isDisconnected;
}
bool allPrevGroupsAreNotChild (OptGroup* group)
{
for (auto it = group->prevGroups().begin (); it != group->prevGroups().end(); it++)
{
if (((*it)->hashID () & hashID()) == (*it)->hashID ())
{
return false;
break;
}
}
return true;
}
bool allNextGroupsAreNotChild (OptGroup* group)
{
for (auto it = group->nextGroups().begin (); it != group->nextGroups().end(); it++)
{
if (((*it)->hashID () & hashID()) == (*it)->hashID ())
{
return false;
break;
}
}
return true;
}
bool allPrevGroupsAreChild (OptGroup* group)
{
for (auto it = group->prevGroups().begin (); it != group->prevGroups().end(); it++)
{
if (((*it)->hashID () & hashID()) != (*it)->hashID ())
{
return false;
break;
}
}
return true;
}
bool allNextGroupsAreChild (OptGroup* group)
{
for (auto it = group->nextGroups().begin (); it != group->nextGroups().end(); it++)
{
if (((*it)->hashID () & hashID()) != (*it)->hashID ())
{
return false;
break;
}
}
return true;
}
bool isDisconnected (OptGroup* toRemove, vector<unordered_set <OptGroup*> >& components)
{
//If either all of toRemove's previous or next groups are not in this group
//Then graph will not become disconnected.
////std::cout<<"isDisconnected allPrevGroupsNot " << allPrevGroupsAreNotChild (toRemove) << " " << allNextGroupsAreNotChild (toRemove) << std::endl;
if (//allPrevGroupsAreNotChild (toRemove) ||
allNextGroupsAreNotChild (toRemove))
return false;
vector<OptGroup*> source_vertices;
unordered_map<uint128_t, bool, uint128Hasher> visited;
//vector of vertices reachable from one vertex using nextGroups
unordered_map<OptGroup*, unordered_set <OptGroup*> > reachable_vertices;
//vector <unordered_set <OptGroup*> > _components;
for (auto it = children.begin(); it != children.end (); it++)
{
stack<OptGroup*> s;
if ((*it)->hashID() == toRemove->hashID())
continue;
unordered_set <OptGroup*> reachable_set;
s.push ((OptGroup*)*it);
while (s.size () != 0)
{
OptGroup* g = s.top ();
s.pop ();
for (auto it2 = g->nextGroups ().begin ();
it2 != g->nextGroups().end (); it2++)
{
if (((*it2)->hashID() & hashID ()) == (*it2)->hashID () &&
(*it2)->hashID () != toRemove->hashID ())
{
reachable_set.insert ((OptGroup*)*it2);
s.push ((OptGroup*)*it2);
}
}
}
reachable_vertices [*it] = reachable_set;
}
////std::cout<< "isDisconnected reachable_vertices: " << std::endl;
for (auto it = reachable_vertices.begin();
it != reachable_vertices.end(); it++)
{
////std::cout<< std::bitset<41>((uint64_t)it->first->hashID ())<<std::endl;
for (auto it2 = it->second.begin(); it2 != it->second.end(); it2++)
{
////std::cout<< " " << std::bitset <41>((uint64_t) (*it2)->hashID ())<< std::endl;
}
}
unordered_map <OptGroup*, int> group_to_set_index;
for (auto it = reachable_vertices.begin();
it != reachable_vertices.end(); it++)
{
unordered_set <OptGroup*>* foundInSet = NULL;
for (auto it2 = components.begin (); it2 != components.end(); it2++)
{
if ((*it2).find (it->first) != (*it2).end ())
{
foundInSet = &(*it2);
//setIndex = it2 - components.begin();
break;
}
}
if (foundInSet == NULL)
{
for (auto it2 = it->second.begin(); it2 != it->second.end (); it2++)
{
if (group_to_set_index.find ((OptGroup*)*it2) !=
group_to_set_index.end ())
{
foundInSet = &components [group_to_set_index [(OptGroup*)*it2]];
break;
}
}
}
if (foundInSet != NULL)
{
for (auto it2 = it->second.begin(); it2 != it->second.end(); it2++)
{
foundInSet->insert ((OptGroup*)*it2);
}
foundInSet->insert (it->first);
}
else
{
unordered_set<OptGroup*> s = it->second;
s.insert (it->first);
components.push_back (s);
group_to_set_index [it->first] = components.size () - 1;
}
}
if (components.size () == 1)
return false;
return true;
}
bool createsCycle (OptGroup* toRemove, std::vector< std::vector <OptGroup*> >& components)
{
//If toRemove's previous group's (in the parent) can reach toRemove's next group's (in the parent)
//by not passing through toRemove, then there will be cycle after removing toRemove
vector <OptGroup*> prev_children;
vector <OptGroup*> next_children;
bool is_createsCycle = false;
for (auto it = toRemove->prevGroups ().begin ();
it != toRemove->prevGroups ().begin (); it++)
{
if ((hashID()& (*it)->hashID()) == (*it)->hashID())
prev_children.push_back ((OptGroup*)*it);
}
for (auto it = toRemove->nextGroups ().begin ();
it != toRemove->nextGroups ().begin (); it++)
{
if ((hashID()& (*it)->hashID()) == (*it)->hashID())
next_children.push_back ((OptGroup*)*it);
}
vector<OptGroup*> source_vertices;
unordered_map<uint128_t, bool, uint128Hasher> visited;
stack<OptGroup*> s;
for (auto it = prev_children.begin(); it != prev_children.end (); it++)
{
s.push (*it);
}
while (s.size () != 0)
{
OptGroup* g = s.top ();
s.pop ();
if (toRemove->nextGroups ().find (g) !=
toRemove->nextGroups ().end())
{
is_createsCycle = true;
break;
}
for (auto it = g->nextGroups ().begin ();
it != g->nextGroups().end (); it++)
{
if (((*it)->hashID() & hashID ()) == (*it)->hashID () &&
(*it)->hashID () != toRemove->hashID ())
{
s.push ((OptGroup*)*it);
}
}
}
////std::cout<< "is_createsCycle "<<is_createsCycle << std::endl;
if (!is_createsCycle)
return false;
while (s.size () != 0)
s.pop ();
for (auto it = next_children.begin(); it != next_children.end (); it++)
{
s.push (*it);
}
while (s.size () != 0)
{
OptGroup* g = s.top ();
s.pop ();
visited[g->hashID()] = true;
for (auto it = g->nextGroups ().begin ();
it != g->nextGroups().end (); it++)
{
if (((*it)->hashID() & hashID ()) == (*it)->hashID () &&
(*it)->hashID () != toRemove->hashID ())
{
s.push ((OptGroup*)*it);
}
}
}
for (auto it = children.begin (); it != children.end (); it++)
{
if ((*it)->hashID() != toRemove->hashID ())
{
if (visited[(*it)->hashID ()] == false)
{
components[1].push_back (*it);
}
else
{
components[0].push_back (*it);
}
}
}
if (components[1].size () == 0)
return false;
return true;
}
bool minParentEdgeToChild (OptGroup* toRemove, std::vector< unordered_set <OptGroup*> >& components,
OptGroup* minParentGroup)
{
if (!minParentGroup)
{
printf ("minParentEdgeToChild: minParentGroup is NULL\n");
assert (false);
}
//If a child of min parent group has an edge to a child of this group
//then break this group as it can create cycles
bool toReturn = false;
vector<OptGroup*> childrenToDisconnect;
for (auto it = minParentGroup->childGroups ().begin();
it != minParentGroup->childGroups ().end(); it++)
{
////std::cout<< "minParentGroup child " << std::bitset <41>((uint64_t)(*it)->hashID())<<std::endl;
for (auto it2 = (*it)->nextGroups ().begin();
it2 != (*it)->nextGroups ().end(); it2++)
{
////std::cout<< "child next "<< std::bitset <41>((uint64_t)(*it2)->hashID())<<std::endl;
if (((*it2)->hashID () & hashID ()) == (*it2)->hashID ())
{
////std::cout<< "is parent's child "<<std::endl;
childrenToDisconnect.push_back ((OptGroup*)(*it2));
toReturn = true;
}
}
}
////std::cout<< "minParentEdgeToChild " << toReturn << std::endl;
////std::cout<< "childrenToDisconnect "<< childrenToDisconnect.size () << std::endl;
for (auto it = childrenToDisconnect.begin(); it != childrenToDisconnect.end (); it++)
{
////std::cout<< std::bitset<41>((uint64_t)(*it)->hashID ())<< std::endl;
}
if (!toReturn)
return toReturn;
vector<OptGroup*> source_vertices;
unordered_map<uint128_t, bool, uint128Hasher> visited;
unordered_map<OptGroup*, unordered_set <OptGroup*> > reachable_vertices;
components.clear ();
for (auto it = children.begin(); it != children.end (); it++)
{
visited [(*it)->hashID ()] = false;
}
for (auto it = childrenToDisconnect.begin();
it != childrenToDisconnect.end (); it++)
{
stack<OptGroup*> s;
unordered_set <OptGroup*> reachable_set;
s.push (*it);
while (s.size () != 0)
{
OptGroup* g = s.top ();
s.pop ();
visited[g->hashID()] = true;
for (auto it2 = g->nextGroups ().begin ();
it2 != g->nextGroups().end (); it2++)
{
if (((*it2)->hashID() & hashID ()) == (*it2)->hashID () &&
(*it2)->hashID () != toRemove->hashID ())
{
reachable_set.insert ((OptGroup*)*it2);
s.push ((OptGroup*)*it2);
}
}
}
reachable_vertices [*it] = reachable_set;
}
components.push_back (unordered_set <OptGroup*> ());
for (auto it = children.begin (); it != children.end (); it++)
{
////std::cout<< "isvisited " << std::bitset<41>((uint64_t)(*it)->hashID ()) << " " << visited[(*it)->hashID ()]<<std::endl;
if (visited[(*it)->hashID ()] == false)
{
components[0].insert (*it);
}
}
if (components [0].size () == 0)
components.clear ();
////std::cout<< "minParentEdgeToChild reachable_vertices: " << std::endl;
for (auto it = reachable_vertices.begin();
it != reachable_vertices.end(); it++)
{
////std::cout<< std::bitset<41>((uint64_t)it->first->hashID ())<<std::endl;
for (auto it2 = it->second.begin(); it2 != it->second.end(); it2++)
{
////std::cout<< " " << std::bitset <41>((uint64_t) (*it2)->hashID ())<< std::endl;
}
}
////std::cout<< "components EARLIER 0" << std::endl;
for (auto it = components.begin(); it != components.end(); it++)
{
////std::cout<< "component " << (it)-components.begin() << std::endl;
for (auto it2 = (*it).begin (); it2 != (*it).end(); it2++)
{
////std::cout<< " " << std::bitset <41>((uint64_t)(*it2)->hashID()) << std::endl;
}
}
for (auto it = reachable_vertices.begin();
it != reachable_vertices.end(); it++)
{
unordered_set <OptGroup*>* foundInSet = NULL;
for (auto it2 = components.begin (); it2 != components.end(); it2++)
{
if ((*it2).find (it->first) != (*it2).end ())
{
foundInSet = &(*it2);
break;
}
}
if (foundInSet != NULL)
{
for (auto it2 = it->second.begin(); it2 != it->second.end(); it2++)
{
foundInSet->insert ((OptGroup*)*it2);
}
foundInSet->insert (it->first);
}
else
{
components.push_back (it->second);
(*(components.end () - 1)).insert (it->first);
}
}
////std::cout<< "components" << std::endl;
for (auto it = components.begin(); it != components.end(); it++)
{
////std::cout<< "component " << (it)-components.begin() << std::endl;
for (auto it2 = (*it).begin (); it2 != (*it).end(); it2++)
{
////std::cout<< " " << std::bitset <41>((uint64_t)(*it2)->hashID()) << std::endl;
}
}
if (components.size () == 1)
return false;
return true;
}
void removeChild (uint128_t _hash_id, OptGroup* minParentGroup)
{
vector <unordered_set <OptGroup*> > components;
std::vector <OptGroup*> childrenToRemove;
uint128_t prev_hash_id = hashID();
////std::cout<< "removing from parent " << std::bitset<41>((uint64_t)(hashID()))<<std::endl;
if (this->hashID() == 0 || _hash_id == 0)
return;
OptGroup* toRemove = OptGroup::optHashIDToGroup[_hash_id];
childrenToRemove.push_back (toRemove);
////std::cout<<"toRemove is " << std::bitset<41>((uint64_t)toRemove->hashID()) << " parent group address " <<(uint64_t)this<<std::endl;
//TODO: create functions for setting/getting values in parentOptGroupToHashID map and optGroupToHashID map
//Also add assertions in it that the group being set/get is equal to the hash id key.
for (auto it = prevGroups().begin(); it != prevGroups().end();
it++)
{
////std::cout<<"before removing prevgroup " << std::bitset<41>((uint64_t)(*it)->hashID())<< " " << (uint64_t)*it <<std::endl;
}
for (auto it = nextGroups().begin(); it != nextGroups().end();
it++)
{
////std::cout<<"before removing nextGroups " << std::bitset<41>((uint64_t)(*it)->hashID()) << " " << (uint64_t)*it<<std::endl;
}
if (_hash_id != hashID () &&
(isDisconnected (childrenToRemove[0],
components) || minParentEdgeToChild (childrenToRemove[0],
components, minParentGroup)))
{
if (components.size() > 1)
{
////std::cout<<"isDisconnected is true " << components.size () << std::endl;
auto components_it = components.begin ();
components_it++; //the first one is current group
while (components_it != components.end ())
{
unordered_set <OptGroup*>& connected_component = *components_it;
////std::cout<< "connected_component size " << connected_component.size () << std::endl;
uint128_t newHashID = (*connected_component.begin())->hashID();
for (auto it = connected_component.begin (); it != connected_component.end ();
it++)
{
newHashID = newHashID | (*it)->hashID ();
////std::cout<<"removing "<< std::bitset<41>((uint64_t)(*it)->hashID ()) << std::endl;
children.erase (OptGroup::optHashIDToGroup[(*it)->hashID ()]);
childrenToRemove.push_back (*it);
}
////std::cout<< "newHashID " << std::bitset<41>((uint64_t)newHashID) << " in parentopt " << inParentOptGroupsToHashID (newHashID) << std::endl;
OptGroup* newGroup;
if (!inParentOptGroupsToHashID (newHashID))
{
newGroup = OptGroup::createParentOptGroup (newHashID);
vector <Group*> toRemove;
//Find next and prev groups for new group
for (auto it2 = connected_component.begin ();
it2 != connected_component.end (); it2++)
{
for (auto it3 = (*it2)->nextGroups ().begin ();
it3 != (*it2)->nextGroups ().end (); it3++)
{
for (auto it4 = (*it3)->parentGroups ().begin ();
it4 != (*it3)->parentGroups ().end ();
it4++)
{
if ((*it4)->hashID () != newGroup->hashID ())
{
////std::cout<<"newgroup nextGroup " << std::bitset<41>((uint64_t)(*it4)->hashID())<<std::endl;
newGroup->nextGroups ().insert (*it4);
(*it4)->prevGroups (). insert (newGroup);
}
}
}
}
for (auto it2 = connected_component.begin ();
it2 != connected_component.end (); it2++)
{
for (auto it3 = (*it2)->prevGroups ().begin ();
it3 != (*it2)->prevGroups ().end (); it3++)
{
for (auto it4 = (*it3)->parentGroups ().begin ();
it4 != (*it3)->parentGroups ().end ();
it4++)
{
if ((*it4)->hashID () != newGroup->hashID ())
{
////std::cout<<"newgroup prevGroups " << std::bitset<41>((uint64_t)(*it4)->hashID())<<std::endl;
newGroup->prevGroups ().insert (*it4);
(*it4)->nextGroups (). insert (newGroup);
}
}
}
}
}
else
{
newGroup = parentOptGroupsToHashID[newHashID];
// //std::cout<< "newGroup in parent " << newGroup << std::endl;
}
//nextGroups ().insert (newGroup);
//newGroup->prevGroups (). insert (this);
components_it++;
}
}
}
/*if (hash_id == 0)
{
//OptGroup is removed
for (auto it = children.begin(); it != children.end(); it++)
{
(*it)->parentGroups().erase (this);
}
}
else*/
for (auto const &childToRemove : childrenToRemove)
{
vector<OptGroup*> prevGroupsToRemove, nextGroupsToRemove;
////std::cout<< std::bitset<41>((uint64_t)(hash_id))<< " " << std::bitset<41>((uint64_t)(childToRemove)->hashID())<<std::endl;
////std::cout<< "contains parent " << ((childToRemove)->parentGroups().find(this) != (childToRemove)->parentGroups().end()) << std::endl;
(childToRemove)->parentGroups().erase (this);
for (auto _it = (childToRemove)->parentGroups().begin();
_it != (childToRemove)->parentGroups().end ();
_it++)
{
//std::cout<<"after removing parent group:" << std::bitset<41>((uint64_t)(*_it)->hashID ()) << std::endl;
}
children.erase (childToRemove);
//Remove those links from prevGroups and nextGroups to this group
//which are due to children in childrenToRemove
//std::cout<<"remove prev next for " << std::bitset<41>((uint64_t)(childToRemove)->hashID()) << std::endl;
for (auto it2 = prevGroups().begin(); it2 != prevGroups().end(); it2++)
{
OptGroup* prevGrp = (OptGroup*)(*it2);
for (auto it3 = childToRemove->prevGroups().begin ();
it3 != childToRemove->prevGroups().end(); it3++)
{
if ((*it3)->parentGroups().find (prevGrp) != (*it3)->parentGroups().end())
{
bool canRemove = true;
for (auto it4 = children.begin(); it4 != children.end();
it4++)
{
for (auto it5 = (*it4)->prevGroups().begin();
it5 != (*it4)->prevGroups().end(); it5++)
{
//Remove parent group only if it is the parent of only
//prev group of only one child
if ((*it5)->parentGroups().find (prevGrp) != (*it5)->parentGroups().end())
{
canRemove = false;
break;
}
}
}
if (canRemove)
prevGroupsToRemove.push_back (prevGrp);
}
}
}
for (auto it2 = nextGroups().begin(); it2 != nextGroups().end(); it2++)
{
OptGroup* nextGrp = (OptGroup*)(*it2);
for (auto it3 = childToRemove->nextGroups().begin ();
it3 != childToRemove->nextGroups().end(); it3++)
{
if ((*it3)->parentGroups().find (nextGrp) !=
(*it3)->parentGroups().end())
{
bool canRemove = true;
for (auto it4 = children.begin(); it4 != children.end();
it4++)
{
for (auto it5 = (*it4)->nextGroups().begin();
it5 != (*it4)->nextGroups().end(); it5++)
{
//Remove parent group only if it is the parent of only
//prev group of only one child
if ((*it5)->parentGroups().find (nextGrp) != (*it5)->parentGroups().end())
{
canRemove = false;
break;
}
}
}
if (canRemove)
nextGroupsToRemove.push_back (nextGrp);
}
}
}
for (auto it2 = prevGroupsToRemove.begin();
it2 != prevGroupsToRemove.end(); it2++)
{
//std::cout<<"remove prev " << std::bitset<41>((uint64_t)(*it2)->hashID()) << std::endl;
prevGroups().erase (*it2);
(*it2)->nextGroups().erase (this);
}
for (auto it2 = nextGroupsToRemove.begin();
it2 != nextGroupsToRemove.end(); it2++)
{
//std::cout<<"remove next " << std::bitset<41>((uint64_t)(*it2)->hashID()) << std::endl;
nextGroups().erase (*it2);
(*it2)->prevGroups().erase (this);
}
}
//std::cout<< "number of children " << children.size () << std::endl;
//Clear prevGroups and nextGroups
prevGroups().clear ();
nextGroups().clear ();
//Update prevGroup and nextGroup with updated children set
for (auto const &child : children)
{
//Add parentGroups of prevGroups of child as prevGroups
for (auto const &child_prev : child->prevGroups ())
{
if (children.find ((OptGroup*)child_prev) == children.end ())
prevGroups().insert (child_prev->parentGroups().begin(),
child_prev->parentGroups().end());
}
//Add parentGroups of nextGroups of child as nextGroups
for (auto const &child_next : child->nextGroups ())
{
if (children.find ((OptGroup*)child_next) == children.end ())
nextGroups().insert (child_next->parentGroups().begin(),
child_next->parentGroups().end());
}
}
for (auto it = prevGroups().begin(); it != prevGroups().end();
it++)
{
//std::cout<<"after removing prevgroup " << std::bitset<41>((uint64_t)(*it)->hashID())<<std::endl;
}
for (auto it = nextGroups().begin(); it != nextGroups().end();
it++)
{
//std::cout<<"after removing nextGroups " << std::bitset<41>((uint64_t)(*it)->hashID())<<std::endl;
for (auto it2 = (*it)->nextGroups().begin(); it2 != (*it)->nextGroups().end();
it2++)
{
//std::cout<<"next " << std::bitset<41>((uint64_t)(*it2)->hashID())<<std::endl;
}
}
//Update all sets where this group is contained because OptGroup
//is hashed on the base of hash id. Changing hash id of group without
//updating there could (or will?) produce error
for (auto it = children.begin(); it != children.end(); it++)
{
//Remove from parentGroup of children
(*it)->parentGroups().erase (this);
}
for (auto it = nextGroups().begin(); it != nextGroups().end(); it++)
{
//Remove from prevGroup of next groups
(*it)->prevGroups().erase (this);
}
for (auto it = prevGroups().begin(); it != prevGroups().end(); it++)
{
//Remove from nextGroup of prev groups
(*it)->nextGroups().erase (this);
}
//Update Hash ID now because set of parents use hash id as its hash id
for (auto it = childrenToRemove.begin (); it != childrenToRemove.end ();
it++)
{
hash_id &= ~(*it)->hashID ();
}
if (hash_id != 0)
{
for (auto it = children.begin(); it != children.end(); it++)
{
//Insert to parentGroup of children
(*it)->parentGroups().insert (this);
}
for (auto it = nextGroups().begin(); it != nextGroups().end(); it++)
{
//Insert to prevGroup of next groups
(*it)->prevGroups().insert (this);
}
for (auto it = prevGroups().begin(); it != prevGroups().end(); it++)
{
//Insert to nextGroup of prev groups
(*it)->nextGroups().insert (this);
}
}
for (auto it = nextGroups().begin(); it != nextGroups().end();
it++)
{
//std::cout<<"after removing121212 nextGroups " << std::bitset<41>((uint64_t)(*it)->hashID())<<std::endl;
for (auto it2 = (*it)->nextGroups().begin(); it2 != (*it)->nextGroups().end();
it2++)
{
//std::cout<<"next " << std::bitset<41>((uint64_t)(*it2)->hashID())<<std::endl;
}
}
//std::cout<< "new hashid for group " << std::bitset<41>((uint64_t)hashID())<<std::endl;
if (hash_id != 0)
parentOptGroupsToHashID [hash_id] = this;
//std::cout<<"qqqqqqqqqqqqqqqqqq " << std::endl;
parentOptGroupsToHashID.erase (prev_hash_id);
//std::cout<<"qwqwqwq " << std::endl;
//delete &components[0];
//delete &components[1];
}
void setChildrenFromHashID ()
{
for (auto it = optHashIDToGroup.begin (); it != optHashIDToGroup.end (); ++it)
{
if (it->second != NULL && it->second != this && (hash_id & it->first) == it->first)
{
children.insert (it->second);
it->second->parentGroups ().insert (this);
}
}
}
set<OptGroup*, GroupComparer>& childGroups ()
{
return children;
}
/*void remove_from_parent ()
{
uint64_t bit = 0;
uint128_t _hash_id = hash_id;
while (_hash_id != 0)
{
if (_hash_id & 1L == 1)
{
uint128_t l = 1;
Group* a = Group::hashIDToGroup[l<<bit];
for (auto it = a->parentGroups().begin (); it != a->parentGroups().end (); it++)
{
if (*it == this)
{
a->parentGroups().erase (it);
break;
}
}
}
_hash_id = _hash_id >> 1;
bit++;
}
}*/
inline bool operator==(const OptGroup& other) const
{
return other.hash_id == hash_id;
}
static OptGroup* createOptGroup (uint128_t _hash_id)
{
OptGroup* _opt_group = optHashIDToGroup[_hash_id];
if (_opt_group == NULL)
{
_opt_group = new OptGroup (_hash_id);
optHashIDToGroup[_hash_id] = _opt_group;
vectorOptGroups.push_back (_opt_group);
}
return (OptGroup*)_opt_group;
}
static bool inParentOptGroupsToHashID (uint128_t _hash_id)
{
return parentOptGroupsToHashID.find(_hash_id) !=
parentOptGroupsToHashID.end() && parentOptGroupsToHashID [_hash_id] != NULL;
}
static OptGroup* createParentOptGroup (uint128_t _hash_id)
{
OptGroup* _opt_group = parentOptGroupsToHashID[_hash_id];
if (_opt_group == NULL)
{
_opt_group = new OptGroup (_hash_id);
parentOptGroupsToHashID[_hash_id] = _opt_group;
_opt_group->setChildrenFromHashID ();
}
return _opt_group;
}
static vector<uint128_t>* nextGroupsHashID (uint128_t hash_id)
{
Group* g;
g = optHashIDToGroup[hash_id];
if (g != NULL)
return new vector<uint128_t> (g->nextGroupsHashID()->begin(),
g->nextGroupsHashID()->end());
vector<uint128_t>* next_groups;
next_groups = new vector<uint128_t> ();
set <uint128_t, uint128Comparer> _set;
for (auto it = vectorOptGroups.begin (); it != vectorOptGroups.end (); ++it)
{
if ((hash_id & (*it)->hashID()) == (*it)->hashID())
{
vector<uint128_t>* a = ((Group*)(*it))->nextGroupsHashID();
for (auto it2 = a->begin(); it2 != a->end(); ++it2)
{
if (((*it2) & hash_id) != (*it2))
next_groups->push_back (*it2);
//_set.insert (*it2);
}
}
}
/*for (auto it = optHashIDToGroup.begin (); it != optHashIDToGroup.end (); ++it)
{
if (it->second != NULL && (hash_id & it->first) == it->first)
{
vector<uint128_t>* a = ((Group*)(it->second))->nextGroupsHashID();
for (auto it2 = a->begin(); it2 != a->end(); ++it2)
{
if (((*it2) & hash_id) != (*it2))
next_groups->push_back (*it2);
//_set.insert (*it2);
}
}
}*/
for (auto it = _set.begin(); it != _set.end(); it++)
next_groups->push_back (*it);
return next_groups;
}
static vector<uint128_t>* prevGroupsHashID (uint128_t hash_id)
{
Group* g;
g = optHashIDToGroup[hash_id];
if (g != NULL)
return new vector<uint128_t> (g->prevGroupsHashID()->begin(),
g->prevGroupsHashID()->end());
vector<uint128_t>* prev_groups;
prev_groups = new vector<uint128_t> ();
for (auto it = optHashIDToGroup.begin (); it != optHashIDToGroup.end (); ++it)
{
if (it->second != NULL && (hash_id & it->first) == it->first)
{
vector<uint128_t>* a = ((Group*)it->second)->prevGroupsHashID();
for (auto it2 = a->begin(); it2 != a->end(); ++it2)
{
if (((*it2) & hash_id) != (*it2))
prev_groups->push_back (*it2);
}
}
}
return prev_groups;
}
static bool isLiveoutForGroup (uint128_t group, OptGroup* child)
{
for (auto const& next_group: child->nextGroups ())
{
if ((next_group->hashID () & group) != next_group->hashID ())
{
return true;
}
}
if (child->nextGroups ().size () == 0)
return true;
return false;
}
static void liveoutsForGroup (const uint128_t hash_id,
const vector<Group*>& children,
unordered_set<Group*, Group::GroupHasher>& liveouts)
{
for (auto const& child: children)
{
bool is_liveout = false;
for (auto const& next: child->nextGroups ())
{
if ((next->hashID() & hash_id) != next->hashID())
{
is_liveout = true;
break;
}
}
if (child->nextGroups ().size () == 0)
is_liveout = true;
if (is_liveout)
{
liveouts.insert (child);
}
}
}
static void liveinsForChildInGroup (uint128_t group, OptGroup* child,
unordered_set<Group*, Group::GroupHasher>& liveins)
{
for (auto const& prev_group: child->prevGroups ())
{
if ((prev_group->hashID () & group) != prev_group->hashID ())
{
liveins.insert (prev_group);
}
}
}
};
#endif
| 34.486732 | 163 | 0.431894 | [
"vector"
] |
0d6adab119bd3d5a3a1d580c97bdcb2a08cc00a0 | 3,388 | h | C | include/lak/stride_vector.h | LAK132/NetworkMaker | 0ad1ba2488d80e8bba0a710e5d9984d7c5cc0739 | [
"MIT"
] | null | null | null | include/lak/stride_vector.h | LAK132/NetworkMaker | 0ad1ba2488d80e8bba0a710e5d9984d7c5cc0739 | [
"MIT"
] | null | null | null | include/lak/stride_vector.h | LAK132/NetworkMaker | 0ad1ba2488d80e8bba0a710e5d9984d7c5cc0739 | [
"MIT"
] | 1 | 2020-08-16T16:27:58.000Z | 2020-08-16T16:27:58.000Z | /*
MIT License
Copyright (c) 2018 Lucas Kleiss (LAK132)
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 <stdint.h>
#include <cstddef>
#include <vector>
#include <memory>
#include <cstring>
#ifndef LAK_STRIDE_VECTOR_H
#define LAK_STRIDE_VECTOR_H
namespace lak
{
using std::vector;
using std::memcpy;
struct stride_vector
{
size_t stride = 1;
vector<uint8_t> data;
stride_vector();
stride_vector(size_t size);
stride_vector(const stride_vector& other);
stride_vector(stride_vector&& other);
void init(size_t size, size_t str = 1);
inline size_t size() { return data.size(); }
stride_vector& operator=(const stride_vector& other);
stride_vector& operator=(stride_vector&& other);
vector<uint8_t> operator[](size_t idx) const;
template <typename T>
T& at(size_t idx)
{
return *static_cast<T*>(&data[sizeof(T) * idx]);
}
template <typename T>
const T& at(size_t idx) const
{
return *static_cast<T*>(&data[sizeof(T) * idx]);
}
template <typename T>
stride_vector& operator=(const vector<T>& other)
{
stride = sizeof(T);
data.resize(sizeof(T) * other.size());
memcpy(&(data[0]), &(other[0]), data.size());
return *this;
}
template <typename T>
stride_vector& operator=(vector<T>&& other)
{
return *this = other;
}
template <typename T>
inline T* get()
{
return (T*)&(data[0]);
}
template <typename T>
static stride_vector strideify(const vector<T> other)
{
stride_vector rtn;
return rtn = other;
}
template <typename T>
static stride_vector strideify(vector<T>&& other)
{
stride_vector rtn;
return rtn = other;
}
static stride_vector interleave(const vector<stride_vector*>& vecs);
static stride_vector interleave(vector<stride_vector*>&& vecs);
};
}
#ifdef LAK_STRIDE_VECTOR_IMPLEM
# ifndef LAK_STRIDE_VECTOR_HAS_IMPLEM
# define LAK_STRIDE_VECTOR_HAS_IMPLEM
# include "stride_vector.cpp"
# endif // LAK_STRIDE_VECTOR_HAS_IMPLEM
#endif // LAK_STRIDE_VECTOR_IMPLEM
#endif // LAK_STRIDE_VECTOR_H | 32.893204 | 78 | 0.652893 | [
"vector"
] |
0d790e3f7005e88339bb648109f3829b92077874 | 79,896 | h | C | source/COSMOS-Fine/Header/cosmos_r.h | odysseus-oosql/ODYSSEUS-OOSQL | 49a5e32b6f73cea611dafdcc0e6767f80d4450ae | [
"BSD-3-Clause"
] | 6 | 2016-08-29T08:03:21.000Z | 2022-03-25T09:56:23.000Z | source/COSMOS-Fine/Header/cosmos_r.h | odysseus-oosql/ODYSSEUS-OOSQL | 49a5e32b6f73cea611dafdcc0e6767f80d4450ae | [
"BSD-3-Clause"
] | null | null | null | source/COSMOS-Fine/Header/cosmos_r.h | odysseus-oosql/ODYSSEUS-OOSQL | 49a5e32b6f73cea611dafdcc0e6767f80d4450ae | [
"BSD-3-Clause"
] | null | null | null | /******************************************************************************/
/* */
/* Copyright (c) 1990-2016, KAIST */
/* 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 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 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. */
/* */
/******************************************************************************/
/******************************************************************************/
/* */
/* ODYSSEUS/COSMOS General-Purpose Large-Scale Object Storage System -- */
/* Fine-Granule Locking Version */
/* Version 3.0 */
/* */
/* Developed by Professor Kyu-Young Whang et al. */
/* */
/* Advanced Information Technology Research Center (AITrc) */
/* Korea Advanced Institute of Science and Technology (KAIST) */
/* */
/* e-mail: odysseus.oosql@gmail.com */
/* */
/* Bibliography: */
/* [1] Whang, K., Lee, J., Lee, M., Han, W., Kim, M., and Kim, J., "DB-IR */
/* Integration Using Tight-Coupling in the Odysseus DBMS," World Wide */
/* Web, Vol. 18, No. 3, pp. 491-520, May 2015. */
/* [2] Whang, K., Lee, M., Lee, J., Kim, M., and Han, W., "Odysseus: a */
/* High-Performance ORDBMS Tightly-Coupled with IR Features," In Proc. */
/* IEEE 21st Int'l Conf. on Data Engineering (ICDE), pp. 1104-1105 */
/* (demo), Tokyo, Japan, April 5-8, 2005. This paper received the Best */
/* Demonstration Award. */
/* [3] Whang, K., Park, B., Han, W., and Lee, Y., "An Inverted Index */
/* Storage Structure Using Subindexes and Large Objects for Tight */
/* Coupling of Information Retrieval with Database Management */
/* Systems," U.S. Patent No.6,349,308 (2002) (Appl. No. 09/250,487 */
/* (1999)). */
/* [4] Whang, K., Lee, J., Kim, M., Lee, M., Lee, K., Han, W., and Kim, */
/* J., "Tightly-Coupled Spatial Database Features in the */
/* Odysseus/OpenGIS DBMS for High-Performance," GeoInformatica, */
/* Vol. 14, No. 4, pp. 425-446, Oct. 2010. */
/* [5] Whang, K., Lee, J., Kim, M., Lee, M., and Lee, K., "Odysseus: a */
/* High-Performance ORDBMS Tightly-Coupled with Spatial Database */
/* Features," In Proc. 23rd IEEE Int'l Conf. on Data Engineering */
/* (ICDE), pp. 1493-1494 (demo), Istanbul, Turkey, Apr. 16-20, 2007. */
/* */
/******************************************************************************/
#ifndef __COSMOS_R_H__
#define __COSMOS_R_H__
#ifdef WIN32
#else
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <semaphore.h>
#include <pthread.h>
#include <errno.h>
#endif /* WIN32 */
#include <semaphore.h>
#include "param.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
* Constants
*/
/* maximum number of mounted volumes */
#define MAXNUMOFVOLS 20
/* maximum number of open relations */
#define MAXNUMOFOPENRELS 400
/* maximum relation name */
#define MAXRELNAME 250
/* maximum number of columns */
#define MAXNUMOFCOLS 256
/* maximum number of indexes */
#define MAXNUMOFINDEXES 128
/* maximum number of boolean expressions */
#define MAXNUMOFBOOLS 20
/* maximum key value length for Btree */
#define MAXKEYLEN 256
/* number of attributes consisting MBR */
#define MBR_NUM_PARTS 4
/* maximum number of key parts in Btree */
#define MAXNUMKEYPARTS 8
/* maximum number of key parts in MLGF */
#define MLGF_MAXNUM_KEYS 10
/* NIL value */
#define NIL -1
/* scan direction */
#define FORWARD 0
#define BACKWARD 1
#define BACKWARD_NOORDERING 2
#define BACKWARD_ORDERING 3
/* end of scan */
#define EOS 1
#define MAXKEYWORDLEN (MAXKEYLEN-sizeof(Two))
#define INITSCAN 20
#define LRDS_SYSTABLES_RELNAME "lrdsSysTables"
#define LRDS_SYSCOLUMNS_RELNAME "lrdsSysColumns"
#define LRDS_SYSINDEXES_RELNAME "lrdsSysIndexes"
/*
* Type definitions for the basic types
*
* Note: it is used not to COSMOS but to ODYSSEUS.
*/
#ifndef __DBLABLIB_H__
#if defined(_LP64) && defined(SUPPORT_LARGE_DATABASE2)
/* one byte data type (in fact, it is a two byte data type) */
typedef short One;
typedef unsigned short UOne;
/* two bytes data type (in fact, it is a four byte data type) */
typedef int Two;
typedef unsigned int UTwo;
/* four bytes data type (in fact, it is a eight byte data type) */
typedef long Four;
typedef unsigned long UFour;
/* eight bytes data type */
typedef long Eight;
typedef unsigned long UEight;
/* invarialbe size data type */
typedef char One_Invariable;
typedef unsigned char UOne_Invariable;
typedef One Two_Invariable;
typedef UOne UTwo_Invariable;
typedef Two Four_Invariable;
typedef UTwo UFour_Invariable;
typedef Four Eight_Invariable;
typedef UFour UEight_Invariable;
/* data & memory align type */
typedef Eight_Invariable ALIGN_TYPE;
typedef Eight_Invariable MEMORY_ALIGN_TYPE;
#elif defined(_LP64) && !defined(SUPPORT_LARGE_DATABASE2)
/* one byte data type */
typedef char One;
typedef unsigned char UOne;
/* two bytes data type */
typedef short Two;
typedef unsigned short UTwo;
/* four bytes data type */
typedef int Four;
typedef unsigned int UFour;
/* eight bytes data type */
typedef long Eight;
typedef unsigned long UEight;
/* invarialbe size data type */
typedef char One_Invariable;
typedef unsigned char UOne_Invariable;
typedef Two Two_Invariable;
typedef UTwo UTwo_Invariable;
typedef Four Four_Invariable;
typedef UFour UFour_Invariable;
typedef Eight Eight_Invariable;
typedef UEight UEight_Invariable;
/* data & memory align type */
typedef Four_Invariable ALIGN_TYPE;
typedef Eight_Invariable MEMORY_ALIGN_TYPE;
#elif !defined(_LP64) && defined(SUPPORT_LARGE_DATABASE2)
/* one byte data type (in fact, it is a two byte data type) */
typedef short One;
typedef unsigned short UOne;
/* two bytes data type (in fact, it is a four byte data type) */
typedef long Two;
typedef unsigned long UTwo;
/* four bytes data type (in fact, it is a eight byte data type) */
#if defined(AIX64) || defined(SOLARIS64) || defined(LINUX64)
typedef long long Four;
typedef unsigned long long UFour;
#elif defined(WIN64) || defined(WIN32)
typedef __int64 Four;
typedef unsigned __int64 UFour;
#else
#define EIGHT_NOT_DEFINED
#endif /* defined(AIX64) || defined(SOLARIS64) || defined(LINUX64) */
/* eight bytes data type */
#if defined(AIX64) || defined(SOLARIS64) || defined(LINUX64)
typedef long long Eight;
typedef unsigned long long UEight;
#elif defined(WIN64) || defined(WIN32)
typedef __int64 Eight;
typedef unsigned __int64 UEight;
#else
#define EIGHT_NOT_DEFINED
#endif /* defined(AIX64) || defined(SOLARIS64) || defined(LINUX64) */
/* invarialbe size data type */
typedef char One_Invariable;
typedef unsigned char UOne_Invariable;
typedef One Two_Invariable;
typedef UOne UTwo_Invariable;
typedef Two Four_Invariable;
typedef UTwo UFour_Invariable;
#if defined(AIX64) || defined(SOLARIS64) || defined(LINUX64) || defined(WIN64) || defined(WIN32)
typedef Four Eight_Invariable;
typedef UFour UEight_Invariable;
#endif
/* data & memory align type */
typedef Eight_Invariable ALIGN_TYPE;
typedef Four_Invariable MEMORY_ALIGN_TYPE;
#elif !defined(_LP64) && !defined(SUPPORT_LARGE_DATABASE2)
/* one byte data type */
typedef char One;
typedef unsigned char UOne;
/* two bytes data type */
typedef short Two;
typedef unsigned short UTwo;
/* four bytes data type */
typedef long Four;
typedef unsigned long UFour;
/* eight bytes data type */
#if defined(AIX64) || defined(SOLARIS64) || defined(LINUX64)
typedef long long Eight;
typedef unsigned long long UEight;
#elif defined(WIN64) || defined(WIN32)
typedef __int64 Eight;
typedef unsigned __int64 UEight;
#else
#define EIGHT_NOT_DEFINED
#endif /* defined(AIX64) || defined(SOLARIS64) || defined(LINUX64) */
/* invarialbe size data type */
typedef char One_Invariable;
typedef unsigned char UOne_Invariable;
typedef Two Two_Invariable;
typedef UTwo UTwo_Invariable;
typedef Four Four_Invariable;
typedef UFour UFour_Invariable;
#if defined(AIX64) || defined(SOLARIS64) || defined(LINUX64) || defined(WIN64) || defined(WIN32)
typedef Eight Eight_Invariable;
typedef UEight UEight_Invariable;
#endif
/* data & memory align type */
typedef Four_Invariable ALIGN_TYPE;
typedef Four_Invariable MEMORY_ALIGN_TYPE;
#endif
#endif /* __DBLABLIB_H__ */
/* Boolean Type */
typedef enum { SM_FALSE, SM_TRUE } Boolean;
/* Comparison Operator */
typedef enum {SM_EQ=0x1, SM_LT=0x2, SM_LE=0x3, SM_GT=0x4, SM_GE=0x5, SM_NE=0x6, SM_EOF=0x10, SM_BOF=0x20} CompOp;
#ifndef WIN32
typedef int FileDesc;
#else
typedef void* FileDesc;
#endif /* WIN32 */
/* hash value */
typedef UFour_Invariable MLGF_HashValue;
/* MBR type */
typedef struct {
MLGF_HashValue values[MBR_NUM_PARTS];
} LRDS_MBR;
/* Btree Key Value */
typedef struct {
Two len;
char val[MAXKEYLEN];
} KeyValue;
/*
* BoundCond Type: used in a range scan of Btree to give bound condition
*/
typedef struct {
KeyValue key; /* Key Value */
CompOp op; /* The key value is included? */
} BoundCond;
/*
* Type Definition for Transaction Identifier
*/
typedef struct { /* 8 byte unsigned integer */
UFour high;
UFour low;
} XactID;
/*
* Lock Parameter
*/
typedef enum { L_NL, L_IS, L_IX, L_S, L_SIX, L_X } LockMode; /* lock mode */
typedef enum { L_INSTANT, L_MANUAL, L_COMMIT } LockDuration; /* lock duration */
typedef struct {
LockMode mode;
LockDuration duration;
} LockParameter;
typedef enum { X_BROWSE_BROWSE, X_CS_BROWSE, X_CS_CS, X_RR_BROWSE, X_RR_CS, X_RR_RR } ConcurrencyLevel; /* isolation degree */
/*
** Type Definition of PageID
*/
typedef Four PageNo;
typedef Two VolNo;
typedef VolNo VolID;
typedef struct {
PageNo pageNo; /* a PageNo */
VolNo volNo; /* a VolNo */
} PageID;
/*
* Definition for Logical ID
*/
typedef Four Serial;
typedef struct {
Serial serial; /* a logical serial number */
VolNo volNo; /* a VolNo */
} LogicalID;
/*
* Type Definition for FileID and IndexID
*/
typedef LogicalID FileID;
typedef LogicalID IndexID;
/*
* Type Definition for ObjectID and TupleID
*/
typedef UFour Unique;
typedef Two SlotNo;
typedef struct {
PageNo pageNo; /* specify the page holding the object */
VolID volNo; /* specify the volume in which object is in */
SlotNo slotNo; /* specify the slot within the page */
Unique unique; /* Unique No for checking dangling object */
} ObjectID;
typedef ObjectID TupleID;
#define SET_NILTUPLEID(tid) (tid).pageNo = NIL
#define IS_NILTUPLEID(tid) (((tid).pageNo == NIL) ? SM_TRUE:SM_FALSE)
/*
* Type Definition for OID
*/
typedef Four ClassID;
typedef struct {
PageNo pageNo; /* specify the page holding the object */
VolID volNo; /* specify the volume in which object is in */
SlotNo slotNo; /* specify the slot within the page */
Unique unique; /* Unique No for checking dangling object */
ClassID classID; /* specify the class including the object */
} OID;
/* In common.h, MAKE_NULL_OID and IS_NULL_OID are defined differently.
* Definitions are
* MAKE_NULL_OID(oid) ((oid).classID = -1),
* IS_NULL_OID(oid) ((oid).classID == -1).
* But, we use following macros for a long time and have no problems.
* So, it had better remain the macros to prevent the future bugs caused by correction.
*/
#define MAKE_NULL_OID(oid) SET_NILTUPLEID(oid)
#define IS_NULL_OID(oid) IS_NILTUPLEID(oid)
/*
* Counter ID
*/
typedef ObjectID CounterID;
/*
** Type Definition for ColInfo
*/
/* key part */
typedef struct {
Two type; /* types supported by COSMOS */
Two offset; /* where ? */
Two length; /* how ? */
} KeyPart;
/* key descriptor */
typedef struct {
Two flag; /* flag for some more informations */
Two nparts; /* the number of key parts */
KeyPart kpart[MAXNUMKEYPARTS]; /* key parts */
} KeyDesc;
typedef struct OrderedSetAuxColInfo_T_tag {
KeyDesc kdesc;
Boolean nestedIndexFlag;
} OrderedSetAuxColInfo_T;
typedef struct {
Two complexType; /* data type of column */
Two type; /* data type of column */
Four length; /* length(maximum in case SM_STRING) of column */
union {
OrderedSetAuxColInfo_T *orderedSet;
} auxInfo;
} ColInfo;
typedef union AuxColInfo_T_tag {
OrderedSetAuxColInfo_T orderedSet;
} AuxColInfo_T;
typedef Four OrderedSet_ElementLength;
/*
* Index Description Definiton
*/
#define KEYFLAG_CLEAR 0x0
#define KEYFLAG_UNIQUE 0x1
#define KEYFLAG_CLUSTERING 0x2
#define KEYINFO_COL_ORDER 0x3 /* ORDER mask */
#define KEYINFO_COL_ASC 0x2 /* ascending order */
#define KEYINFO_COL_DESC 0x1 /* descending order */
typedef struct {
Two flag; /* KEYFLAG_CLEAR, KEYFLAG_UNIQUE, KEYFLAG_CLUSTERING */
Two nColumns; /* # of columns on which the index is defined */
struct {
Four colNo;
Four flag; /* ascending/descendig */
} columns[MAXNUMKEYPARTS];
} KeyInfo;
typedef struct {
Two flag; /* KEYFLAG_CLEAR, KEYFLAG_CLUSTERING */
Two nColumns; /* # of columns on which the index is defined */
Two colNo[MLGF_MAXNUM_KEYS]; /* column numbers */
Two extraDataLen; /* length of the extra data for an object */
} MLGF_KeyInfo;
#define SM_INDEXTYPE_BTREE 1
#define SM_INDEXTYPE_MLGF 2
typedef struct {
One indexType;
union {
KeyInfo btree; /* Key Information for Btree */
MLGF_KeyInfo mlgf; /* Key Information for MLGF */
} kinfo;
} LRDS_IndexDesc;
/*
** Type Definition for Boolean Expression
*/
typedef struct {
Two op; /* SM_EQ, SM_LT, SM_LE, SM_GT, SM_GE, SM_NE */
Two colNo; /* which column ? */
Two length; /* length of the value: used for SM_VARSTRING */
union {
Two_Invariable s; /* SM_SHORT */
Four_Invariable i; /* SM_INT */
Four_Invariable l; /* SM_LONG */
Eight_Invariable ll; /* SM_LONG */
float f; /* SM_FLOAT */
double d; /* SM_DOUBLE */
PageID pid; /* SM_PAGEID */
FileID fid; /* SM_FILEID */
IndexID iid; /* SM_INDEXID */
OID oid; /* SM_OID */
LRDS_MBR mbr; /* SM_MBR */
char str[MAXKEYLEN]; /* SM_STRING or SM_VARSTRING */
} data; /* the value to be compared */
} BoolExp;
/*
** Cursor definition
*/
/* AnyCursor:
* All cursors should have the following members at the front of them
* in the same order.
*/
typedef struct {
One opaque; /* opaque member */
TupleID tid; /* object pointed by the cursor */
} LRDS_AnyCursor;
/* DataCursor:
* sequential scan using the data file
*/
typedef struct {
One opaque; /* opaque member */
TupleID tid; /* object pointed by the cursor */
} LRDS_DataCursor;
/* BtreeCursor:
* scan using a B+ tree
*/
typedef struct {
One opaque; /* opaque member */
TupleID tid; /* object pointed by the cursor */
KeyValue key; /* what key value? */
} LRDS_BtreeCursor;
typedef struct {
One opaque; /* opaque member */
TupleID tid; /* object pointed by the cursor */
MLGF_HashValue keys[MLGF_MAXNUM_KEYS]; /* what key values? */
} LRDS_MLGF_Cursor;
/* Universal Cursor */
typedef union {
LRDS_AnyCursor any; /* for access of 'flag' and 'oid' */
LRDS_DataCursor seq; /* sequential scan */
LRDS_BtreeCursor btree; /* scan using a B+ tree */
LRDS_MLGF_Cursor mlgf; /* scan using MLGF index */
} LRDS_Cursor;
/*
** Type Definition for ColListStruct
*/
#define ALL_VALUE -1 /* special value of 'start' */
#define TO_END -1 /* special value of 'length' */
typedef struct {
Two colNo; /* IN column number */
Boolean nullFlag; /* TRUE if it has null value */
Four start; /* IN starting offset within a column */
/* ALL_VALUE: read all data of this column */
Four length; /* IN amount of old data within a column */
/* REMAINDER: to the end of the column */
Four dataLength; /* IN amount of new data */
union {
Two_Invariable s; /* SM_SHORT */
Four_Invariable i; /* SM_INT */
Four_Invariable l; /* SM_LONG */
Eight_Invariable ll; /* SM_LONG */
float f; /* SM_FLOAT */
double d; /* SM_DOUBLE */
PageID pid; /* SM_PAGEID */
FileID fid; /* SM_FILEID */
IndexID iid; /* SM_INDEXID */
OID oid; /* SM_OID */
LRDS_MBR mbr; /* SM_MBR */
void *ptr; /* pointer to data: SM_STRING, SM_VARSTRING */
} data;
Four retLength; /* OUT return length of Read/Write */
} ColListStruct;
/*
* to read the length of columns
*/
typedef struct {
Two colNo;
Four length;
}ColLengthInfoListStruct;
/*
* Data Types Supported by COSMOS
*/
#define SM_COMPLEXTYPE_BASIC 0
#define SM_COMPLEXTYPE_SET 1
#define SM_COMPLEXTYPE_ORDEREDSET 2
#define SM_COMPLEXTYPE_COLLECTIONSET 3
#define SM_COMPLEXTYPE_COLLECTIONBAG 4
#define SM_COMPLEXTYPE_COLLECTIONLIST 5
#define SM_SHORT 0
#define SM_INT 1
#define SM_LONG 2
#define SM_FLOAT 3
#define SM_DOUBLE 4
#define SM_STRING 5 /* fixed-length string */
#define SM_VARSTRING 6 /* variable-length string */
#define SM_PAGEID 7 /* PageID type */
#define SM_FILEID 8 /* FileID type */
#define SM_INDEXID 9 /* IndexID type */
#define SM_OID 10 /* OID(volume no, page no, slot no, unique no, class id) type */
/* NOTICE: OID is different with ObjectID */
#define SM_TEXT 11 /* Text Type */
#define SM_MBR 12 /* MBR Type */
#define SM_LONG_LONG 14
#define SM_SHORT_SIZE sizeof(Two_Invariable)
#define SM_INT_SIZE sizeof(Four_Invariable)
#define SM_LONG_SIZE sizeof(Four_Invariable)
#define SM_FLOAT_SIZE sizeof(float)
#define SM_DOUBLE_SIZE sizeof(double)
#define SM_PAGEID_SIZE sizeof(PageID)
#define SM_INDEXID_SIZE sizeof(IndexID)
#define SM_FILEID_SIZE sizeof(FileID)
#define SM_OID_SIZE sizeof(OID)
#define SM_MBR_SIZE (MBR_NUM_PARTS*sizeof(MLGF_HashValue))
#define SM_OBJECT_ID_SIZE sizeof(ObjectID)
#define SM_LONG_LONG_SIZE sizeof(Eight_Invariable)
/*
** Interface Function Prototypes of LRDS
*/
Four LRDS_AbortTransaction(Four, XactID*);
Four LRDS_AddSysCounters(Four, Four);
Four LRDS_AddIndex(Four, Four, char*, LRDS_IndexDesc*, IndexID*);
Four LRDS_AddColumn(Four, Four, char*, ColInfo*);
Four LRDS_BeginTransaction(Four, XactID*, ConcurrencyLevel);
Four LRDS_CloseRelation(Four, Four);
Four LRDS_CloseScan(Four, Four);
Four LRDS_CollectionSet_Create(Four, Four, Boolean, TupleID*, Four, Four);
Four LRDS_CollectionSet_Destroy(Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionSet_GetN_Elements(Four, Four, Boolean, TupleID*, Four, Four*);
Four LRDS_CollectionSet_Assign(Four, Four, Boolean, TupleID*, Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionSet_AssignElements(Four, Four, Boolean, TupleID*, Four, Four, Four*, void*);
Four LRDS_CollectionSet_InsertElements(Four, Four, Boolean, TupleID*, Four, Four, Four*, void*);
Four LRDS_CollectionSet_DeleteElements(Four, Four, Boolean, TupleID*, Four, Four, Four*, void*);
Four LRDS_CollectionSet_DeleteAll(Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionSet_IsMember(Four, Four, Boolean, TupleID*, Four, Four, void*);
Four LRDS_CollectionSet_IsEqual(Four, Four, Boolean, TupleID*, Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionSet_IsSubset(Four, Four, Boolean, TupleID*, Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionSet_RetrieveElements(Four, Four, Boolean, TupleID*, Four, Four, Four, Four*, Four, void*);
Four LRDS_CollectionSet_GetSizeOfElements(Four, Four, Boolean, TupleID*, Four, Four, Four, Four*);
Four LRDS_CollectionSet_Union(Four, Four, Boolean, TupleID*, Four, Four, Boolean, TupleID*, Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionSet_Intersect(Four, Four, Boolean, TupleID*, Four, Four, Boolean, TupleID*, Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionSet_Difference(Four, Four, Boolean, TupleID*, Four, Four, Boolean, TupleID*, Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionSet_UnionWith(Four, Four, Boolean, TupleID*, Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionSet_IntersectWith(Four, Four, Boolean, TupleID*, Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionSet_DifferenceWith(Four, Four, Boolean, TupleID*, Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionSet_Scan_Open(Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionSet_Scan_Close(Four, Four);
Four LRDS_CollectionSet_Scan_NextElements(Four, Four, Four, Four*, Four, void*);
Four LRDS_CollectionSet_Scan_GetSizeOfNextElements(Four, Four, Four, Four*);
Four LRDS_CollectionSet_Scan_InsertElements(Four, Four, Four, Four*, void*);
Four LRDS_CollectionSet_Scan_DeleteElements(Four, Four);
Four LRDS_CollectionSet_IsNull(Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionBag_Create(Four, Four, Boolean, TupleID*, Four, Four);
Four LRDS_CollectionBag_Destroy(Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionBag_GetN_Elements(Four, Four, Boolean, TupleID*, Four, Four*);
Four LRDS_CollectionBag_Assign(Four, Four, Boolean, TupleID*, Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionBag_AssignElements(Four, Four, Boolean, TupleID*, Four, Four, Four*, void*);
Four LRDS_CollectionBag_InsertElements(Four, Four, Boolean, TupleID*, Four, Four, Four*, void*);
Four LRDS_CollectionBag_DeleteElements(Four, Four, Boolean, TupleID*, Four, Four, Four*, void*);
Four LRDS_CollectionBag_DeleteAll(Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionBag_IsMember(Four, Four, Boolean, TupleID*, Four, Four, void*);
Four LRDS_CollectionBag_IsEqual(Four, Four, Boolean, TupleID*, Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionBag_IsSubset(Four, Four, Boolean, TupleID*, Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionBag_RetrieveElements(Four, Four, Boolean, TupleID*, Four, Four, Four, Four*, Four, void*);
Four LRDS_CollectionBag_GetSizeOfElements(Four, Four, Boolean, TupleID*, Four, Four, Four, Four*);
Four LRDS_CollectionBag_Union(Four, Four, Boolean, TupleID*, Four, Four, Boolean, TupleID*, Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionBag_Intersect(Four, Four, Boolean, TupleID*, Four, Four, Boolean, TupleID*, Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionBag_Difference(Four, Four, Boolean, TupleID*, Four, Four, Boolean, TupleID*, Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionBag_UnionWith(Four, Four, Boolean, TupleID*, Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionBag_IntersectWith(Four, Four, Boolean, TupleID*, Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionBag_DifferenceWith(Four, Four, Boolean, TupleID*, Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionBag_Scan_Open(Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionBag_Scan_Close(Four, Four);
Four LRDS_CollectionBag_Scan_NextElements(Four, Four, Four, Four*, Four, void*);
Four LRDS_CollectionBag_Scan_GetSizeOfNextElements(Four, Four, Four, Four*);
Four LRDS_CollectionBag_Scan_InsertElements(Four, Four, Four, Four*, void*);
Four LRDS_CollectionBag_Scan_DeleteElements(Four, Four);
Four LRDS_CollectionBag_IsNull(Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionList_Create(Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionList_Destroy(Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionList_GetN_Elements(Four, Four, Boolean, TupleID*, Four, Four*);
Four LRDS_CollectionList_Assign(Four, Four, Boolean, TupleID*, Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionList_AssignElements(Four, Four, Boolean, TupleID*, Four, Four, Four*, void*);
Four LRDS_CollectionList_InsertElements(Four, Four, Boolean, TupleID*, Four, Four, Four, Four*, void*);
Four LRDS_CollectionList_DeleteElements(Four, Four, Boolean, TupleID*, Four, Four, Four);
Four LRDS_CollectionList_DeleteAll(Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionList_AppendElements(Four, Four, Boolean, TupleID*, Four, Four, Four*, void*);
Four LRDS_CollectionList_GetSizeOfElements(Four, Four, Boolean, TupleID*, Four, Four, Four, Four*);
Four LRDS_CollectionList_RetrieveElements(Four, Four, Boolean, TupleID*, Four, Four, Four, Four*, Four, void*);
Four LRDS_CollectionList_UpdateElements(Four, Four, Boolean, TupleID*, Four, Four, Four, Four*, void*);
Four LRDS_CollectionList_Concatenate(Four, Four, Boolean, TupleID*, Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionList_Resize(Four, Four, Boolean, TupleID*, Four, Four);
Four LRDS_CollectionList_IsMember(Four, Four, Boolean, TupleID*, Four, Four, void*, Four*);
Four LRDS_CollectionList_IsEqual(Four, Four, Boolean, TupleID*, Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionList_Scan_Open(Four, Four, Boolean, TupleID*, Four);
Four LRDS_CollectionList_Scan_Close(Four, Four);
Four LRDS_CollectionList_Scan_NextElements(Four, Four, Four, Four*, Four, void*);
Four LRDS_CollectionList_Scan_GetSizeOfNextElements(Four, Four, Four, Four*);
Four LRDS_CollectionList_Scan_InsertElements(Four, Four, Four, Four*, void*);
Four LRDS_CollectionList_Scan_DeleteElements(Four, Four);
Four LRDS_CollectionList_IsNull(Four, Four, Boolean, TupleID*, Four);
Four LRDS_CommitTransaction(Four, XactID*);
Four LRDS_CreateCounter(Four, Four, char*, Four, CounterID*);
Four LRDS_CreateRelation(Four, Four, char*, LRDS_IndexDesc*, Four, ColInfo*, Boolean);
Four LRDS_CreateTuple(Four, Four, Boolean, Four, ColListStruct*, TupleID*);
Four LRDS_DestroyCounter(Four, Four, char*);
Four LRDS_DestroyRelation(Four, Four, char*);
Four LRDS_DestroyTuple(Four, Four, Boolean, TupleID*);
Four LRDS_Dismount(Four, Four);
Four LRDS_DropIndex(Four, Four, char*, IndexID*);
char *LRDS_Err(Four, Four);
Four LRDS_ExpandDataVolume(Four, Four, Four, char**, Four*);
Four LRDS_FetchTuple(Four, Four, Boolean, TupleID*, Four, ColListStruct*);
Four LRDS_FetchColLength(Four, Four, Boolean, TupleID*, Four, ColLengthInfoListStruct*);
Four LRDS_Final();
Four LRDS_FormatDataVolume(Four, Four, char**, char*, Four, Four, Four*, Four);
Four LRDS_FormatTempDataVolume(Four, Four, char**, char*, Four, Four, Four*, Four);
Four LRDS_FormatLogVolume(Four, Four, char**, char*, Four, Four, Four*);
Four LRDS_FormatCoherencyVolume(Four, char*, char*, Four);
Four LRDS_GetCounterId(Four, Four, char*, CounterID*);
Four LRDS_GetCounterValues(Four, Four, CounterID*, Four, Four*);
Four LRDS_GetFileIdOfRelation(Four, Four, char*, FileID*);
Four LRDS_Init();
Four LRDS_MLGF_OpenIndexScan(Four, Four, IndexID*, MLGF_HashValue[], MLGF_HashValue[], Four, BoolExp[], LockParameter*);
Four LRDS_MLGF_SearchNearTuple(Four, Four, IndexID*, MLGF_HashValue[], TupleID*, LockParameter*);
Four LRDS_Mount(Four, Four, char**, Four*);
Four LRDS_NextTuple(Four, Four, TupleID*, LRDS_Cursor**);
Four LRDS_OpenIndexScan(Four, Four, IndexID*, BoundCond*, BoundCond*, Four, BoolExp*, LockParameter*);
Four LRDS_OpenRelation(Four, Four, char*);
Four LRDS_OpenSeqScan(Four, Four, Four, Four, BoolExp*, LockParameter*);
Four LRDS_OrderedSet_AppendSortedElements(Four, Four, Boolean, TupleID*, Four, Four, Four, char*, LockParameter*);
Four LRDS_OrderedSet_Create(Four, Four, Boolean, TupleID*, Four, LockParameter*);
Four LRDS_OrderedSet_CreateNestedIndex(Four, Four, Four);
Four LRDS_OrderedSet_DeleteElement(Four, Four, Boolean, TupleID*, Four, KeyValue*, LockParameter*);
Four LRDS_OrderedSet_UpdateElement(Four, Four, Boolean, TupleID*, Four colNo, KeyValue*, Four, Four, Four, void*, LockParameter*);
Four LRDS_OrderedSet_DeleteElements(Four, Four, Boolean, TupleID*, Four, Four, KeyValue*, LockParameter*);
Four LRDS_OrderedSet_Destroy(Four, Four, Boolean, TupleID*, Four, LockParameter*);
Four LRDS_OrderedSet_DestroyNestedIndex(Four, Four, Four);
Four LRDS_OrderedSet_GetTotalLengthOfElements(Four, Four, Boolean, TupleID*, Four, Four*, LockParameter*);
Four LRDS_OrderedSet_GetN_Elements(Four, Four, Boolean, TupleID*, Four, Four*, LockParameter*);
Four LRDS_OrderedSet_InsertElement(Four, Four, Boolean, TupleID*, Four, char*, LockParameter*);
Four LRDS_OrderedSet_IsMember(Four, Four, Boolean, TupleID*, Four, KeyValue*, Four, char*, LockParameter*);
Four LRDS_OrderedSet_Scan_Close(Four, Four);
Four LRDS_OrderedSet_Scan_SkipElementsUntilGivenKeyValue(Four, Four, Four, char*);
#ifndef ORDEREDSET_BACKWARD_SCAN
Four LRDS_OrderedSet_Scan_Open(Four, Four, Boolean, TupleID*, Four, LockParameter*);
Four LRDS_OrderedSet_Scan_NextElements(Four, Four, Four, char*);
#else
Four LRDS_OrderedSet_Scan_Open(Four, Four, Boolean, TupleID*, Four, Four, LockParameter*);
#ifndef COMPRESSION
Four LRDS_OrderedSet_Scan_NextElements(Four, Four, Four, char*, Four, char*);
#else
Four LRDS_OrderedSet_Scan_NextElements(Four, Four, Four, char*, Four, char*, Four*);
#endif
#endif
Four LRDS_OrderedSet_SpecifyKeyOfElement(Four, Four, char*, Four, KeyDesc*);
Four LRDS_OrderedSet_IsNull(Four, Four, Boolean, TupleID*, Four);
#ifdef COMPRESSION
Four LRDS_OrderedSet_SpecifyVolNo(Four, Four, Boolean, TupleID*, Four, VolNo, LockParameter*);
Four LRDS_OrderedSet_GetVolNo(Four, Four, Boolean, TupleID*, Four, VolNo*, LockParameter*);
#endif
Four LRDS_ReadCounter(Four, Four, CounterID*, Four*);
Four LRDS_SetCounter(Four, Four, CounterID*, Four);
Four LRDS_Set_Create(Four, Four, Boolean, TupleID*, Four);
Four LRDS_Set_DeleteElements(Four, Four, Boolean, TupleID*, Four, Four, void*);
Four LRDS_Set_Destroy(Four, Four, Boolean, TupleID*, Four);
Four LRDS_Set_InsertElements(Four, Four, Boolean, TupleID*, Four, Four, void*);
Four LRDS_Set_IsMember(Four, Four, Boolean, TupleID*, Four, void*);
Four LRDS_Set_Scan_Close(Four, Four);
Four LRDS_Set_Scan_DeleteElements(Four, Four);
Four LRDS_Set_Scan_InsertElements(Four, Four, Four, void*);
Four LRDS_Set_Scan_NextElements(Four, Four, Four, void*);
Four LRDS_Set_Scan_Open(Four, Four, Boolean, TupleID*, Four);
Four LRDS_Set_IsNull(Four, Four, Boolean, TupleID*, Four);
Four LRDS_SortRelation(Four, Four, Four, char*, KeyInfo*, Boolean, char*, Boolean, LockParameter*);
Four LRDS_Text_AddKeywords(Four, Four, Boolean, TupleID*, Four, Four, char*);
Four LRDS_Text_GetIndexID(Four, Four, Four, IndexID*);
Four LRDS_Text_DeleteKeywords(Four, Four, Boolean, TupleID*, Four, Four, char*);
Four LRDS_UpdateTuple(Four, Four, Boolean, TupleID*, Four, ColListStruct*);
Four LRDS_SetCfgParam(Four, char*, char*);
char* LRDS_GetCfgParam(Four, char*);
Four LRDS_AllocHandle(Four*);
Four LRDS_FreeHandle(Four);
/*
* Bulkload API
*/
Four LRDS_InitRelationBulkLoad(Four, Four, Four, char*, Boolean, Boolean, Two, Two, LockParameter*);
Four LRDS_NextRelationBulkLoad(Four, Four, Four, ColListStruct*, Boolean, TupleID*);
Four LRDS_FinalRelationBulkLoad(Four, Four);
#ifndef COMPRESSION
Four LRDS_NextRelationBulkLoad_OrderedSetBulkLoad(Four, Four, Four, Four, Four, Four, char*, Boolean, TupleID*);
#else
Four LRDS_NextRelationBulkLoad_OrderedSetBulkLoad(Four, Four, Four, Four, Four, Four, char*, Boolean, TupleID*, char*, VolNo, Four);
#endif
Four LRDS_NextRelationBulkLoad_Collection(Four, VolID, Four, Four, Boolean, Boolean, TupleID*, Four, Four);
Four LRDS_OrderedSetAppendBulkLoad(Four, Four, Four, Boolean, TupleID*, Four, Four, Four, char*, LockParameter*);
Four LRDS_InitTextBulkLoad(Four, Four, Four, Boolean, Boolean, Four, LockParameter*);
Four LRDS_NextTextBulkLoad(Four, Four, TupleID*, Four, char*);
Four LRDS_FinalTextBulkLoad(Four, Four);
/*
* Stream utility
*/
#define SORTKEYDESC_ATTR_ORDER 0x3 /* attribute ORDER mask */
#define SORTKEYDESC_ATTR_ASC 0x2 /* ascending order */
#define SORTKEYDESC_ATTR_DESC 0x1 /* descending order */
typedef struct {
Two nparts; /* # of key parts */
Two hdrSize; /* size of header in front of sorted tuple */
struct {
Four type; /* part's type */
Four length; /* part's length */
Four flag; /* ascending/descendig = SORTKEYDESC_ATTR_ASC/SORTKEYDESC_ATTR_DESC */
} parts[MAXNUMKEYPARTS];
} SortTupleDesc;
typedef struct {
Two len;
char* data;
} SortStreamTuple;
Four SM_OpenSortStream(Four, VolID, SortTupleDesc*);
Four SM_CloseSortStream(Four, Four);
Four SM_SortingSortStream(Four, Four);
Four SM_PutTuplesIntoSortStream(Four, Four, Four, SortStreamTuple*);
Four SM_GetTuplesFromSortStream(Four, Four, Four*, SortStreamTuple*, Boolean*);
Four SM_OpenStream(Four, VolID);
Four SM_CloseStream(Four, Four);
Four SM_ChangePhaseStream(Four, Four);
Four SM_PutTuplesIntoStream(Four, Four, Four, SortStreamTuple*);
Four SM_GetTuplesFromStream(Four, Four, Four*, SortStreamTuple*, Boolean*);
#define LRDS_OpenSortStream(_handle, volId, sortTupleDesc) SM_OpenSortStream(_handle, volId, sortTupleDesc)
#define LRDS_CloseSortStream(_handle, streamId) SM_CloseSortStream(_handle, streamId)
#define LRDS_SortingSortStream(_handle, streamId) SM_SortingSortStream(_handle, streamId)
#define LRDS_PutTuplesIntoSortStream(_handle, streamId, numTuples, tuples) \
SM_PutTuplesIntoSortStream(_handle, streamId, numTuples, tuples)
#define LRDS_GetTuplesFromSortStream(_handle, streamId, numTuples, tuples, eof) \
SM_GetTuplesFromSortStream(_handle, streamId, numTuples, tuples, eof)
#define LRDS_GetNumTuplesInSortStream(_handle, streamId) SM_GetNumTuplesInSortStream(_handle, streamId)
#define LRDS_GetSizeOfSortStream(_handle, streamId) SM_GetSizeOfSortStream(_handle, streamId)
#define LRDS_OpenStream(_handle, volId) SM_OpenStream(_handle, volId)
#define LRDS_CloseStream(_handle, streamId) SM_CloseStream(_handle, streamId)
#define LRDS_ChangePhaseStream(_handle, streamId) SM_ChangePhaseStream(_handle, streamId)
#define LRDS_PutTuplesIntoStream(_handle, streamId, numTuples, tuples) \
SM_PutTuplesIntoStream(_handle, streamId, numTuples, tuples)
#define LRDS_GetTuplesFromStream(_handle, streamId, numTuples, tuples, eof) \
SM_GetTuplesFromStream(_handle, streamId, numTuples, tuples, eof)
#define LRDS_GetNumTuplesInStream(_handle, streamId) SM_GetNumTuplesInStream(_handle, streamId)
#define LRDS_GetSizeOfStream(_handle, streamId) SM_GetSizeOfStream(_handle, streamId)
/*
* APIs for variable array
*/
/* Type definition for the variable size array */
typedef struct {
Four nEntries; /* # of entries in this array */
void *ptr; /* pointer to the chunk of memory */
} VarArray;
/* function prototype */
Four Util_initVarArray(Four, VarArray*, Four, Four);
Four Util_doublesizeVarArray(Four, VarArray*, Four);
Four Util_finalVarArray(Four, VarArray*);
/* APIs */
#define LRDS_initVarArray(_handle, varArray, size, number) Util_initVarArray(_handle, varArray, size, number)
#define LRDS_doublesizeVarArray(_handle, varArray, size) Util_doublesizeVarArray(_handle, varArray, size)
#define LRDS_finalVarArray(_handle, varArray) Util_finalVarArray(_handle, varArray)
/*
* XA Interface
*/
/*
* Type Definition
*/
typedef enum { LRDS_XA_SCANSTARTED, LRDS_XA_SCANENDED } LRDSXAscanStatus;
/*
* Transaction branch identification: XID and NULLXID:
*/
#ifndef LRDS_XA_XIDDATASIZE /* guard against redefinition in tx.h */
#define LRDS_XA_XIDDATASIZE 128 /* size in bytes */
#define LRDS_XA_MAXGTRIDSIZE 64 /* maximum size in bytes of gtrid */
#define LRDS_XA_MAXBQUALSIZE 64 /* maximum size in bytes of bqual */
typedef struct {
long formatID; /* format identifier */
long gtrid_length; /* value from 1 through 64 */
long bqual_length; /* value from 1 through 64 */
char data[LRDS_XA_XIDDATASIZE];
} LRDS_XA_XID;
#endif /* LRDS_XA_XIDDATASIZE */
/*
* Constant Variable Definition
*/
/* Flag definitions for the RM switch */
#define LRDS_XA_TMASYNC 0x80000000L /* perform routine asynchronously */
#define LRDS_XA_TMONEPHASE 0x40000000L /* caller is using on-phase commit optimisation */
#define LRDS_XA_TMFAIL 0x20000000L /* dissociates caller and marks transaction branch rollback-only */
#define LRDS_XA_TMNOWAIT 0x10000000L /* return if blocking condition exists */
#define LRDS_XA_TMRESUME 0x08000000L /* caller is resuming association with suspended transaction branch */
#define LRDS_XA_TMSUCCESS 0x04000000L /* dissociate caller from transaction branch */
#define LRDS_XA_TMSUSPEND 0x02000000L /* caller is suspending, not ending, association */
#define LRDS_XA_TMSTARTRSCAN 0x01000000L /* start a recovery scan */
#define LRDS_XA_TMENDRSCAN 0x00800000L /* end a recovery scan */
#define LRDS_XA_TMMULTIPLE 0x00400000L /* wait for any asynchronous operation */
#define LRDS_XA_TMJOIN 0x00200000L /* caller is joining existing transaction branch */
#define LRDS_XA_TMMIGRATE 0x00100000L /* caller intends to perfrom migration */
/*
*Flag definitions for the RM switch
*/
#define LRDS_XA_TMNOFLAGS 0x00000000L /* no resource manager features selected */
#define LRDS_XA_TMREGISTER 0x00000001L /* resource manager dynamically registers */
#define LRDS_XA_TMNOMIGRATE 0x00000002L /* resource manager does not support association migration */
#define LRDS_XA_TMUSEASYNC 0x00000004L /* resource manager supports asynchronous operations */
/*
* Macro Definitions
*/
#define LRDS_XA_OPENSTRINGHEADER "COSMOS_XA"
#define LRDS_XA_MAXOPENSTRINGLEN 1024
#define LRDS_XA_SCANSTATUS(_handle) (perThreadTable[_handle].lrdsDS.lrds_xa_scanStatus)
#define LRDS_XA_PREPAREDNUM(_handle) (perThreadTable[_handle].lrdsDS.lrds_xa_preparedNum)
#define LRDS_XA_CURRENTPOS(_handle) (perThreadTable[_handle].lrdsDS.lrds_xa_currentPos)
#define LRDS_XA_PREPAREDLIST(_handle) (perThreadTable[_handle].lrdsDS.lrds_xa_preparedList)
#define LRDS_XA_VOLID(_handle) (perThreadTable[_handle].lrdsDS.lrds_xa_volId)
/*
** Interface Function Prototypes of LRDS
*/
Four LRDS_XA_Commit(Four, LRDS_XA_XID *, int, long);
Four LRDS_XA_Forget(Four, LRDS_XA_XID *, int, long);
Four LRDS_XA_Prepare(Four, LRDS_XA_XID *, int, long);
Four LRDS_XA_Start(Four, LRDS_XA_XID *, int, long);
Four LRDS_XA_Complete(Four, int *, int *, int, long);
Four LRDS_XA_Open(Four, Four, char**, Four*, int, long);
Four LRDS_XA_Recover(Four, LRDS_XA_XID *, long, int, long);
Four LRDS_XA_Close(Four, char *, int, long);
Four LRDS_XA_End(Four, LRDS_XA_XID *, int, long);
Four LRDS_XA_Rollback(Four, LRDS_XA_XID *, int, long);
Four LRDS_XA_AxReg(Four, int, LRDS_XA_XID * , long);
Four LRDS_XA_AxUnreg(Four, int, long);
/*
* Function prototype for error log function
*/
void Util_ErrorLog_Printf(char* msg, ...);
Four Util_Sleep(double secs);
/*
* error codes
*/
#define eNOERROR 0
#define eINVALIDLICENSE -65536
#define eINTERNAL -65537
#define eBADPARAMETER -65538
#define eBADVOLUMEID -65539
#define eBADFILEID -65540
#define eBADINDEXID -65541
#define eBADPAGEID -65542
#define eBADCATOBJ -65543
#define eDEADLOCK -65544
#define eBADCURSOR -65545
#define eNOTFOUND -65546
#define eNULLPTR -65547
#define eMEMORYALLOCERR -65548
#define eTOOMANYVOLUMES -65549
#define eLOCKREQUESTFAIL -65550
#define eSCANOPENATSAVEPOINT -65551
#define eBADBUFSIZE -65552
#define eBLKLDTABLEFULL -65553
#define eVOLUMELOCKBLOCK -65554
#define eBADFREEDELEMENT_UTIL -131072
#define eBADFREEDARRAY_UTIL -131073
#define eSORTSTREAMTABLEFULL_UTIL -131074
#define eNOTENOUGHSORTTUPLEBUF_UTIL -131075
#define eOVERFLOWQUICKSORTSTACK_UTIL -131076
#define eVOLNOTMOUNTED_RDSM -196608
#define eUSEDDEVICE_RDSM -196609
#define eTOOMANYVOLUMES_RDSM -196610
#define eDEVICEOPENFAIL_RDSM -196611
#define eDEVICECLOSEFAIL_RDSM -196612
#define eREADFAIL_RDSM -196613
#define eWRITEFAIL_RDSM -196614
#define eLSEEKFAIL_RDSM -196615
#define eINVALIDTRAINSIZE_RDSM -196616
#define eINVALIDFIRSTEXT_RDSM -196617
#define eINVALIDPID_RDSM -196618
#define eINVALIDMETAENTRY_RDSM -196619
#define eINVALIDEFF_RDSM -196620
#define eNODISKSPACE_RDSM -196621
#define eNOEMPTYMETAENTRY_RDSM -196622
#define eDUPMETADICTENTRY_RDSM -196623
#define eVOLALREADYMOUNTED_RDSM -196624
#define eALREADYSETBIT_RDSM -196625
#define eINVALIDPAGETYPE_RDSM -196626
#define eMETADICTENTRYNOTFOUND_RDSM -196627
#define eBADBUFFERTYPE_BFM -262144
#define eBADLATCHMODE_BFM -262145
#define eBADBUFFER_BFM -262146
#define eBADHASHKEY_BFM -262147
#define eBADBUFTBLENTRY_BFM -262148
#define eFLUSHFIXEDBUF_BFM -262149
#define eNOTFOUND_BFM -262150
#define eNOUNFIXEDBUF_BFM -262151
#define eBADBUFINDEX_BFM -262152
#define eNULLBUFACCESSCB_BFM -262153
#define eNOSUCHLOCKEXIST_BFM -262154
#define eALREADYMOUNTEDCOHERENCYVOLUME_BFM -262155
#define eNOTMOUNTEDCOHERENCYVOLUME_BFM -262156
#define eBADOFFSET_LOT -327680
#define eTOOLARGELENGTH_LOT -327681
#define eMEMALLOCERR_LOT -327682
#define eBADPARAMETER_LOT -327683
#define eBADLENGTH_LOT -327684
#define eBADCATALOGOBJECT_LOT -327685
#define eEXCEEDMAXDEPTH_LOT -327686
#define eEMPTYPATH_LOT -327687
#define eBADPAGEID_LOT -327688
#define eBADSLOTNO_LOT -327689
#define eBADOBJECTID_LOT -327690
#define eBADPARAMETER_OM -393216
#define eBADOBJECTID_OM -393217
#define eBADCATALOGOBJECT_OM -393218
#define eBADLENGTH_OM -393219
#define eBADSTART_OM -393220
#define eBADFILEID_OM -393221
#define eBADUSERBUF_OM -393222
#define eBADPAGEID_OM -393223
#define eTOOLARGESORTKEY_OM -393224
#define eCANTALLOCEXTENT_BL_OM -393225
#define eBADPARAMETER_BTM -458752
#define eBADBTREEPAGE_BTM -458753
#define eBADPAGE_BTM -458754
#define eNOTFOUND_BTM -458755
#define eDUPLICATEDOBJECTID_BTM -458756
#define eBADCOMPOP_BTM -458757
#define eDUPLICATEDKEY_BTM -458758
#define eBADPAGETYPE_BTM -458759
#define eEXCEEDMAXDEPTHOFBTREE_BTM -458760
#define eTRAVERSEPATH_BTM -458761
#define eNOSUCHTREELATCH_BTM -458762
#define eDELETEOBJECTFAILED_BTM -458763
#define eBADCACHETREELATCHCELLPTR_BTM -458764
#define eBADPARAMETER_SM -524288
#define eNOTMOUNTEDVOLUME_SM -524289
#define eBADINDEXID_SM -524290
#define eINDEXIDFULL_SM -524291
#define eBADFILEID_SM -524292
#define eFILEIDFULL_SM -524293
#define eNOTFOUNDCATALOGENTRY_SM -524294
#define eOPENINDEX_SM -524295
#define eOPENFILE_SM -524296
#define eTOOMANYVOLUMES_SM -524297
#define eEXCLUSIVELOCKREQUIRED_SM -524298
#define eINVALIDHIERARCHICALLOCK_SM -524299
#define eBADLOCKMODE_SM -524300
#define eCOMMITDURATIONLOCKREQUIRED_SM -524301
#define eINVALIDMOUNTCOUNTER_SM -524302
#define eINTERNAL_SM -524303
#define eEXISTACTIVETRANSACTION_SM -524304
#define eNOACTIVETRANSACTION_SM -524305
#define eINVALIDCFGPARAM_SM -524306
#define eXACTNOTSTARTED_SM -524307
#define eTMPFILEEXISTATSAVEPOINT_SM -524308
#define eVOLUMEDISMOUNTDISALLOWED_SM -524309
#define eNOACTIVEPREPAREDTRANSACTION_SM -524310
#define eACTIVEGLOBALTRANSACTION_SM -524311
#define eNOACTIVEGLOBALTRANSACTION_SM -524312
#define eDUPLICATEDGTID_SM -524313
#define e2PCTRANSACTION_TM -589824
#define eNEWXACTNOTALLOWED_TM -589825
#define eWRONGXACTID_TM -589826
#define eBADDEALLOCLISTTYPE_TM -589827
#define eWRONGTMSTART_TM -589828
#define eNOFREEXACTTBLENTRY_TM -589829
#define eNO2PCTRANSACTION_TM -589830
#define eNONESTEDTOPACTION_TM -589831
#define eNOTFOUNDGLOBALXACTID_TM -589832
#define eNOTPREPARED_TM -589833
#define eTOODEEPNESTEDTOPACTION_TM -589834
#define eWRONGXACTCOMMIT_TM -589835
#define eWRONGXACTABORT_TM -589836
#define eDUPLICATEDGTID_TM -589837
#define eNOFREESPACEINGHEAP_SHM -655360
#define eSHMGETFAILED_SHM -655361
#define eSHMATFAILED_SHM -655362
#define eSEMGETFAILED_SHM -655363
#define eSHMCTLFAILED_SHM -655364
#define eSHMDTFAILED_SHM -655365
#define eFULLPROCTABLE_SHM -655366
#define eSEMCTLFAILED_SHM -655367
#define eSEMOPFAILED_SHM -655368
#define eSEMCTLSETVALFAILED_SHM -655369
#define eSEMCTLGETVALFAILED_SHM -655370
#define eSEMOPSENDERROR_SHM -655371
#define eSEMOPWAITERROR_SHM -655372
#define eBADLATCHCONVERSION_SHM -655373
#define eDEMONFORKFAILED_SHM -655374
#define eHANDLERINSTALLFAILED_SHM -655375
#define eHANDLERUNINSTALLFAILED_SHM -655376
#define eBADXACTID_LM -720896
#define eBADOBJECTLOCK_LM -720897
#define eBADPAGELOCK_LM -720898
#define eBADFILELOCK_LM -720899
#define eBADKEYVALUELOCK_LM -720900
#define eLOCKHIERARCHYVIOLATE_LM -720901
#define eWRONGLOCKSTATUS_LM -720902
#define eWRONGLOCKMODE_LM -720903
#define eWRONGDURATION_LM -720904
#define eDUPXACTID_LM -720905
#define eFATALERROR_LM -720906
#define eWRONGACTIONSTART_LM -720907
#define eWRONGACTIONEND_LM -720908
#define eNONEEDACTION_LM -720909
#define eNOLOGSPACE_LOG -786432
#define eENDOFLOG_LOG -786433
#define eNOOPENEDLOGVOLUME_LOG -786434
#define eLOGVOLUMEALREADYOPENED_LOG -786435
#define eLOGVOLOPENFAIL_RM -851968
#define eLSEEKFAIL_RM -851969
#define eLOGVOLUMEFULL_RM -851970
#define eREADFAIL_RM -851971
#define eWRITEFAIL_RM -851972
#define eNOLOGGEDTRANSACTION_RM -851973
#define eLOGVOLCLOSEFAIL_RM -851974
#define eNOLOGVOLUME_RM -851975
#define eINVALIDTRAINTYPE_RM -851976
#define eINVALIDOBJECTID_RM -851977
#define eACTIVEPREPAREDTRANSACTION_RM -851978
#define eNOACTIVEPREPAREDTRANSACTION_RM -851979
#define eRELATIONNOTFOUND_LRDS -917504
#define eINDEXNOTFOUND_LRDS -917505
#define eCOUNTERNOTFOUND_LRDS -917506
#define eTOOMANYOPENRELATIONS_LRDS -917507
#define eRELATIONEXIST_LRDS -917508
#define eINDEXEXIST_LRDS -917509
#define eOPENRELATION_LRDS -917510
#define eTOOMANYTMPRELATIONS_LRDS -917511
#define eSET_EXIST_LRDS -917512
#define eSET_NOTEXIST_LRDS -917513
#define eSET_OPENSCAN_LRDS -917514
#define eORDEREDSET_EXIST_LRDS -917515
#define eORDEREDSET_NOTEXIST_LRDS -917516
#define eORDEREDSET_OPENSCAN_LRDS -917517
#define eORDEREDSET_ELEMENTNOTFOUND_LRDS -917518
#define eCOLLECTION_EXIST_LRDS -917519
#define eCOLLECTION_NOTEXIST_LRDS -917520
#define eCOLLECTION_OPENSCAN_LRDS -917521
#define eCOLLECTIONSET_ELEMENTEXIST_LRDS -917522
#define eCOLLECTIONSET_ELEMENTNOTFOUND_LRDS -917523
#define eCOLLECTIONSET_NOTCOMPATIBLE_LRDS -917524
#define eCOLLECTIONBAG_ELEMENTNOTFOUND_LRDS -917525
#define eCOLLECTIONBAG_NOTCOMPATIBLE_LRDS -917526
#define eCOLUMNVALUEEXPECTED_LRDS -917527
#define eWRONGCOLUMNVALUE_LRDS -917528
#define eINVALIDCURRENTTUPLE_LRDS -917529
#define eTOOLARGELENGTH_LRDS -917530
#define eCATALOGNOTFOUND_LRDS -917531
#define eRELATIONOPENATSAVEPOINT_LRDS -917532
#define eTMPRELEXISTATSAVEPOINT_LRDS -917533
#define eXA_RBROLLBACK_LRDS_XA -917534
#define eXA_RBCOMMFAIL_LRDS_XA -917535
#define eXA_RBDEADLOCK_LRDS_XA -917536
#define eXA_RBINTEGRITY_LRDS_XA -917537
#define eXA_RBOTHER_LRDS_XA -917538
#define eXA_RBPROTO_LRDS_XA -917539
#define eXA_RBTIMEOUT_LRDS_XA -917540
#define eXA_RBTRANSIENT_LRDS_XA -917541
#define eXA_RBEND_LRDS_XA -917542
#define eXA_NOMIGRATE_LRDS_XA -917543
#define eXA_HEURHAZ_LRDS_XA -917544
#define eXA_HEURCOM_LRDS_XA -917545
#define eXA_HEURRB_LRDS_XA -917546
#define eXA_HEURMIX_LRDS_XA -917547
#define eXA_RETRY_LRDS_XA -917548
#define eXA_RDONLY_LRDS_XA -917549
#define eXAER_ASYNC_LRDS_XA -917550
#define eXAER_RMERR_LRDS_XA -917551
#define eXAER_NOTA_LRDS_XA -917552
#define eXAER_INVAL_LRDS_XA -917553
#define eXAER_PROTO_LRDS_XA -917554
#define eXAER_RMFAIL_LRDS_XA -917555
#define eXAER_DUPID_LRDS_XA -917556
#define eXAER_OUTSIDE_LRDS_XA -917557
#define eINVALIDOPENSTRING_LRDS_XA -917558
#define eDUPLICATEDGTID_LRDS_XA -917559
#define eINVALIDOPENSTRING_COSMOS_XA -983040
#define eINVALIDERRORCODE_COSMOS_XA -983041
#define eTHREADCREATEAGAIN_THM -1048576
#define eTHREADCREATEINVAL_THM -1048577
#define eTHREADCREATEUNKNOWN_THM -1048578
#define eTHREADWAITSRCH_THM -1048579
#define eTHREADWAITDEADLK_THM -1048580
#define eTHREADWAITINVAL_THM -1048581
#define eTHREADWAITUNKNOWN_THM -1048582
#define eMUTEXCREATEBUSY_THM -1048583
#define eMUTEXCREATEINVAL_THM -1048584
#define eMUTEXCREATEFAULT_THM -1048585
#define eMUTEXCREATEUNKNOWN_THM -1048586
#define eMUTEXDESTROYINVAL_THM -1048587
#define eMUTEXDESTROYUNKNOWN_THM -1048588
#define eMUTEXLOCKAGAIN_THM -1048589
#define eMUTEXLOCKDEADLK_THM -1048590
#define eMUTEXLOCKUNKNOWN_THM -1048591
#define eMUTEXUNLOCKPERM_THM -1048592
#define eMUTEXUNLOCKUNKNOWN_THM -1048593
#define eMUTEXINITFAILED_THM -1048594
#define eCONDCREATEINVAL_THM -1048595
#define eCONDCREATEBUSY_THM -1048596
#define eCONDCREATEAGAIN_THM -1048597
#define eCONDCREATENOMEM_THM -1048598
#define eCONDCREATEUNKNOWN_THM -1048599
#define eCONDDESTROYINVAL_THM -1048600
#define eCONDDESTROYUNKNOWN_THM -1048601
#define eCONDWAITINVAL_THM -1048602
#define eCONDWAITUNKNOWN_THM -1048603
#define eCONDSIGNALINVAL_THM -1048604
#define eCONDSIGNALUNKNOWN_THM -1048605
#define eSEMCREATEACCES_THM -1048606
#define eSEMCREATEEXIST_THM -1048607
#define eSEMCREATEINTR_THM -1048608
#define eSEMCREATEINVAL_THM -1048609
#define eSEMCREATEMFILE_THM -1048610
#define eSEMCREATENAMETOOLONG_THM -1048611
#define eSEMCREATENFILE_THM -1048612
#define eSEMCREATENOENT_THM -1048613
#define eSEMCREATENOSPC_THM -1048614
#define eSEMCREATENOSYS_THM -1048615
#define eSEMCREATEUNKNOWN_THM -1048616
#define eSEMCLOSEINVAL_THM -1048617
#define eSEMCLOSENOSYS_THM -1048618
#define eSEMCLOSEUNKNOWN_THM -1048619
#define eSEMDESTROYACCES_THM -1048620
#define eSEMDESTROYNAMETOOLONG_THM -1048621
#define eSEMDESTROYENOENT_THM -1048622
#define eSEMDESTROYNOSYS_THM -1048623
#define eSEMDESTROYUNKNOWN_THM -1048624
#define eSEMPOSTINVAL_THM -1048625
#define eSEMPOSTUNKNOWN_THM -1048626
#define eSEMWAITINVAL_THM -1048627
#define eSEMWAITINTR_THM -1048628
#define eSEMWAITUNKNOWN_THM -1048629
/*###########################################################################*/
/*
* The followings are for ODYSSEUS.
* These should be deleted when COSMOS is released outside.
*/
/*
* Macro Definition for Logical & Physical Pointer
*/
#ifdef USE_LOGICAL_PTR
/* Use logical address. */
#define SHM_BASE_ADDRESS (shmPtr)
extern struct SemStruct_tag *shmPtr;
typedef MEMORY_ALIGN_TYPE LogicalPtr_T;
#define LOGICAL_PTR_TYPE(_type) LogicalPtr_T
#define LOGICAL_PTR(_p) ((_p == NULL) ? NULL_LOGICAL_PTR : ((LogicalPtr_T)(_p) - (LogicalPtr_T)SHM_BASE_ADDRESS))
#define PHYSICAL_PTR(_p) ((_p == NULL_LOGICAL_PTR) ? (void*)NULL : ((void*)((LogicalPtr_T)(_p) + (LogicalPtr_T)SHM_BASE_ADDRESS)))
#define NULL_LOGICAL_PTR ((LogicalPtr_T)0x0)
#else /* USE_LOGICAL_PTR */
/* Use physical address. */
#define LOGICAL_PTR_TYPE(_type) _type
#define LOGICAL_PTR(_p) (_p)
#define PHYSICAL_PTR(_p) (_p)
#define NULL_LOGICAL_PTR NULL
#endif /* USE_LOGICAL_PTR */
/*
* cosmos Thread APIs
*/
#ifdef WIN32
#else
typedef sem_t cosmos_thread_sem_t;
typedef char cosmos_thread_semName_t;
typedef pthread_mutex_t cosmos_thread_mutex_t;
typedef pthread_mutexattr_t cosmos_thread_mutex_attr_t;
typedef pthread_cond_t cosmos_thread_cond_t;
typedef pthread_condattr_t cosmos_thread_cond_attr_t;
typedef pthread_t cosmos_thread_t;
typedef pthread_attr_t cosmos_thread_attr_t;
extern cosmos_thread_mutex_attr_t cosmos_thread_mutex_attr_default;
extern cosmos_thread_cond_attr_t cosmos_thread_cond_attr_default;
extern cosmos_thread_attr_t cosmos_thread_attr_default;
#endif
#define MAXSEMAPHORENAME 256
#define COSMOS_THREAD_MUTEX_INIT_FOR_INTRAPROCESS PTHREAD_MUTEX_INITIALIZER
/* ***********************************************
* API for filelock *
* *********************************************** */
Four file_lock_control(FileDesc, int, int);
/* ***********************************************
* Init, Final API for thread *
* *********************************************** */
Four THM_threadOperator_Init(void);
Four THM_threadOperator_Final(void);
/* ***********************************************
* API for thread *
* *********************************************** */
Four cosmos_thread_create(cosmos_thread_t *tid, void*(*start_routine)(void*), void *arg, Four flag);
Four cosmos_thread_wait(cosmos_thread_t tid);
/* ***********************************************
* API for mutex *
* *********************************************** */
Four cosmos_thread_mutex_create(cosmos_thread_mutex_t *mp, Four flag);
Four cosmos_thread_mutex_destroy(cosmos_thread_mutex_t *mp);
Four cosmos_thread_mutex_lock(cosmos_thread_mutex_t *mp);
Four cosmos_thread_mutex_unlock(cosmos_thread_mutex_t *mp);
/* ***********************************************
* API for condition variable *
* *********************************************** */
Four cosmos_thread_cond_create(cosmos_thread_cond_t *cv, Four flag);
Four cosmos_thread_cond_destroy(cosmos_thread_cond_t *cv);
Four cosmos_thread_cond_wait(cosmos_thread_cond_t *cv, cosmos_thread_mutex_t *mp);
Four cosmos_thread_cond_signal(cosmos_thread_cond_t *cv);
/* ***********************************************
* API for semaphore *
* *********************************************** */
Four cosmos_thread_unnamed_sem_create(cosmos_thread_sem_t* returnSem, unsigned int value, Four flag);
Four cosmos_thread_named_sem_create(cosmos_thread_sem_t** returnSem, cosmos_thread_semName_t *semName, unsigned int value, Four flag);
Four cosmos_thread_named_sem_close(cosmos_thread_sem_t *sem);
Four cosmos_thread_unnamed_sem_destroy(cosmos_thread_sem_t *sem_ID);
Four cosmos_thread_named_sem_destroy(cosmos_thread_semName_t *sem_name);
Four cosmos_thread_sem_post(cosmos_thread_sem_t *sem);
Four cosmos_thread_sem_wait(cosmos_thread_sem_t *sem);
/*
** Type Definition for LRDS Mount Table Entry.
*/
#define LRDS_NUMOFCATALOGTABLES 3
typedef struct {
Two volId; /* volume identifier */
/* open relation numbers of catalog tables */
Four catalogTableOrn[LRDS_NUMOFCATALOGTABLES];
Four nMount; /* number of Mount */
} lrds_MountTableEntry;
#define LRDS_MOUNTTABLE lrds_shmPtr->MountTable
/*
** Type Definition for RelationInfo.
*/
typedef struct {
ObjectID catalogEntry; /* ObjectID of an entry in LRDS_SYSTABLES */
FileID fid; /* identifier of data file mapped to this relation */
Four nTuples; /* number of tuples */
Four maxTupleLen; /* maximum length of a tuple */
Two nIndexes; /* number of indexes */
Two nColumns; /* number of columns */
Two nVarColumns; /* number of variable-length columns */
char relName[MAXRELNAME]; /* relation name */
} RelationInfo;
/*
** Type Definition for IndexInfo.
*/
typedef struct {
One flag; /* flag */
One nKeys; /* number of keys */
Two extraDataLen; /* length of the extra data for an object */
MLGF_HashValue minMaxTypeVector; /* bit vector of flags indicating MIN/MAX of MBR for each attribute */
} MLGF_KeyDesc;
typedef struct {
IndexID iid; /* index identifier */
union {
KeyDesc btree; /* a key descriptor for btree */
MLGF_KeyDesc mlgf; /* a key descriptro for mlgf */
} kdesc;
Two colNo[MAXNUMKEYPARTS]; /* column numbers */
One indexType; /* index type */
} IndexInfo;
/*
** Type Definition for ColDesc
** - in-core memory data structure
** - ColInfo is used after converted to ColDesc
*/
typedef struct {
Two complexType; /* SM_COMPLEX_BASIC, SM_COMPLEX_SET */
Two type; /* SM_SHORT, SM_LONG, SM_FLOAT, ... */
Two varColNo; /* column number of variable-length columns */
Two fixedColNo; /* column number of fixed-length columns */
Four offset; /* offset of the field */
Four length; /* length of the field */
LOGICAL_PTR_TYPE(void *) auxInfo; /* auxiliary column information */
} ColDesc;
/*
* Type Definition for Latch Conditions
*/
typedef enum LatchMode_tag {
M_FREE=0x0,
M_SHARED=0x1,
M_EXCLUSIVE=0x2
} LatchMode;
typedef enum LatchConditional_tag {
M_UNCONDITIONAL=0x1,
M_CONDITIONAL=0x2,
M_INSTANT=0x4
} LatchConditional;
typedef struct pcell PIB; /* PIB - process information block structure */
struct pcell {
Four pID; /* process ID */
};
typedef struct tcell TCB; /* TCB - process control block structure */
struct tcell{
cosmos_thread_sem_t semID; /* semaphore no for thread. old: *semID */
cosmos_thread_semName_t semName[MAXSEMAPHORENAME];
/* data structure for latch algorithm */
LatchMode mode; /* latch request mode */
LatchConditional condition; /* check whether M_INSTANT or not */
LOGICAL_PTR_TYPE(TCB*) next; /* used for latch->queue structure */
Four nGranted; /* number of granted latch */
VarArray *grantedLatchStruct; /* keep information for granted latch */
};
typedef struct GlobalHandle_T {
Four procIndex;
Four threadIndex;
} GlobalHandle;
typedef struct {
One_Invariable sync; /* testandset target */
One dummy; /* alignment */
LatchMode mode; /* M_FREE, M_SHARD or M_EXCLUSIVE */
Two latchCounter; /* number of granted */
GlobalHandle grantedGlobalHandle; /* index of thread which owns this latch */
LOGICAL_PTR_TYPE(TCB*) queue; /* waiting queue */
cosmos_thread_mutex_t mutex;
} LATCH_TYPE;
/*
** Type Definition for LRDS Open Relation Entry.
*/
typedef struct {
Four count; /* # of opens */
Four clusteringIndex; /* array index of clustering index on IndexInfo */
RelationInfo ri; /* information for relation */
LOGICAL_PTR_TYPE(IndexInfo*) ii; /* information for indexes */
LOGICAL_PTR_TYPE(ColDesc*) cdesc; /* array of column descriptors */
Boolean isCatalog; /* is this a catalog relation? (flag) */
LATCH_TYPE latch; /* support mutex for an entry of RelTable */
} lrds_RelTableEntry;
/*
** Type Definition for lrds_UserOpenRelTableEntry
** - open relation per process
** - 'sysOrn' is an index of an entry in LRDS_RELTABLE_FOR_TMP_RELS
** if it is a temporary relation. 'sysOrn' is an index of an entry
** in LRDS_RELTABLE if it is a ordinary relation.
**
*/
typedef struct {
Four sysOrn; /* system open relation number */
Four count; /* # of opens */
Boolean tmpRelationFlag; /* Is this a temporary relation? */
} lrds_UserOpenRelTableEntry;
#define LRDS_RELTABLE (lrds_shmPtr->lrdsRelTable)
#define LRDS_RELTABLE_FOR_TMP_RELS(_handle) (perThreadTable[_handle].lrdsDS.lrdsRelTableForTmpRelations)
#define LRDS_USEROPENRELTABLE(_handle) (perThreadTable[_handle].lrdsDS.lrdsUserOpenRelTable)
#define LRDS_GET_RELTABLE_ENTRY(_handle, orn) \
((LRDS_USEROPENRELTABLE(_handle)[orn].tmpRelationFlag) ? &LRDS_RELTABLE_FOR_TMP_RELS(_handle)[LRDS_USEROPENRELTABLE(_handle)[orn].sysOrn]: &LRDS_RELTABLE[LRDS_USEROPENRELTABLE(_handle)[orn].sysOrn])
#define LRDS_IS_TEMPORARY_RELATION(_handle, orn) (LRDS_USEROPENRELTABLE(_handle)[orn].tmpRelationFlag)
#define LRDS_GET_IDXINFO_FROM_RELTABLE_ENTRY(_re) ((IndexInfo*)PHYSICAL_PTR(_re->ii))
#define LRDS_GET_COLDESC_FROM_RELTABLE_ENTRY(_re) ((ColDesc*)PHYSICAL_PTR(_re->cdesc))
Four SM_MLGF_InsertIndexEntry(Four, IndexID*, MLGF_KeyDesc*, MLGF_HashValue[], ObjectID*, void*, LockParameter*);
Four SM_MLGF_DeleteIndexEntry(Four, IndexID*, MLGF_KeyDesc*, MLGF_HashValue[], ObjectID*, void*, LockParameter*);
/*
** Type Definition for LRDS Scan Table Entry.
*/
typedef struct {
Four orn; /* open relation number */
Four smScanId; /* Scan Manager Level Scan Identifier */
Four nBools; /* # of boolean expressions */
#ifdef __cplusplus
BoolExp *boolexp; /* array of boolean expressions */
#else
BoolExp *bool; /* array of boolean expressions */
#endif
TupleID tid; /* a current tuple id */
} lrds_ScanTableEntry;
/* access lrdsScanTable entry */
#define LRDS_SCANTABLE(_handle) ((lrds_ScanTableEntry*)perThreadTable[_handle].lrdsDS.lrdsScanTable.ptr)
/*
** Type Definition for LRDS Collection Scan Table Etnry.
*/
typedef struct {
Four ornOrScanId; /* open relation no or relation scan id for the relation containing the set */
Boolean useScanFlag; /* use relation scan if TRUE */
Two colNo; /* column on which the set is defined */
TupleID tid; /* tuple containing the set */
Four ithElementToRead; /* points to an element to read */
Four ithElementPrevRead; /* points to the first element of previous read */
} lrds_CollectionScanTableEntry;
/* access lrdsCollectionScanTable entry */
#define LRDS_COLLECTIONSCANTABLE(_handle) ((lrds_CollectionScanTableEntry*)perThreadTable[_handle].lrdsDS.lrdsCollectionScanTable.ptr)
/*
* Type Definition for HeapWord
* HeapWord is a basic unit of a heap.
*/
union _HeapWord {
LOGICAL_PTR_TYPE(union _HeapWord*) ptr; /* pointer to the next control HeapWord. */
MEMORY_ALIGN_TYPE dummay; /* alignment unit */
};
typedef union _HeapWord HeapWord;
/*
* Type Definition for subheap header
* For each subheap, a subheap header is defined.
* The subheap header is dynamically allocated at once with the subheap.
*/
struct _SubheapHdr {
Four count; /* # of heap words in the heap */
LOGICAL_PTR_TYPE(HeapWord*) searchPtr; /* start position of search */
LOGICAL_PTR_TYPE(struct _SubheapHdr*) nextSubheap; /* pointer to next subheap */
};
typedef struct _SubheapHdr SubheapHdr;
/*
* Type definition for Heap.
* Heap consists of the subheaps of same size.
*/
struct _Heap {
LATCH_TYPE latch; /* latch for allocate/free one element from a pool */
Four elemSize; /* element size */
Four maxWordsInSubheap; /* maximum heap words in a subheap */
LOGICAL_PTR_TYPE(SubheapHdr*) subheapPtr; /* pointer to the first subheap */
};
typedef struct _Heap Heap;
/*
* Type Definition for subpool header
* For each subpool, a subpool header is defined.
* The subpool header is dynamically allocated at once with the subpool.
*/
struct _SubpoolHdr {
Four count; /* # of elements in the freed list */
LOGICAL_PTR_TYPE(char*) firstElem; /* pointer to the first freed element */
/* freed elements make a linked list. */
LOGICAL_PTR_TYPE(struct _SubpoolHdr*) nextSubpool; /* pointer to next subpool */
};
typedef struct _SubpoolHdr SubpoolHdr;
/*
* Type definition for Pool.
* Pool consists of the subpools of same size.
*/
struct _Pool {
LATCH_TYPE latch; /* latch for allocate/free one element from a pool */
Four elemSize; /* element size */
Four maxElemInSubpool; /* maximum elements in subpool */
Four usedElemInPool; /* the # of the used elements */
LOGICAL_PTR_TYPE(SubpoolHdr*) subpoolPtr; /* pointer to the first subpool */
};
typedef struct _Pool Pool;
/*
* Shared Memory Data Structures
*/
typedef struct {
LATCH_TYPE latch_openRelation; /* latch for mount table and relation table */
lrds_MountTableEntry lrdsMountTable[MAXNUMOFVOLS]; /* Mount Table of LRDS */
lrds_RelTableEntry lrdsRelTable[MAXNUMOFOPENRELS]; /* Open Relation Table of LRDS */
Heap lrdsColumnTableHeap; /* heap for Column Table */
Heap lrdsIndexTableHeap; /* heap for Index Table */
Pool lrdsOrderedSetAuxColInfoPool; /* pool for Auxiliary Column Information of Ordered Set */
} LRDS_SHM;
/*
* Per Thread Data Structures
*/
#define CATALOGTABLESIZE 3
#define CATALOGTABLEENTRYSIZE 256
#define LRDS_NUM_OF_ENTRIES_OF_RELTABLE_FOR_TMP_RELS MAX_NUM_OF_TMP_RELS
#define LRDS_NUM_OF_ENTRIES_OF_USEROPENRELTABLE MAX_NUM_OF_USEROPENRELS
#define LRDS_NUM_OF_ENTRIES_OF_USERMOUNTTABLE MAXNUMOFVOLS
#define MAX_NUM_OF_TMP_RELS 10
#define MAX_NUM_OF_USEROPENRELS 400
#define MAX_LRDS_BLKLD_TABLE_SIZE 10
typedef struct LocalSubpoolHdr_tag LocalSubpoolHdr;
struct LocalSubpoolHdr_tag {
Four count; /* # of elements in the freed list */
char *firstElem; /* pointer to the first freed element */
/* freed elements make a linked list. */
LocalSubpoolHdr *nextSubpool; /* pointer to next subpool */
};
struct _LocalPool {
/* No needs for latch. Used only locally */
Four elemSize; /* element size */
Four maxElemInSubpool; /* maximum elements in subpool */
LocalSubpoolHdr *subpoolPtr; /* pointer to the first subpool */
};
typedef struct _LocalPool LocalPool;
/*
* Type definition for LocalHeap.
* Heap consists of the subheaps of same size.
*/
typedef union LocalHeapWord_tag LocalHeapWord;
union LocalHeapWord_tag {
LocalHeapWord *ptr; /* pointer to the next control HeapWord. */
MEMORY_ALIGN_TYPE dummay; /* alignment unit */
};
typedef struct LocalSubheapHdr_tag LocalSubheapHdr;
struct LocalSubheapHdr_tag {
Four count; /* # of heap words in the heap */
LocalHeapWord *searchPtr; /* start position of search */
LocalSubheapHdr *nextSubheap; /* pointer to next subheap */
};
struct _LocalHeap {
Four elemSize; /* element size */
Four maxWordsInSubheap; /* maximum heap words in a subheap */
LocalSubheapHdr *subheapPtr; /* pointer to the first subheap */
};
typedef struct _LocalHeap LocalHeap;
typedef struct LRDS_PerThreadDS_T_tag {
/* Catalog Table Names */
char catalogTable[CATALOGTABLESIZE][CATALOGTABLEENTRYSIZE];
KeyDesc lrds_SysCountersCounterNameIndexKdesc;
VarArray lrdsScanTable; /* Scan Table of LRDS */
VarArray lrdsSetScanTable; /* Set Scan Table of LRDS */
VarArray lrdsOrderedSetScanTable; /* Ordered Set Scan Table of LRDS */
VarArray lrdsCollectionScanTable; /* Collection Scan Table of LRDS */
LocalHeap lrdsBoolTableHeap; /* heap for Boolean Table */
LocalPool lrdsOrderedSetAuxColInfoLocalPool; /* AuxColInfo Pool for Ordered Set */
LocalPool lrdsOrderedSetElementLengthLocalPool;
/* relation table for temporary relations */
lrds_RelTableEntry lrdsRelTableForTmpRelations[LRDS_NUM_OF_ENTRIES_OF_RELTABLE_FOR_TMP_RELS];
/* User Open Relation Table of LRDS */
lrds_UserOpenRelTableEntry lrdsUserOpenRelTable[LRDS_NUM_OF_ENTRIES_OF_USEROPENRELTABLE];
lrds_MountTableEntry lrds_userMountTable[LRDS_NUM_OF_ENTRIES_OF_USERMOUNTTABLE];
Two_Invariable lrdsformat_tmpTwo;
Four_Invariable lrdsformat_tmpFour;
Eight_Invariable lrdsformat_tmpEight;
char dummy_Bulkload[2240];
/* XA Interface */
LRDSXAscanStatus lrds_xa_scanStatus;
Four lrds_xa_preparedNum;
Four lrds_xa_currentPos;
LRDS_XA_XID* lrds_xa_preparedList;
Four lrds_xa_volId;
} LRDS_PerThreadDS_T;
typedef struct PerThreadTableEntry_T_tag {
LRDS_PerThreadDS_T lrdsDS;
char dummy_Thread[238696]; /* Be careful the size of dummy */
} PerThreadTableEntry_T;
/*
* LRDS Reset/Get number of Disk IO
*/
Four LRDS_ResetNumberOfDiskIO(Four);
Four LRDS_GetNumberOfDiskIO(Four, Four* , Four* );
/*
* Global Variables
*/
extern LRDS_SHM *lrds_shmPtr;
extern PerThreadTableEntry_T perThreadTable[MAXTHREADS];
/* this global variables is eliminated ,for multithread
extern VarArray lrdsScanTable;
===> perThreadTable[handle].lrdsDS.lrdsScanTable
extern VarArray lrdsCollectionScanTable;
===> perThreadTable[handle].lrdsDS.lrdsCollectionScanTable
extern lrds_UserOpenRelTableEntry lrdsUserOpenRelTable[];
===> perThreadTable[handle].lrdsDS.lrdsUserOpenRelTable[LRDS_NUM_OF_ENTRIES_OF_USEROPENRELTABLE]
extern lrds_RelTableEntry lrdsRelTableForTmpRelations[];
===> perThreadTable[handle].lrdsDS.lrdsRelTableForTmpRelations[LRDS_NUM_OF_ENTRIES_OF_RELTABLE_FOR_TMP_RELS]
*/
/* Is 'x' the valid scan identifier? */
#define LRDS_VALID_ORN(_handle, x) ( ((x) >= 0) && ((x) < LRDS_NUM_OF_ENTRIES_OF_USEROPENRELTABLE) && \
!LRDS_IS_UNUSED_ENTRY_OF_USEROPENRELTABLE(_handle, x) )
#define LRDS_VALID_SCANID(_handle, x) ( ((x) >= 0) && ((x) < perThreadTable[_handle].lrdsDS.lrdsScanTable.nEntries) && \
LRDS_SCANTABLE(_handle)[(x)].orn != NIL )
/*
* APIs for large files
*/
typedef Four filepos_t;
#ifdef USE_LARGE_FILE
#if (defined(AIX64) || defined(SOLARIS64) || defined(LINUX64)) && !defined(EIGHT_NOT_DEFINED)
#define Util_fopen fopen64
#elif (defined(WIN64) || defined(WIN32)) && !defined(EIGHT_NOT_DEFINED)
#define Util_fopen fopen
#else
#define Util_fopen fopen
#endif
#else
#define Util_fopen fopen
#endif
#define Util_fclose fclose
#define Util_fseek fseek
#define Util_ftell ftell
#define Util_fprintf fprintf
#define Util_fscanf fscanf
#define Util_fgets(string, n, stream) fgets(string, n, stream)
#define Util_fputs(string, stream) fputs(string, stream)
#define Util_fread(buffer, size, count, stream) fread(buffer, size, count, stream)
#define Util_fwrite(buffer, size, count, stream) fwrite(buffer, size, count, stream)
#define Util_fflush(stream) fflush(stream)
#ifdef __cplusplus
}
#endif
#endif /* __COSMOS_R_H__ */
| 42.475279 | 198 | 0.645739 | [
"object",
"vector"
] |
0d7bc8d992193f4b8c2328aff9666574cf15960a | 11,420 | h | C | src/SOS/lldbplugin/swift-4.1/lldb/Utility/CleanUp.h | felipepessoto/diagnostics | 66d976fda64bb9dc6c356de21c2a459833c74de6 | [
"MIT"
] | 427 | 2018-05-29T14:21:02.000Z | 2022-03-16T03:17:54.000Z | src/SOS/lldbplugin/swift-4.1/lldb/Utility/CleanUp.h | felipepessoto/diagnostics | 66d976fda64bb9dc6c356de21c2a459833c74de6 | [
"MIT"
] | 25 | 2018-07-23T08:34:15.000Z | 2021-11-05T07:13:36.000Z | src/SOS/lldbplugin/swift-4.1/lldb/Utility/CleanUp.h | felipepessoto/diagnostics | 66d976fda64bb9dc6c356de21c2a459833c74de6 | [
"MIT"
] | 52 | 2018-07-19T19:57:32.000Z | 2022-03-11T16:05:38.000Z | //===-- CleanUp.h -----------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef liblldb_CleanUp_h_
#define liblldb_CleanUp_h_
#include "lldb/lldb-public.h"
#include <functional>
namespace lldb_utility {
//----------------------------------------------------------------------
// Templated class that guarantees that a cleanup callback function will
// be called. The cleanup function will be called once under the
// following conditions:
// - when the object goes out of scope
// - when the user explicitly calls clean.
// - the current value will be cleaned up when a new value is set using
// set(T value) as long as the current value hasn't already been cleaned.
//
// This class is designed to be used with simple types for type T (like
// file descriptors, opaque handles, pointers, etc). If more complex
// type T objects are desired, we need to probably specialize this class
// to take "const T&" for all input T parameters. Yet if a type T is
// complex already it might be better to build the cleanup functionality
// into T.
//
// The cleanup function must take one argument that is of type T.
// The calback function return type is R. The return value is currently
// needed for "CallbackType". If there is an easy way to get around the
// need for the return value we can change this class.
//
// The two template parameters are:
// T - The variable type of value that will be stored and used as the
// sole argument for the cleanup callback.
// R - The return type for the cleanup function.
//
// EXAMPLES
// // Use with file handles that get opened where you want to close
// // them. Below we use "int open(const char *path, int oflag, ...)"
// // which returns an integer file descriptor. -1 is the invalid file
// // descriptor so to make an object that will call "int close(int fd)"
// // automatically we can use:
//
// CleanUp <int, int> fd(open("/tmp/a.txt", O_RDONLY, 0), -1, close);
//
// // malloc/free example
// CleanUp <void *, void> malloced_bytes(malloc(32), NULL, free);
//----------------------------------------------------------------------
template <typename T, typename R = void> class CleanUp {
public:
typedef T value_type;
typedef std::function<R(value_type)> CallbackType;
//----------------------------------------------------------------------
// Constructor that sets the current value only. No values are
// considered to be invalid and the cleanup function will be called
// regardless of the value of m_current_value.
//----------------------------------------------------------------------
CleanUp(value_type value, CallbackType callback)
: m_current_value(value), m_invalid_value(), m_callback(callback),
m_callback_called(false), m_invalid_value_is_valid(false) {}
//----------------------------------------------------------------------
// Constructor that sets the current value and also the invalid value.
// The cleanup function will be called on "m_value" as long as it isn't
// equal to "m_invalid_value".
//----------------------------------------------------------------------
CleanUp(value_type value, value_type invalid, CallbackType callback)
: m_current_value(value), m_invalid_value(invalid), m_callback(callback),
m_callback_called(false), m_invalid_value_is_valid(true) {}
//----------------------------------------------------------------------
// Automatically cleanup when this object goes out of scope.
//----------------------------------------------------------------------
~CleanUp() { clean(); }
//----------------------------------------------------------------------
// Access the value stored in this class
//----------------------------------------------------------------------
value_type get() { return m_current_value; }
//----------------------------------------------------------------------
// Access the value stored in this class
//----------------------------------------------------------------------
const value_type get() const { return m_current_value; }
//----------------------------------------------------------------------
// Reset the owned value to "value". If a current value is valid and
// the cleanup callback hasn't been called, the previous value will
// be cleaned up (see void CleanUp::clean()).
//----------------------------------------------------------------------
void set(const value_type value) {
// Cleanup the current value if needed
clean();
// Now set the new value and mark our callback as not called
m_callback_called = false;
m_current_value = value;
}
//----------------------------------------------------------------------
// Checks is "m_current_value" is valid. The value is considered valid
// no invalid value was supplied during construction of this object or
// if an invalid value was supplied and "m_current_value" is not equal
// to "m_invalid_value".
//
// Returns true if "m_current_value" is valid, false otherwise.
//----------------------------------------------------------------------
bool is_valid() const {
if (m_invalid_value_is_valid)
return m_current_value != m_invalid_value;
return true;
}
//----------------------------------------------------------------------
// This function will call the cleanup callback provided in the
// constructor one time if the value is considered valid (See is_valid()).
// This function sets m_callback_called to true so we don't call the
// cleanup callback multiple times on the same value.
//----------------------------------------------------------------------
void clean() {
if (m_callback && !m_callback_called) {
m_callback_called = true;
if (is_valid())
m_callback(m_current_value);
}
}
//----------------------------------------------------------------------
// Cancels the cleanup that would have been called on "m_current_value"
// if it was valid. This function can be used to release the value
// contained in this object so ownership can be transferred to the caller.
//----------------------------------------------------------------------
value_type release() {
m_callback_called = true;
return m_current_value;
}
private:
value_type m_current_value;
const value_type m_invalid_value;
CallbackType m_callback;
bool m_callback_called;
bool m_invalid_value_is_valid;
// Outlaw default constructor, copy constructor and the assignment operator
DISALLOW_COPY_AND_ASSIGN(CleanUp);
};
template <typename T, typename R, typename A0> class CleanUp2 {
public:
typedef T value_type;
typedef std::function<R(value_type, A0)> CallbackType;
//----------------------------------------------------------------------
// Constructor that sets the current value only. No values are
// considered to be invalid and the cleanup function will be called
// regardless of the value of m_current_value.
//----------------------------------------------------------------------
CleanUp2(value_type value, CallbackType callback, A0 arg)
: m_current_value(value), m_invalid_value(), m_callback(callback),
m_callback_called(false), m_invalid_value_is_valid(false),
m_argument(arg) {}
//----------------------------------------------------------------------
// Constructor that sets the current value and also the invalid value.
// The cleanup function will be called on "m_value" as long as it isn't
// equal to "m_invalid_value".
//----------------------------------------------------------------------
CleanUp2(value_type value, value_type invalid, CallbackType callback, A0 arg)
: m_current_value(value), m_invalid_value(invalid), m_callback(callback),
m_callback_called(false), m_invalid_value_is_valid(true),
m_argument(arg) {}
//----------------------------------------------------------------------
// Automatically cleanup when this object goes out of scope.
//----------------------------------------------------------------------
~CleanUp2() { clean(); }
//----------------------------------------------------------------------
// Access the value stored in this class
//----------------------------------------------------------------------
value_type get() { return m_current_value; }
//----------------------------------------------------------------------
// Access the value stored in this class
//----------------------------------------------------------------------
const value_type get() const { return m_current_value; }
//----------------------------------------------------------------------
// Reset the owned value to "value". If a current value is valid and
// the cleanup callback hasn't been called, the previous value will
// be cleaned up (see void CleanUp::clean()).
//----------------------------------------------------------------------
void set(const value_type value) {
// Cleanup the current value if needed
clean();
// Now set the new value and mark our callback as not called
m_callback_called = false;
m_current_value = value;
}
//----------------------------------------------------------------------
// Checks is "m_current_value" is valid. The value is considered valid
// no invalid value was supplied during construction of this object or
// if an invalid value was supplied and "m_current_value" is not equal
// to "m_invalid_value".
//
// Returns true if "m_current_value" is valid, false otherwise.
//----------------------------------------------------------------------
bool is_valid() const {
if (m_invalid_value_is_valid)
return m_current_value != m_invalid_value;
return true;
}
//----------------------------------------------------------------------
// This function will call the cleanup callback provided in the
// constructor one time if the value is considered valid (See is_valid()).
// This function sets m_callback_called to true so we don't call the
// cleanup callback multiple times on the same value.
//----------------------------------------------------------------------
void clean() {
if (m_callback && !m_callback_called) {
m_callback_called = true;
if (is_valid())
m_callback(m_current_value, m_argument);
}
}
//----------------------------------------------------------------------
// Cancels the cleanup that would have been called on "m_current_value"
// if it was valid. This function can be used to release the value
// contained in this object so ownership can be transferred to the caller.
//----------------------------------------------------------------------
value_type release() {
m_callback_called = true;
return m_current_value;
}
private:
value_type m_current_value;
const value_type m_invalid_value;
CallbackType m_callback;
bool m_callback_called;
bool m_invalid_value_is_valid;
A0 m_argument;
// Outlaw default constructor, copy constructor and the assignment operator
DISALLOW_COPY_AND_ASSIGN(CleanUp2);
};
} // namespace lldb_utility
#endif // #ifndef liblldb_CleanUp_h_
| 43.587786 | 80 | 0.53345 | [
"object"
] |
0d8b967c8b2ee04da70390fcfa656fda40053431 | 85,197 | c | C | components/network/ble/blemesh_model/bfl_ble_mesh/btc/btc_ble_mesh_prov.c | bouffalolab/bl_iot_sdk_matter | c2b633bccfb12a26a36c705958df4714369d30e2 | [
"Apache-2.0"
] | null | null | null | components/network/ble/blemesh_model/bfl_ble_mesh/btc/btc_ble_mesh_prov.c | bouffalolab/bl_iot_sdk_matter | c2b633bccfb12a26a36c705958df4714369d30e2 | [
"Apache-2.0"
] | null | null | null | components/network/ble/blemesh_model/bfl_ble_mesh/btc/btc_ble_mesh_prov.c | bouffalolab/bl_iot_sdk_matter | c2b633bccfb12a26a36c705958df4714369d30e2 | [
"Apache-2.0"
] | null | null | null | // Copyright 2017-2019 Espressif Systems (Shanghai) PTE LTD
// Additional Copyright 2016-2020 Bouffalolab
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <string.h>
#include <errno.h>
#include "btc_ble_mesh_prov.h"
//#include "btc_ble_mesh_config_model.h"
//#include "btc_ble_mesh_health_model.h"
#include "btc_ble_mesh_generic_model.h"
//#include "btc_ble_mesh_time_scene_model.h"
//#include "btc_ble_mesh_sensor_model.h"
#include "btc_ble_mesh_lighting_model.h"
#include "adv.h"
//#include "mesh_kernel.h"
//#include "mesh_proxy.h"
#include "mesh.h"
#include "access.h"
//#include "prov.h"
//#include "proxy_server.h"
//#include "proxy_client.h"
//#include "proxy.h"
//#include "provisioner_prov.h"
//#include "provisioner_main.h"
//#include "cfg_cli.h"
//#include "health_cli.h"
//#include "cfg_srv.h"
//#include "health_srv.h"
#include "generic_client.h"
#include "lighting_client.h"
//#include "sensor_client.h"
//#include "time_scene_client.h"
#include "client_common.h"
#include "state_binding.h"
#include "local_operation.h"
//#include "bfl_ble_mesh_common_api.h"
#include "bfl_ble_mesh_provisioning_api.h"
#include "bfl_ble_mesh_networking_api.h"
static inline void btc_ble_mesh_prov_cb_to_app(bfl_ble_mesh_prov_cb_event_t event,
bfl_ble_mesh_prov_cb_param_t *param)
{
bfl_ble_mesh_prov_cb_t btc_ble_mesh_cb =
(bfl_ble_mesh_prov_cb_t)btc_profile_cb_get(BTC_PID_PROV);
if (btc_ble_mesh_cb) {
btc_ble_mesh_cb(event, param);
}
}
static inline void btc_ble_mesh_model_cb_to_app(bfl_ble_mesh_model_cb_event_t event,
bfl_ble_mesh_model_cb_param_t *param)
{
bfl_ble_mesh_model_cb_t btc_ble_mesh_cb =
(bfl_ble_mesh_model_cb_t)btc_profile_cb_get(BTC_PID_MODEL);
if (btc_ble_mesh_cb) {
btc_ble_mesh_cb(event, param);
}
}
void btc_ble_mesh_prov_arg_deep_copy(btc_msg_t *msg, void *p_dest, void *p_src)
{
btc_ble_mesh_prov_args_t *dst = (btc_ble_mesh_prov_args_t *)p_dest;
btc_ble_mesh_prov_args_t *src = (btc_ble_mesh_prov_args_t *)p_src;
if (!msg || !dst || !src) {
BT_ERR("%s, Invalid parameter", __func__);
return;
}
switch (msg->act) {
case BTC_BLE_MESH_ACT_PROXY_CLIENT_ADD_FILTER_ADDR:
BT_DBG("%s, BTC_BLE_MESH_ACT_PROXY_CLIENT_ADD_FILTER_ADDR", __func__);
dst->proxy_client_add_filter_addr.addr = (uint16_t *)bt_mesh_calloc(src->proxy_client_add_filter_addr.addr_num << 1);
if (dst->proxy_client_add_filter_addr.addr) {
memcpy(dst->proxy_client_add_filter_addr.addr, src->proxy_client_add_filter_addr.addr,
src->proxy_client_add_filter_addr.addr_num << 1);
} else {
BT_ERR("%s, Failed to allocate memory, act %d", __func__, msg->act);
}
break;
case BTC_BLE_MESH_ACT_PROXY_CLIENT_REMOVE_FILTER_ADDR:
BT_DBG("%s, BTC_BLE_MESH_ACT_PROXY_CLIENT_REMOVE_FILTER_ADDR", __func__);
dst->proxy_client_remove_filter_addr.addr = bt_mesh_calloc(src->proxy_client_remove_filter_addr.addr_num << 1);
if (dst->proxy_client_remove_filter_addr.addr) {
memcpy(dst->proxy_client_remove_filter_addr.addr, src->proxy_client_remove_filter_addr.addr,
src->proxy_client_remove_filter_addr.addr_num << 1);
} else {
BT_ERR("%s, Failed to allocate memory, act %d", __func__, msg->act);
}
break;
case BTC_BLE_MESH_ACT_PROVISIONER_STORE_NODE_COMP_DATA:
BT_DBG("%s, BTC_BLE_MESH_ACT_PROVISIONER_STORE_NODE_COMP_DATA", __func__);
dst->store_node_comp_data.data = bt_mesh_calloc(src->store_node_comp_data.length);
if (dst->store_node_comp_data.data) {
memcpy(dst->store_node_comp_data.data, src->store_node_comp_data.data, src->store_node_comp_data.length);
} else {
BT_ERR("%s, Failed to allocate memory, act %d", __func__, msg->act);
}
break;
default:
BT_DBG("%s, Unknown deep copy act %d", __func__, msg->act);
break;
}
}
static void btc_ble_mesh_prov_arg_deep_free(btc_msg_t *msg)
{
btc_ble_mesh_prov_args_t *arg = NULL;
if (!msg || !msg->arg) {
BT_ERR("%s, Invalid parameter", __func__);
return;
}
arg = (btc_ble_mesh_prov_args_t *)(msg->arg);
switch (msg->act) {
case BTC_BLE_MESH_ACT_PROXY_CLIENT_ADD_FILTER_ADDR:
if (arg->proxy_client_add_filter_addr.addr) {
bt_mesh_free(arg->proxy_client_add_filter_addr.addr);
}
break;
case BTC_BLE_MESH_ACT_PROXY_CLIENT_REMOVE_FILTER_ADDR:
if (arg->proxy_client_remove_filter_addr.addr) {
bt_mesh_free(arg->proxy_client_remove_filter_addr.addr);
}
break;
case BTC_BLE_MESH_ACT_PROVISIONER_STORE_NODE_COMP_DATA:
if (arg->store_node_comp_data.data) {
bt_mesh_free(arg->store_node_comp_data.data);
}
break;
default:
break;
}
}
void btc_ble_mesh_model_arg_deep_copy(btc_msg_t *msg, void *p_dest, void *p_src)
{
btc_ble_mesh_model_args_t *dst = (btc_ble_mesh_model_args_t *)p_dest;
btc_ble_mesh_model_args_t *src = (btc_ble_mesh_model_args_t *)p_src;
if (!msg || !dst || !src) {
BT_ERR("%s, Invalid parameter", __func__);
return;
}
switch (msg->act) {
case BTC_BLE_MESH_ACT_SERVER_MODEL_SEND:
case BTC_BLE_MESH_ACT_CLIENT_MODEL_SEND: {
BT_DBG("%s, BTC_BLE_MESH_ACT_MODEL_SEND, src->model_send.length = %d", __func__, src->model_send.length);
dst->model_send.data = src->model_send.length ? (uint8_t *)bt_mesh_malloc(src->model_send.length) : NULL;
dst->model_send.ctx = bt_mesh_malloc(sizeof(bfl_ble_mesh_msg_ctx_t));
if (src->model_send.length) {
if (dst->model_send.data) {
memcpy(dst->model_send.data, src->model_send.data, src->model_send.length);
} else {
BT_ERR("%s, Failed to allocate memory, act %d", __func__, msg->act);
}
}
if (dst->model_send.ctx) {
memcpy(dst->model_send.ctx, src->model_send.ctx, sizeof(bfl_ble_mesh_msg_ctx_t));
} else {
BT_ERR("%s, Failed to allocate memory, act %d", __func__, msg->act);
}
break;
}
case BTC_BLE_MESH_ACT_SERVER_MODEL_UPDATE_STATE:
BT_DBG("%s, BTC_BLE_MESH_ACT_SERVER_MODEL_UPDATE_STATE", __func__);
dst->model_update_state.value = bt_mesh_malloc(sizeof(bfl_ble_mesh_server_state_value_t));
if (dst->model_update_state.value) {
memcpy(dst->model_update_state.value, src->model_update_state.value,
sizeof(bfl_ble_mesh_server_state_value_t));
} else {
BT_ERR("%s, Failed to allocate memory, act %d", __func__, msg->act);
}
break;
default:
BT_DBG("%s, Unknown deep copy act %d", __func__, msg->act);
break;
}
}
static void btc_ble_mesh_model_arg_deep_free(btc_msg_t *msg)
{
btc_ble_mesh_model_args_t *arg = NULL;
if (!msg || !msg->arg) {
BT_ERR("%s, Invalid parameter", __func__);
return;
}
arg = (btc_ble_mesh_model_args_t *)(msg->arg);
switch (msg->act) {
case BTC_BLE_MESH_ACT_SERVER_MODEL_SEND:
case BTC_BLE_MESH_ACT_CLIENT_MODEL_SEND:
if (arg->model_send.data) {
bt_mesh_free(arg->model_send.data);
}
if (arg->model_send.ctx) {
bt_mesh_free(arg->model_send.ctx);
}
break;
case BTC_BLE_MESH_ACT_SERVER_MODEL_UPDATE_STATE:
if (arg->model_update_state.value) {
bt_mesh_free(arg->model_update_state.value);
}
break;
default:
break;
}
return;
}
static void btc_ble_mesh_model_copy_req_data(btc_msg_t *msg, void *p_dest, void *p_src)
{
bfl_ble_mesh_model_cb_param_t *p_dest_data = (bfl_ble_mesh_model_cb_param_t *)p_dest;
bfl_ble_mesh_model_cb_param_t *p_src_data = (bfl_ble_mesh_model_cb_param_t *)p_src;
if (!msg || !p_src_data || !p_dest_data) {
BT_ERR("%s, Invalid parameter", __func__);
return;
}
switch (msg->act) {
case BFL_BLE_MESH_MODEL_OPERATION_EVT: {
if (p_src_data->model_operation.ctx && p_src_data->model_operation.msg) {
p_dest_data->model_operation.ctx = bt_mesh_malloc(sizeof(bfl_ble_mesh_msg_ctx_t));
p_dest_data->model_operation.msg = p_src_data->model_operation.length ? (uint8_t *)bt_mesh_malloc(p_src_data->model_operation.length) : NULL;
if (p_dest_data->model_operation.ctx) {
memcpy(p_dest_data->model_operation.ctx, p_src_data->model_operation.ctx, sizeof(bfl_ble_mesh_msg_ctx_t));
} else {
BT_ERR("%s, Failed to allocate memory, act %d", __func__, msg->act);
}
if (p_src_data->model_operation.length) {
if (p_dest_data->model_operation.msg) {
memcpy(p_dest_data->model_operation.msg, p_src_data->model_operation.msg, p_src_data->model_operation.length);
} else {
BT_ERR("%s, Failed to allocate memory, act %d", __func__, msg->act);
}
}
}
break;
}
case BFL_BLE_MESH_CLIENT_MODEL_RECV_PUBLISH_MSG_EVT: {
if (p_src_data->client_recv_publish_msg.ctx && p_src_data->client_recv_publish_msg.msg) {
p_dest_data->client_recv_publish_msg.ctx = bt_mesh_malloc(sizeof(bfl_ble_mesh_msg_ctx_t));
p_dest_data->client_recv_publish_msg.msg = p_src_data->client_recv_publish_msg.length ? (uint8_t *)bt_mesh_malloc(p_src_data->client_recv_publish_msg.length) : NULL;
if (p_dest_data->client_recv_publish_msg.ctx) {
memcpy(p_dest_data->client_recv_publish_msg.ctx, p_src_data->client_recv_publish_msg.ctx, sizeof(bfl_ble_mesh_msg_ctx_t));
} else {
BT_ERR("%s, Failed to allocate memory, act %d", __func__, msg->act);
}
if (p_src_data->client_recv_publish_msg.length) {
if (p_dest_data->client_recv_publish_msg.msg) {
memcpy(p_dest_data->client_recv_publish_msg.msg, p_src_data->client_recv_publish_msg.msg, p_src_data->client_recv_publish_msg.length);
} else {
BT_ERR("%s, Failed to allocate memory, act %d", __func__, msg->act);
}
}
}
break;
}
case BFL_BLE_MESH_MODEL_SEND_COMP_EVT: {
if (p_src_data->model_send_comp.ctx) {
p_dest_data->model_send_comp.ctx = bt_mesh_malloc(sizeof(bfl_ble_mesh_msg_ctx_t));
if (p_dest_data->model_send_comp.ctx) {
memcpy(p_dest_data->model_send_comp.ctx, p_src_data->model_send_comp.ctx, sizeof(bfl_ble_mesh_msg_ctx_t));
} else {
BT_ERR("%s, Failed to allocate memory, act %d", __func__, msg->act);
}
}
break;
}
case BFL_BLE_MESH_CLIENT_MODEL_SEND_TIMEOUT_EVT: {
if (p_src_data->client_send_timeout.ctx) {
p_dest_data->client_send_timeout.ctx = bt_mesh_malloc(sizeof(bfl_ble_mesh_msg_ctx_t));
if (p_dest_data->client_send_timeout.ctx) {
memcpy(p_dest_data->client_send_timeout.ctx, p_src_data->client_send_timeout.ctx, sizeof(bfl_ble_mesh_msg_ctx_t));
} else {
BT_ERR("%s, Failed to allocate memory, act %d", __func__, msg->act);
}
}
break;
}
default:
break;
}
}
static void btc_ble_mesh_model_free_req_data(btc_msg_t *msg)
{
bfl_ble_mesh_model_cb_param_t *arg = NULL;
if (!msg || !msg->arg) {
BT_ERR("%s, Invalid parameter", __func__);
return;
}
arg = (bfl_ble_mesh_model_cb_param_t *)(msg->arg);
switch (msg->act) {
case BFL_BLE_MESH_MODEL_OPERATION_EVT: {
if (arg->model_operation.msg) {
bt_mesh_free(arg->model_operation.msg);
}
if (arg->model_operation.ctx) {
bt_mesh_free(arg->model_operation.ctx);
}
break;
}
case BFL_BLE_MESH_CLIENT_MODEL_RECV_PUBLISH_MSG_EVT: {
if (arg->client_recv_publish_msg.msg) {
bt_mesh_free(arg->client_recv_publish_msg.msg);
}
if (arg->client_recv_publish_msg.ctx) {
bt_mesh_free(arg->client_recv_publish_msg.ctx);
}
break;
}
case BFL_BLE_MESH_MODEL_SEND_COMP_EVT: {
if (arg->model_send_comp.ctx) {
bt_mesh_free(arg->model_send_comp.ctx);
}
break;
}
case BFL_BLE_MESH_CLIENT_MODEL_SEND_TIMEOUT_EVT: {
if (arg->client_send_timeout.ctx) {
bt_mesh_free(arg->client_send_timeout.ctx);
}
break;
}
default:
break;
}
}
static bt_status_t btc_ble_mesh_model_callback(bfl_ble_mesh_model_cb_param_t *param, uint8_t act)
{
btc_msg_t msg = {0};
bt_status_t ret = BT_STATUS_SUCCESS;
BT_DBG("%s", __func__);
/* If corresponding callback is not registered, event will not be posted. */
if (!btc_profile_cb_get(BTC_PID_MODEL)) {
return BT_STATUS_SUCCESS;
}
msg.sig = BTC_SIG_API_CB;
msg.pid = BTC_PID_MODEL;
msg.act = act;
ret = btc_transfer_context(&msg, param,
sizeof(bfl_ble_mesh_model_cb_param_t), btc_ble_mesh_model_copy_req_data);
if (ret != BT_STATUS_SUCCESS) {
BT_ERR("%s, btc_transfer_context failed", __func__);
}
return ret;
}
static void btc_ble_mesh_server_model_op_cb(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
bfl_ble_mesh_model_cb_param_t mesh_param = {0};
mesh_param.model_operation.opcode = ctx->recv_op;
mesh_param.model_operation.model = (bfl_ble_mesh_model_t *)model;
mesh_param.model_operation.ctx = (bfl_ble_mesh_msg_ctx_t *)ctx;
mesh_param.model_operation.length = buf->len;
mesh_param.model_operation.msg = buf->data;
btc_ble_mesh_model_callback(&mesh_param, BFL_BLE_MESH_MODEL_OPERATION_EVT);
return;
}
static void btc_ble_mesh_client_model_op_cb(struct bt_mesh_model *model,
struct bt_mesh_msg_ctx *ctx,
struct net_buf_simple *buf)
{
bfl_ble_mesh_model_cb_param_t mesh_param = {0};
bt_mesh_client_node_t *node = NULL;
if (!model || !model->user_data || !ctx || !buf) {
BT_ERR("%s, Invalid parameter", __func__);
return;
}
bt_mesh_client_model_lock();
node = bt_mesh_is_client_recv_publish_msg(model, ctx, buf, false);
if (node == NULL) {
mesh_param.client_recv_publish_msg.opcode = ctx->recv_op;
mesh_param.client_recv_publish_msg.model = (bfl_ble_mesh_model_t *)model;
mesh_param.client_recv_publish_msg.ctx = (bfl_ble_mesh_msg_ctx_t *)ctx;
mesh_param.client_recv_publish_msg.length = buf->len;
mesh_param.client_recv_publish_msg.msg = buf->data;
btc_ble_mesh_model_callback(&mesh_param, BFL_BLE_MESH_CLIENT_MODEL_RECV_PUBLISH_MSG_EVT);
} else {
mesh_param.model_operation.opcode = ctx->recv_op;
mesh_param.model_operation.model = (bfl_ble_mesh_model_t *)model;
mesh_param.model_operation.ctx = (bfl_ble_mesh_msg_ctx_t *)ctx;
mesh_param.model_operation.length = buf->len;
mesh_param.model_operation.msg = buf->data;
if (!k_delayed_work_free(&node->timer)) {
bt_mesh_client_free_node(node);
btc_ble_mesh_model_callback(&mesh_param, BFL_BLE_MESH_MODEL_OPERATION_EVT);
}
}
bt_mesh_client_model_unlock();
return;
}
static void btc_ble_mesh_client_model_timeout_cb(struct k_work *work)
{
bfl_ble_mesh_model_cb_param_t mesh_param = {0};
struct k_delayed_work *timer = NULL;
bt_mesh_client_node_t *node = NULL;
struct bt_mesh_msg_ctx ctx = {0};
bt_mesh_client_model_lock();
timer = CONTAINER_OF(work, struct k_delayed_work, work);
if (timer && !k_delayed_work_free(timer)) {
node = CONTAINER_OF(work, bt_mesh_client_node_t, timer.work);
if (node) {
memcpy(&ctx, &node->ctx, sizeof(ctx));
mesh_param.client_send_timeout.opcode = node->opcode;
mesh_param.client_send_timeout.model = (bfl_ble_mesh_model_t *)ctx.model;
mesh_param.client_send_timeout.ctx = (bfl_ble_mesh_msg_ctx_t *)&ctx;
bt_mesh_client_free_node(node);
btc_ble_mesh_model_callback(&mesh_param, BFL_BLE_MESH_CLIENT_MODEL_SEND_TIMEOUT_EVT);
}
}
bt_mesh_client_model_unlock();
return;
}
static void btc_ble_mesh_model_send_comp_cb(bfl_ble_mesh_model_t *model, bfl_ble_mesh_msg_ctx_t *ctx, u32_t opcode, int err)
{
bfl_ble_mesh_model_cb_param_t mesh_param = {0};
mesh_param.model_send_comp.err_code = err;
mesh_param.model_send_comp.opcode = opcode;
mesh_param.model_send_comp.model = model;
mesh_param.model_send_comp.ctx = ctx;
btc_ble_mesh_model_callback(&mesh_param, BFL_BLE_MESH_MODEL_SEND_COMP_EVT);
return;
}
static void btc_ble_mesh_model_publish_comp_cb(bfl_ble_mesh_model_t *model, int err)
{
bfl_ble_mesh_model_cb_param_t mesh_param = {0};
mesh_param.model_publish_comp.err_code = err;
mesh_param.model_publish_comp.model = model;
btc_ble_mesh_model_callback(&mesh_param, BFL_BLE_MESH_MODEL_PUBLISH_COMP_EVT);
return;
}
static int btc_ble_mesh_model_publish_update(struct bt_mesh_model *mod)
{
bfl_ble_mesh_model_cb_param_t mesh_param = {0};
bt_status_t ret = BT_STATUS_SUCCESS;
BT_DBG("%s", __func__);
mesh_param.model_publish_update.model = (bfl_ble_mesh_model_t *)mod;
ret = btc_ble_mesh_model_callback(&mesh_param, BFL_BLE_MESH_MODEL_PUBLISH_UPDATE_EVT);
return (ret == BT_STATUS_SUCCESS) ? 0 : -1;
}
static void btc_ble_mesh_server_model_update_state_comp_cb(bfl_ble_mesh_model_t *model,
bfl_ble_mesh_server_state_type_t type, int err)
{
bfl_ble_mesh_model_cb_param_t mesh_param = {0};
mesh_param.server_model_update_state.err_code = err;
mesh_param.server_model_update_state.model = model;
mesh_param.server_model_update_state.type = type;
btc_ble_mesh_model_callback(&mesh_param, BFL_BLE_MESH_SERVER_MODEL_UPDATE_STATE_COMP_EVT);
return;
}
static bt_status_t btc_ble_mesh_prov_callback(bfl_ble_mesh_prov_cb_param_t *param, uint8_t act)
{
btc_msg_t msg = {0};
bt_status_t ret = BT_STATUS_SUCCESS;
BT_DBG("%s", __func__);
/* If corresponding callback is not registered, event will not be posted. */
if (!btc_profile_cb_get(BTC_PID_PROV)) {
return BT_STATUS_SUCCESS;
}
msg.sig = BTC_SIG_API_CB;
msg.pid = BTC_PID_PROV;
msg.act = act;
ret = btc_transfer_context(&msg, param, sizeof(bfl_ble_mesh_prov_cb_param_t), NULL);
if (ret != BT_STATUS_SUCCESS) {
BT_ERR("%s, btc_transfer_context failed", __func__);
}
return ret;
}
#if CONFIG_BLE_MESH_NODE
static void btc_ble_mesh_oob_pub_key_cb(void)
{
BT_DBG("%s", __func__);
btc_ble_mesh_prov_callback(NULL, BFL_BLE_MESH_NODE_PROV_OOB_PUB_KEY_EVT);
return;
}
static int btc_ble_mesh_output_number_cb(bt_mesh_output_action_t act, u32_t num)
{
bfl_ble_mesh_prov_cb_param_t mesh_param = {0};
bt_status_t ret = BT_STATUS_SUCCESS;
BT_DBG("%s", __func__);
mesh_param.node_prov_output_num.action = (bfl_ble_mesh_output_action_t)act;
mesh_param.node_prov_output_num.number = num;
ret = btc_ble_mesh_prov_callback(&mesh_param, BFL_BLE_MESH_NODE_PROV_OUTPUT_NUMBER_EVT);
return (ret == BT_STATUS_SUCCESS) ? 0 : -1;
}
static int btc_ble_mesh_output_string_cb(const char *str)
{
bfl_ble_mesh_prov_cb_param_t mesh_param = {0};
bt_status_t ret = BT_STATUS_SUCCESS;
BT_DBG("%s", __func__);
strncpy(mesh_param.node_prov_output_str.string, str,
MIN(strlen(str), sizeof(mesh_param.node_prov_output_str.string)));
ret = btc_ble_mesh_prov_callback(&mesh_param, BFL_BLE_MESH_NODE_PROV_OUTPUT_STRING_EVT);
return (ret == BT_STATUS_SUCCESS) ? 0 : -1;
}
static int btc_ble_mesh_input_cb(bt_mesh_input_action_t act, u8_t size)
{
bfl_ble_mesh_prov_cb_param_t mesh_param = {0};
bt_status_t ret = BT_STATUS_SUCCESS;
BT_DBG("%s", __func__);
mesh_param.node_prov_input.action = (bfl_ble_mesh_input_action_t)act;
mesh_param.node_prov_input.size = size;
ret = btc_ble_mesh_prov_callback(&mesh_param, BFL_BLE_MESH_NODE_PROV_INPUT_EVT);
return (ret == BT_STATUS_SUCCESS) ? 0 : -1;
}
static void btc_ble_mesh_link_open_cb(bt_mesh_prov_bearer_t bearer)
{
bfl_ble_mesh_prov_cb_param_t mesh_param = {0};
BT_DBG("%s", __func__);
mesh_param.node_prov_link_open.bearer = (bfl_ble_mesh_prov_bearer_t)bearer;
btc_ble_mesh_prov_callback(&mesh_param, BFL_BLE_MESH_NODE_PROV_LINK_OPEN_EVT);
return;
}
static void btc_ble_mesh_link_close_cb(bt_mesh_prov_bearer_t bearer)
{
bfl_ble_mesh_prov_cb_param_t mesh_param = {0};
BT_DBG("%s", __func__);
mesh_param.node_prov_link_close.bearer = (bfl_ble_mesh_prov_bearer_t)bearer;
btc_ble_mesh_prov_callback(&mesh_param, BFL_BLE_MESH_NODE_PROV_LINK_CLOSE_EVT);
return;
}
static void btc_ble_mesh_complete_cb(u16_t net_idx, const u8_t net_key[16], u16_t addr, u8_t flags, u32_t iv_index)
{
bfl_ble_mesh_prov_cb_param_t mesh_param = {0};
BT_DBG("%s", __func__);
mesh_param.node_prov_complete.net_idx = net_idx;
memcpy(mesh_param.node_prov_complete.net_key, net_key, 16);
mesh_param.node_prov_complete.addr = addr;
mesh_param.node_prov_complete.flags = flags;
mesh_param.node_prov_complete.iv_index = iv_index;
btc_ble_mesh_prov_callback(&mesh_param, BFL_BLE_MESH_NODE_PROV_COMPLETE_EVT);
return;
}
static void btc_ble_mesh_reset_cb(void)
{
BT_DBG("%s", __func__);
btc_ble_mesh_prov_callback(NULL, BFL_BLE_MESH_NODE_PROV_RESET_EVT);
return;
}
#endif /* CONFIG_BLE_MESH_NODE */
static void btc_ble_mesh_prov_register_complete_cb(int err_code)
{
bfl_ble_mesh_prov_cb_param_t mesh_param = {0};
BT_DBG("%s", __func__);
mesh_param.prov_register_comp.err_code = err_code;
btc_ble_mesh_prov_callback(&mesh_param, BFL_BLE_MESH_PROV_REGISTER_COMP_EVT);
return;
}
static void btc_ble_mesh_prov_set_complete_cb(bfl_ble_mesh_prov_cb_param_t *param, uint8_t act)
{
BT_DBG("%s", __func__);
btc_ble_mesh_prov_callback(param, act);
return;
}
#if CONFIG_BLE_MESH_PROVISIONER
static void btc_ble_mesh_provisioner_recv_unprov_adv_pkt_cb(
const u8_t addr[6], const u8_t addr_type,
const u8_t adv_type, const u8_t dev_uuid[16],
u16_t oob_info, bt_mesh_prov_bearer_t bearer, s8_t rssi)
{
bfl_ble_mesh_prov_cb_param_t mesh_param = {0};
BT_DBG("%s", __func__);
if (addr == NULL || dev_uuid == NULL ||
(bearer != BLE_MESH_PROV_ADV && bearer != BLE_MESH_PROV_GATT)) {
BT_ERR("%s, Invalid parameter", __func__);
return;
}
memcpy(mesh_param.provisioner_recv_unprov_adv_pkt.dev_uuid, dev_uuid, 16);
memcpy(mesh_param.provisioner_recv_unprov_adv_pkt.addr, addr, BLE_MESH_ADDR_LEN);
mesh_param.provisioner_recv_unprov_adv_pkt.addr_type = addr_type;
mesh_param.provisioner_recv_unprov_adv_pkt.oob_info = oob_info;
mesh_param.provisioner_recv_unprov_adv_pkt.adv_type = adv_type;
mesh_param.provisioner_recv_unprov_adv_pkt.bearer = bearer;
mesh_param.provisioner_recv_unprov_adv_pkt.rssi = rssi;
btc_ble_mesh_prov_callback(&mesh_param, BFL_BLE_MESH_PROVISIONER_RECV_UNPROV_ADV_PKT_EVT);
return;
}
static int btc_ble_mesh_provisioner_prov_read_oob_pub_key_cb(u8_t link_idx)
{
bfl_ble_mesh_prov_cb_param_t mesh_param = {0};
bt_status_t ret = BT_STATUS_SUCCESS;
BT_DBG("%s", __func__);
mesh_param.provisioner_prov_read_oob_pub_key.link_idx = link_idx;
ret = btc_ble_mesh_prov_callback(&mesh_param, BFL_BLE_MESH_PROVISIONER_PROV_READ_OOB_PUB_KEY_EVT);
return (ret == BT_STATUS_SUCCESS) ? 0 : -1;
}
static int btc_ble_mesh_provisioner_prov_input_cb(u8_t method,
bt_mesh_output_action_t act, u8_t size, u8_t link_idx)
{
bfl_ble_mesh_prov_cb_param_t mesh_param = {0};
bt_status_t ret = BT_STATUS_SUCCESS;
BT_DBG("%s", __func__);
mesh_param.provisioner_prov_input.method = (bfl_ble_mesh_oob_method_t)method;
mesh_param.provisioner_prov_input.action = (bfl_ble_mesh_output_action_t)act;
mesh_param.provisioner_prov_input.size = size;
mesh_param.provisioner_prov_input.link_idx = link_idx;
ret = btc_ble_mesh_prov_callback(&mesh_param, BFL_BLE_MESH_PROVISIONER_PROV_INPUT_EVT);
return (ret == BT_STATUS_SUCCESS) ? 0 : -1;
}
static int btc_ble_mesh_provisioner_prov_output_cb(u8_t method,
bt_mesh_input_action_t act, void *data, u8_t size, u8_t link_idx)
{
bfl_ble_mesh_prov_cb_param_t mesh_param = {0};
bt_status_t ret = BT_STATUS_SUCCESS;
BT_DBG("%s", __func__);
mesh_param.provisioner_prov_output.method = (bfl_ble_mesh_oob_method_t)method;
mesh_param.provisioner_prov_output.action = (bfl_ble_mesh_input_action_t)act;
mesh_param.provisioner_prov_output.size = size;
mesh_param.provisioner_prov_output.link_idx = link_idx;
if (act == BLE_MESH_ENTER_STRING) {
strncpy(mesh_param.provisioner_prov_output.string, (char *)data, size);
} else {
mesh_param.provisioner_prov_output.number = sys_get_le32((u8_t *)data);
}
ret = btc_ble_mesh_prov_callback(&mesh_param, BFL_BLE_MESH_PROVISIONER_PROV_OUTPUT_EVT);
return (ret == BT_STATUS_SUCCESS) ? 0 : -1;
}
static void btc_ble_mesh_provisioner_link_open_cb(bt_mesh_prov_bearer_t bearer)
{
bfl_ble_mesh_prov_cb_param_t mesh_param = {0};
BT_DBG("%s", __func__);
mesh_param.provisioner_prov_link_open.bearer = (bfl_ble_mesh_prov_bearer_t)bearer;
btc_ble_mesh_prov_callback(&mesh_param, BFL_BLE_MESH_PROVISIONER_PROV_LINK_OPEN_EVT);
return;
}
static void btc_ble_mesh_provisioner_link_close_cb(bt_mesh_prov_bearer_t bearer, u8_t reason)
{
bfl_ble_mesh_prov_cb_param_t mesh_param = {0};
BT_DBG("%s", __func__);
mesh_param.provisioner_prov_link_close.bearer = (bfl_ble_mesh_prov_bearer_t)bearer;
mesh_param.provisioner_prov_link_close.reason = reason;
btc_ble_mesh_prov_callback(&mesh_param, BFL_BLE_MESH_PROVISIONER_PROV_LINK_CLOSE_EVT);
return;
}
static void btc_ble_mesh_provisioner_prov_complete_cb(
u16_t node_idx, const u8_t device_uuid[16],
u16_t unicast_addr, u8_t element_num,
u16_t netkey_idx)
{
bfl_ble_mesh_prov_cb_param_t mesh_param = {0};
BT_DBG("%s", __func__);
mesh_param.provisioner_prov_complete.node_idx = node_idx;
mesh_param.provisioner_prov_complete.unicast_addr = unicast_addr;
mesh_param.provisioner_prov_complete.element_num = element_num;
mesh_param.provisioner_prov_complete.netkey_idx = netkey_idx;
memcpy(mesh_param.provisioner_prov_complete.device_uuid, device_uuid, sizeof(bfl_ble_mesh_octet16_t));
btc_ble_mesh_prov_callback(&mesh_param, BFL_BLE_MESH_PROVISIONER_PROV_COMPLETE_EVT);
return;
}
bfl_ble_mesh_node_t *btc_ble_mesh_provisioner_get_node_with_uuid(const uint8_t uuid[16])
{
return (bfl_ble_mesh_node_t *)bt_mesh_provisioner_get_node_with_uuid(uuid);
}
bfl_ble_mesh_node_t *btc_ble_mesh_provisioner_get_node_with_addr(uint16_t unicast_addr)
{
return (bfl_ble_mesh_node_t *)bt_mesh_provisioner_get_node_with_addr(unicast_addr);
}
#endif /* CONFIG_BLE_MESH_PROVISIONER */
#if 0
static void btc_ble_mesh_heartbeat_msg_recv_cb(u8_t hops, u16_t feature)
{
bfl_ble_mesh_prov_cb_param_t mesh_param = {0};
BT_DBG("%s", __func__);
mesh_param.heartbeat_msg_recv.hops = hops;
mesh_param.heartbeat_msg_recv.feature = feature;
btc_ble_mesh_prov_callback(&mesh_param, BFL_BLE_MESH_HEARTBEAT_MESSAGE_RECV_EVT);
return;
}
#endif
#if CONFIG_BLE_MESH_LOW_POWER
static void btc_ble_mesh_lpn_cb(u16_t friend_addr, bool established)
{
bfl_ble_mesh_prov_cb_param_t mesh_param = {0};
u8_t act = 0U;
BT_DBG("%s", __func__);
if (established) {
mesh_param.lpn_friendship_establish.friend_addr = friend_addr;
act = BFL_BLE_MESH_LPN_FRIENDSHIP_ESTABLISH_EVT;
} else {
mesh_param.lpn_friendship_terminate.friend_addr = friend_addr;
act = BFL_BLE_MESH_LPN_FRIENDSHIP_TERMINATE_EVT;
}
btc_ble_mesh_prov_callback(&mesh_param, act);
return;
}
#endif /* CONFIG_BLE_MESH_LOW_POWER */
#if CONFIG_BLE_MESH_FRIEND
void btc_ble_mesh_friend_cb(bool establish, u16_t lpn_addr, u8_t reason)
{
bfl_ble_mesh_prov_cb_param_t mesh_param = {0};
u8_t act = 0U;
BT_DBG("%s", __func__);
if (!BLE_MESH_ADDR_IS_UNICAST(lpn_addr)) {
BT_ERR("%s, Not a unicast address", __func__);
return;
}
if (establish) {
mesh_param.frnd_friendship_establish.lpn_addr = lpn_addr;
act = BFL_BLE_MESH_FRIEND_FRIENDSHIP_ESTABLISH_EVT;
} else {
mesh_param.frnd_friendship_terminate.lpn_addr = lpn_addr;
mesh_param.frnd_friendship_terminate.reason = reason;
act = BFL_BLE_MESH_FRIEND_FRIENDSHIP_TERMINATE_EVT;
}
btc_ble_mesh_prov_callback(&mesh_param, act);
return;
}
#endif /* CONFIG_BLE_MESH_FRIEND */
#if CONFIG_BLE_MESH_GATT_PROXY_CLIENT
static void btc_ble_mesh_proxy_client_adv_recv_cb(const bt_mesh_addr_t *addr,
u8_t type, bt_mesh_proxy_adv_ctx_t *ctx, s8_t rssi)
{
bfl_ble_mesh_prov_cb_param_t mesh_param = {0};
if (!addr || !ctx || type != BLE_MESH_PROXY_ADV_NET_ID) {
BT_ERR("%s, Invalid parameter", __func__);
return;
}
BT_DBG("%s", __func__);
mesh_param.proxy_client_recv_adv_pkt.addr_type = addr->type;
memcpy(mesh_param.proxy_client_recv_adv_pkt.addr, addr->val, BD_ADDR_LEN);
mesh_param.proxy_client_recv_adv_pkt.net_idx = ctx->net_id.net_idx;
memcpy(mesh_param.proxy_client_recv_adv_pkt.net_id, ctx->net_id.net_id, 8);
mesh_param.proxy_client_recv_adv_pkt.rssi = rssi;
btc_ble_mesh_prov_callback(&mesh_param, BFL_BLE_MESH_PROXY_CLIENT_RECV_ADV_PKT_EVT);
return;
}
static void btc_ble_mesh_proxy_client_connect_cb(const bt_mesh_addr_t *addr,
u8_t conn_handle, u16_t net_idx)
{
bfl_ble_mesh_prov_cb_param_t mesh_param = {0};
if (!addr || conn_handle >= BLE_MESH_MAX_CONN) {
BT_ERR("%s, Invalid parameter", __func__);
return;
}
BT_DBG("%s", __func__);
mesh_param.proxy_client_connected.addr_type = addr->type;
memcpy(mesh_param.proxy_client_connected.addr, addr->val, BD_ADDR_LEN);
mesh_param.proxy_client_connected.conn_handle = conn_handle;
mesh_param.proxy_client_connected.net_idx = net_idx;
btc_ble_mesh_prov_callback(&mesh_param, BFL_BLE_MESH_PROXY_CLIENT_CONNECTED_EVT);
return;
}
static void btc_ble_mesh_proxy_client_disconnect_cb(const bt_mesh_addr_t *addr,
u8_t conn_handle, u16_t net_idx, u8_t reason)
{
bfl_ble_mesh_prov_cb_param_t mesh_param = {0};
if (!addr || conn_handle >= BLE_MESH_MAX_CONN) {
BT_ERR("%s, Invalid parameter", __func__);
return;
}
BT_DBG("%s", __func__);
mesh_param.proxy_client_disconnected.addr_type = addr->type;
memcpy(mesh_param.proxy_client_disconnected.addr, addr->val, BD_ADDR_LEN);
mesh_param.proxy_client_disconnected.conn_handle = conn_handle;
mesh_param.proxy_client_disconnected.net_idx = net_idx;
mesh_param.proxy_client_disconnected.reason = reason;
btc_ble_mesh_prov_callback(&mesh_param, BFL_BLE_MESH_PROXY_CLIENT_DISCONNECTED_EVT);
return;
}
static void btc_ble_mesh_proxy_client_filter_status_recv_cb(u8_t conn_handle,
u16_t src, u16_t net_idx, u8_t filter_type, u16_t list_size)
{
bfl_ble_mesh_prov_cb_param_t mesh_param = {0};
if (conn_handle >= BLE_MESH_MAX_CONN) {
BT_ERR("%s, Invalid parameter", __func__);
return;
}
BT_DBG("%s", __func__);
mesh_param.proxy_client_recv_filter_status.conn_handle = conn_handle;
mesh_param.proxy_client_recv_filter_status.server_addr = src;
mesh_param.proxy_client_recv_filter_status.net_idx = net_idx;
mesh_param.proxy_client_recv_filter_status.filter_type = filter_type;
mesh_param.proxy_client_recv_filter_status.list_size = list_size;
btc_ble_mesh_prov_callback(&mesh_param, BFL_BLE_MESH_PROXY_CLIENT_RECV_FILTER_STATUS_EVT);
return;
}
#endif /* CONFIG_BLE_MESH_GATT_PROXY_CLIENT */
int btc_ble_mesh_client_model_init(bfl_ble_mesh_model_t *model)
{
__ASSERT(model && model->op, "%s, Invalid parameter", __func__);
bfl_ble_mesh_model_op_t *op = (bfl_ble_mesh_model_op_t *)model->op;
while (op != NULL && op->opcode != 0) {
op->func = btc_ble_mesh_client_model_op_cb;
op++;
}
return bt_mesh_client_init((struct bt_mesh_model *)model);
}
int btc_ble_mesh_client_model_deinit(bfl_ble_mesh_model_t *model)
{
return bt_mesh_client_deinit((struct bt_mesh_model *)model);
}
int32_t btc_ble_mesh_model_pub_period_get(bfl_ble_mesh_model_t *mod)
{
return bt_mesh_model_pub_period_get((struct bt_mesh_model *)mod);
}
uint16_t btc_ble_mesh_get_primary_addr(void)
{
return bt_mesh_primary_addr();
}
uint16_t *btc_ble_mesh_model_find_group(bfl_ble_mesh_model_t *mod, uint16_t addr)
{
return bt_mesh_model_find_group((struct bt_mesh_model **)&mod, addr);
}
bfl_ble_mesh_elem_t *btc_ble_mesh_elem_find(u16_t addr)
{
return (bfl_ble_mesh_elem_t *)bt_mesh_elem_find(addr);
}
uint8_t btc_ble_mesh_elem_count(void)
{
return bt_mesh_elem_count();
}
bfl_ble_mesh_model_t *btc_ble_mesh_model_find_vnd(const bfl_ble_mesh_elem_t *elem,
uint16_t company, uint16_t id)
{
return (bfl_ble_mesh_model_t *)bt_mesh_model_find_vnd((struct bt_mesh_elem *)elem, company, id);
}
bfl_ble_mesh_model_t *btc_ble_mesh_model_find(const bfl_ble_mesh_elem_t *elem, uint16_t id)
{
return (bfl_ble_mesh_model_t *)bt_mesh_model_find((struct bt_mesh_elem *)elem, id);
}
const bfl_ble_mesh_comp_t *btc_ble_mesh_comp_get(void)
{
return (const bfl_ble_mesh_comp_t *)bt_mesh_comp_get();
}
u16_t btc_ble_mesh_provisioner_get_prov_node_count(void)
{
#if 0
return bt_mesh_provisioner_get_node_count();
#else
return 0;
#endif
}
/* Configuration Models */
extern const struct bt_mesh_model_op bt_mesh_cfg_srv_op[];
extern const struct bt_mesh_model_op bt_mesh_cfg_cli_op[];
/* Health Models */
extern const struct bt_mesh_model_op bt_mesh_health_srv_op[];
extern const struct bt_mesh_model_op bt_mesh_health_cli_op[];
/* Generic Client Models */
extern const struct bt_mesh_model_op gen_onoff_cli_op[];
extern const struct bt_mesh_model_op gen_level_cli_op[];
extern const struct bt_mesh_model_op gen_def_trans_time_cli_op[];
extern const struct bt_mesh_model_op gen_power_onoff_cli_op[];
extern const struct bt_mesh_model_op gen_power_level_cli_op[];
extern const struct bt_mesh_model_op gen_battery_cli_op[];
extern const struct bt_mesh_model_op gen_location_cli_op[];
extern const struct bt_mesh_model_op gen_property_cli_op[];
/* Lighting Client Models */
extern const struct bt_mesh_model_op light_lightness_cli_op[];
extern const struct bt_mesh_model_op light_ctl_cli_op[];
extern const struct bt_mesh_model_op light_hsl_cli_op[];
extern const struct bt_mesh_model_op light_xyl_cli_op[];
extern const struct bt_mesh_model_op light_lc_cli_op[];
/* Sensor Client Models */
extern const struct bt_mesh_model_op sensor_cli_op[];
/* Time and Scenes Client Models */
extern const struct bt_mesh_model_op time_cli_op[];
extern const struct bt_mesh_model_op scene_cli_op[];
extern const struct bt_mesh_model_op scheduler_cli_op[];
/* Generic Server Models */
extern const struct bt_mesh_model_op gen_onoff_srv_op[];
extern const struct bt_mesh_model_op gen_level_srv_op[];
extern const struct bt_mesh_model_op gen_def_trans_time_srv_op[];
extern const struct bt_mesh_model_op gen_power_onoff_srv_op[];
extern const struct bt_mesh_model_op gen_power_onoff_setup_srv_op[];
extern const struct bt_mesh_model_op gen_power_level_srv_op[];
extern const struct bt_mesh_model_op gen_power_level_setup_srv_op[];
extern const struct bt_mesh_model_op gen_battery_srv_op[];
extern const struct bt_mesh_model_op gen_location_srv_op[];
extern const struct bt_mesh_model_op gen_location_setup_srv_op[];
extern const struct bt_mesh_model_op gen_user_prop_srv_op[];
extern const struct bt_mesh_model_op gen_admin_prop_srv_op[];
extern const struct bt_mesh_model_op gen_manu_prop_srv_op[];
extern const struct bt_mesh_model_op gen_client_prop_srv_op[];
/* Lighting Server Models */
extern const struct bt_mesh_model_op light_lightness_srv_op[];
extern const struct bt_mesh_model_op light_lightness_setup_srv_op[];
extern const struct bt_mesh_model_op light_ctl_srv_op[];
extern const struct bt_mesh_model_op light_ctl_setup_srv_op[];
extern const struct bt_mesh_model_op light_ctl_temp_srv_op[];
extern const struct bt_mesh_model_op light_hsl_srv_op[];
extern const struct bt_mesh_model_op light_hsl_hue_srv_op[];
extern const struct bt_mesh_model_op light_hsl_sat_srv_op[];
extern const struct bt_mesh_model_op light_hsl_setup_srv_op[];
extern const struct bt_mesh_model_op light_xyl_srv_op[];
extern const struct bt_mesh_model_op light_xyl_setup_srv_op[];
extern const struct bt_mesh_model_op light_lc_srv_op[];
extern const struct bt_mesh_model_op light_lc_setup_srv_op[];
/* Time and Scenes Server Models */
extern const struct bt_mesh_model_op time_srv_op[];
extern const struct bt_mesh_model_op time_setup_srv_op[];
extern const struct bt_mesh_model_op scene_srv_op[];
extern const struct bt_mesh_model_op scene_setup_srv_op[];
extern const struct bt_mesh_model_op scheduler_srv_op[];
extern const struct bt_mesh_model_op scheduler_setup_srv_op[];
/* Sensor Server Models */
extern const struct bt_mesh_model_op sensor_srv_op[];
extern const struct bt_mesh_model_op sensor_setup_srv_op[];
static void btc_ble_mesh_model_op_add(bfl_ble_mesh_model_t *model)
{
bfl_ble_mesh_model_op_t *op = NULL;
if (!model) {
BT_ERR("%s, Invalid parameter", __func__);
return;
}
/* For SIG client and server models, model->op will be NULL and initialized here.
* For vendor models whose opcode is 3 bytes, model->op will be initialized here.
*/
if ((model->op != NULL) && (model->op->opcode >= 0x10000)) {
goto add_model_op;
}
switch (model->id) {
case BT_MESH_MODEL_ID_CFG_SRV: {
#if 0
model->op = (bfl_ble_mesh_model_op_t *)bt_mesh_cfg_srv_op;
struct bt_mesh_cfg_srv *srv = (struct bt_mesh_cfg_srv *)model->user_data;
if (srv) {
srv->hb_sub.func = btc_ble_mesh_heartbeat_msg_recv_cb;
}
#endif
break;
}
case BT_MESH_MODEL_ID_CFG_CLI: {
#if 0
model->op = (bfl_ble_mesh_model_op_t *)bt_mesh_cfg_cli_op;
bt_mesh_config_client_t *cli = (bt_mesh_config_client_t *)model->user_data;
if (cli != NULL) {
cli->publish_status = btc_ble_mesh_config_client_publish_callback;
}
#endif
break;
}
case BT_MESH_MODEL_ID_HEALTH_SRV: {
#if 0
model->op = (bfl_ble_mesh_model_op_t *)bt_mesh_health_srv_op;
struct bt_mesh_health_srv *srv = (struct bt_mesh_health_srv *)model->user_data;
if (srv) {
srv->cb.fault_clear = btc_ble_mesh_health_server_fault_clear;
srv->cb.fault_test = btc_ble_mesh_health_server_fault_test;
srv->cb.attn_on = btc_ble_mesh_health_server_attention_on;
srv->cb.attn_off = btc_ble_mesh_health_server_attention_off;
}
#endif
break;
}
case BT_MESH_MODEL_ID_HEALTH_CLI: {
#if 0
model->op = (bfl_ble_mesh_model_op_t *)bt_mesh_health_cli_op;
bt_mesh_health_client_t *cli = (bt_mesh_health_client_t *)model->user_data;
if (cli != NULL) {
cli->publish_status = btc_ble_mesh_health_publish_callback;
}
#endif
break;
}
case BT_MESH_MODEL_ID_GEN_ONOFF_CLI: {
model->op = gen_onoff_cli_op;
bt_mesh_gen_onoff_client_t *cli = (bt_mesh_gen_onoff_client_t *)model->user_data;
if (cli != NULL) {
cli->publish_status = btc_ble_mesh_generic_client_publish_callback;
}
break;
}
case BT_MESH_MODEL_ID_GEN_LEVEL_CLI: {
model->op = gen_level_cli_op;
bt_mesh_gen_level_client_t *cli = (bt_mesh_gen_level_client_t *)model->user_data;
if (cli != NULL) {
cli->publish_status = btc_ble_mesh_generic_client_publish_callback;
}
break;
}
case BT_MESH_MODEL_ID_GEN_DEF_TRANS_TIME_CLI: {
model->op = gen_def_trans_time_cli_op;
bt_mesh_gen_def_trans_time_client_t *cli = (bt_mesh_gen_def_trans_time_client_t *)model->user_data;
if (cli != NULL) {
cli->publish_status = btc_ble_mesh_generic_client_publish_callback;
}
break;
}
case BT_MESH_MODEL_ID_GEN_POWER_ONOFF_CLI: {
model->op = gen_power_onoff_cli_op;
bt_mesh_gen_power_onoff_client_t *cli = (bt_mesh_gen_power_onoff_client_t *)model->user_data;
if (cli != NULL) {
cli->publish_status = btc_ble_mesh_generic_client_publish_callback;
}
break;
}
case BT_MESH_MODEL_ID_GEN_POWER_LEVEL_CLI: {
model->op = gen_power_level_cli_op;
bt_mesh_gen_power_level_client_t *cli = (bt_mesh_gen_power_level_client_t *)model->user_data;
if (cli != NULL) {
cli->publish_status = btc_ble_mesh_generic_client_publish_callback;
}
break;
}
case BT_MESH_MODEL_ID_GEN_BATTERY_CLI: {
model->op = gen_battery_cli_op;
bt_mesh_gen_battery_client_t *cli = (bt_mesh_gen_battery_client_t *)model->user_data;
if (cli != NULL) {
cli->publish_status = btc_ble_mesh_generic_client_publish_callback;
}
break;
}
case BT_MESH_MODEL_ID_GEN_LOCATION_CLI: {
model->op = gen_location_cli_op;
bt_mesh_gen_location_client_t *cli = (bt_mesh_gen_location_client_t *)model->user_data;
if (cli != NULL) {
cli->publish_status = btc_ble_mesh_generic_client_publish_callback;
}
break;
}
case BT_MESH_MODEL_ID_GEN_PROP_CLI: {
model->op = gen_property_cli_op;
bt_mesh_gen_property_client_t *cli = (bt_mesh_gen_property_client_t *)model->user_data;
if (cli != NULL) {
cli->publish_status = btc_ble_mesh_generic_client_publish_callback;
}
break;
}
case BT_MESH_MODEL_ID_LIGHT_LIGHTNESS_CLI: {
model->op = light_lightness_cli_op;
bt_mesh_light_lightness_client_t *cli = (bt_mesh_light_lightness_client_t *)model->user_data;
if (cli != NULL) {
cli->publish_status = btc_ble_mesh_lighting_client_publish_callback;
}
break;
}
case BT_MESH_MODEL_ID_LIGHT_CTL_CLI: {
model->op = light_ctl_cli_op;
bt_mesh_light_ctl_client_t *cli = (bt_mesh_light_ctl_client_t *)model->user_data;
if (cli != NULL) {
cli->publish_status = btc_ble_mesh_lighting_client_publish_callback;
}
break;
}
case BT_MESH_MODEL_ID_LIGHT_HSL_CLI: {
model->op = light_hsl_cli_op;
bt_mesh_light_hsl_client_t *cli = (bt_mesh_light_hsl_client_t *)model->user_data;
if (cli != NULL) {
cli->publish_status = btc_ble_mesh_lighting_client_publish_callback;
}
break;
}
case BT_MESH_MODEL_ID_LIGHT_XYL_CLI: {
model->op = light_xyl_cli_op;
bt_mesh_light_xyl_client_t *cli = (bt_mesh_light_xyl_client_t *)model->user_data;
if (cli != NULL) {
cli->publish_status = btc_ble_mesh_lighting_client_publish_callback;
}
break;
}
case BT_MESH_MODEL_ID_LIGHT_LC_CLI: {
model->op = light_lc_cli_op;
bt_mesh_light_lc_client_t *cli = (bt_mesh_light_lc_client_t *)model->user_data;
if (cli != NULL) {
cli->publish_status = btc_ble_mesh_lighting_client_publish_callback;
}
break;
}
case BT_MESH_MODEL_ID_SENSOR_CLI: {
#if 0
model->op = ((bfl_ble_mesh_model_op_t *)sensor_cli_op);
bt_mesh_sensor_client_t *cli = (bt_mesh_sensor_client_t *)model->user_data;
if (cli != NULL) {
cli->publish_status = btc_ble_mesh_sensor_client_publish_callback;
}
#endif
break;
}
case BT_MESH_MODEL_ID_TIME_CLI: {
#if 0
model->op = ((bfl_ble_mesh_model_op_t *)time_cli_op);
bt_mesh_time_client_t *cli = (bt_mesh_time_client_t *)model->user_data;
if (cli != NULL) {
cli->publish_status = btc_ble_mesh_time_scene_client_publish_callback;
}
#endif
break;
}
case BT_MESH_MODEL_ID_SCENE_CLI: {
#if 0
model->op = ((bfl_ble_mesh_model_op_t *)scene_cli_op);
bt_mesh_scene_client_t *cli = (bt_mesh_scene_client_t *)model->user_data;
if (cli != NULL) {
cli->publish_status = btc_ble_mesh_time_scene_client_publish_callback;
}
#endif
break;
}
case BT_MESH_MODEL_ID_SCHEDULER_CLI: {
#if 0
model->op = ((bfl_ble_mesh_model_op_t *)scheduler_cli_op);
bt_mesh_scheduler_client_t *cli = (bt_mesh_scheduler_client_t *)model->user_data;
if (cli != NULL) {
cli->publish_status = btc_ble_mesh_time_scene_client_publish_callback;
}
#endif
break;
}
case BT_MESH_MODEL_ID_GEN_ONOFF_SRV:
model->op = gen_onoff_srv_op;
if (model->pub) {
model->pub->update = btc_ble_mesh_model_publish_update;
}
break;
case BT_MESH_MODEL_ID_GEN_LEVEL_SRV:
model->op = gen_level_srv_op;
if (model->pub) {
model->pub->update = btc_ble_mesh_model_publish_update;
}
break;
case BT_MESH_MODEL_ID_GEN_DEF_TRANS_TIME_SRV:
model->op = gen_def_trans_time_srv_op;
if (model->pub) {
model->pub->update = btc_ble_mesh_model_publish_update;
}
break;
case BT_MESH_MODEL_ID_GEN_POWER_ONOFF_SRV:
model->op = gen_power_onoff_srv_op;
if (model->pub) {
model->pub->update = btc_ble_mesh_model_publish_update;
}
break;
case BT_MESH_MODEL_ID_GEN_POWER_ONOFF_SETUP_SRV:
model->op = gen_power_onoff_setup_srv_op;
if (model->pub) {
model->pub->update = btc_ble_mesh_model_publish_update;
}
break;
case BT_MESH_MODEL_ID_GEN_POWER_LEVEL_SRV:
model->op = gen_power_level_srv_op;
if (model->pub) {
model->pub->update = btc_ble_mesh_model_publish_update;
}
break;
case BT_MESH_MODEL_ID_GEN_POWER_LEVEL_SETUP_SRV:
model->op = gen_power_level_setup_srv_op;
if (model->pub) {
model->pub->update = btc_ble_mesh_model_publish_update;
}
break;
case BT_MESH_MODEL_ID_GEN_BATTERY_SRV:
model->op = gen_battery_srv_op;
if (model->pub) {
model->pub->update = btc_ble_mesh_model_publish_update;
}
break;
case BT_MESH_MODEL_ID_GEN_LOCATION_SRV:
model->op = gen_location_srv_op;
if (model->pub) {
model->pub->update = btc_ble_mesh_model_publish_update;
}
break;
case BT_MESH_MODEL_ID_GEN_USER_PROP_SRV:
model->op = gen_user_prop_srv_op;
if (model->pub) {
model->pub->update = btc_ble_mesh_model_publish_update;
}
break;
case BT_MESH_MODEL_ID_GEN_ADMIN_PROP_SRV:
model->op = gen_admin_prop_srv_op;
if (model->pub) {
model->pub->update = btc_ble_mesh_model_publish_update;
}
break;
case BT_MESH_MODEL_ID_GEN_MANUFACTURER_PROP_SRV:
model->op = gen_manu_prop_srv_op;
if (model->pub) {
model->pub->update = btc_ble_mesh_model_publish_update;
}
break;
case BT_MESH_MODEL_ID_GEN_CLIENT_PROP_SRV:
model->op = gen_client_prop_srv_op;
if (model->pub) {
model->pub->update = btc_ble_mesh_model_publish_update;
}
break;
case BT_MESH_MODEL_ID_GEN_LOCATION_SETUP_SRV:
model->op = gen_location_setup_srv_op;
if (model->pub) {
model->pub->update = btc_ble_mesh_model_publish_update;
}
break;
case BT_MESH_MODEL_ID_LIGHT_LIGHTNESS_SRV:
model->op = light_lightness_srv_op;
if (model->pub) {
model->pub->update = btc_ble_mesh_model_publish_update;
}
break;
case BT_MESH_MODEL_ID_LIGHT_LIGHTNESS_SETUP_SRV:
model->op = light_lightness_setup_srv_op;
if (model->pub) {
model->pub->update = btc_ble_mesh_model_publish_update;
}
break;
case BT_MESH_MODEL_ID_LIGHT_CTL_SRV:
model->op = light_ctl_srv_op;
if (model->pub) {
model->pub->update = btc_ble_mesh_model_publish_update;
}
break;
case BT_MESH_MODEL_ID_LIGHT_CTL_SETUP_SRV:
model->op = light_ctl_setup_srv_op;
if (model->pub) {
model->pub->update = btc_ble_mesh_model_publish_update;
}
break;
case BT_MESH_MODEL_ID_LIGHT_CTL_TEMP_SRV:
model->op = light_ctl_temp_srv_op;
if (model->pub) {
model->pub->update = btc_ble_mesh_model_publish_update;
}
break;
case BT_MESH_MODEL_ID_LIGHT_HSL_SRV:
model->op = light_hsl_srv_op;
if (model->pub) {
model->pub->update = btc_ble_mesh_model_publish_update;
}
break;
case BT_MESH_MODEL_ID_LIGHT_HSL_HUE_SRV:
model->op = light_hsl_hue_srv_op;
if (model->pub) {
model->pub->update = btc_ble_mesh_model_publish_update;
}
break;
case BT_MESH_MODEL_ID_LIGHT_HSL_SAT_SRV:
model->op = light_hsl_sat_srv_op;
if (model->pub) {
model->pub->update = btc_ble_mesh_model_publish_update;
}
break;
case BT_MESH_MODEL_ID_LIGHT_HSL_SETUP_SRV:
model->op = light_hsl_setup_srv_op;
if (model->pub) {
model->pub->update = btc_ble_mesh_model_publish_update;
}
break;
case BT_MESH_MODEL_ID_LIGHT_XYL_SRV:
model->op = light_xyl_srv_op;
if (model->pub) {
model->pub->update = btc_ble_mesh_model_publish_update;
}
break;
case BT_MESH_MODEL_ID_LIGHT_XYL_SETUP_SRV:
model->op = light_xyl_setup_srv_op;
if (model->pub) {
model->pub->update = btc_ble_mesh_model_publish_update;
}
break;
case BT_MESH_MODEL_ID_LIGHT_LC_SRV:
model->op = light_lc_srv_op;
if (model->pub) {
model->pub->update = btc_ble_mesh_model_publish_update;
}
break;
case BT_MESH_MODEL_ID_LIGHT_LC_SETUP_SRV:
model->op = light_lc_setup_srv_op;
if (model->pub) {
model->pub->update = btc_ble_mesh_model_publish_update;
}
break;
case BT_MESH_MODEL_ID_TIME_SRV:
#if 0
model->op = (bfl_ble_mesh_model_op_t *)time_srv_op;
if (model->pub) {
model->pub->update = (bfl_ble_mesh_cb_t)btc_ble_mesh_model_publish_update;
}
#endif
break;
case BT_MESH_MODEL_ID_TIME_SETUP_SRV:
#if 0
model->op = (bfl_ble_mesh_model_op_t *)time_setup_srv_op;
if (model->pub) {
/* Time Setup Server model does not support subscribing nor publishing. */
BT_ERR("%s, Time Setup Server shall not support publication", __func__);
return;
}
#endif
break;
case BT_MESH_MODEL_ID_SCENE_SRV:
#if 0
model->op = (bfl_ble_mesh_model_op_t *)scene_srv_op;
if (model->pub) {
model->pub->update = (bfl_ble_mesh_cb_t)btc_ble_mesh_model_publish_update;
}
#endif
break;
case BT_MESH_MODEL_ID_SCENE_SETUP_SRV:
#if 0
model->op = (bfl_ble_mesh_model_op_t *)scene_setup_srv_op;
if (model->pub) {
model->pub->update = (bfl_ble_mesh_cb_t)btc_ble_mesh_model_publish_update;
}
#endif
break;
case BT_MESH_MODEL_ID_SCHEDULER_SRV:
#if 0
model->op = (bfl_ble_mesh_model_op_t *)scheduler_srv_op;
if (model->pub) {
model->pub->update = (bfl_ble_mesh_cb_t)btc_ble_mesh_model_publish_update;
}
#endif
break;
case BT_MESH_MODEL_ID_SCHEDULER_SETUP_SRV:
#if 0
model->op = (bfl_ble_mesh_model_op_t *)scheduler_setup_srv_op;
if (model->pub) {
model->pub->update = (bfl_ble_mesh_cb_t)btc_ble_mesh_model_publish_update;
}
#endif
break;
case BT_MESH_MODEL_ID_SENSOR_SRV:
#if 0
model->op = (bfl_ble_mesh_model_op_t *)sensor_srv_op;
if (model->pub) {
model->pub->update = (bfl_ble_mesh_cb_t)btc_ble_mesh_model_publish_update;
}
#endif
break;
case BT_MESH_MODEL_ID_SENSOR_SETUP_SRV:
#if 0
model->op = (bfl_ble_mesh_model_op_t *)sensor_setup_srv_op;
if (model->pub) {
model->pub->update = (bfl_ble_mesh_cb_t)btc_ble_mesh_model_publish_update;
}
#endif
break;
default:
goto add_model_op;
}
return;
add_model_op:
if (model->pub) {
model->pub->update = btc_ble_mesh_model_publish_update;
}
op = (bfl_ble_mesh_model_op_t *)model->op;
while (op != NULL && op->opcode != 0) {
op->func = btc_ble_mesh_server_model_op_cb;
op++;
}
return;
}
void btc_ble_mesh_prov_call_handler(btc_msg_t *msg)
{
bfl_ble_mesh_prov_cb_param_t param = {0};
btc_ble_mesh_prov_args_t *arg = NULL;
uint8_t act = 0U;
if (!msg) {
BT_ERR("%s, Invalid parameter", __func__);
return;
}
arg = (btc_ble_mesh_prov_args_t *)(msg->arg);
switch (msg->act) {
case BTC_BLE_MESH_ACT_MESH_INIT: {
int err_code = 0;
for (int i = 0; i < arg->mesh_init.comp->elem_count; i++) {
bfl_ble_mesh_elem_t *elem = &arg->mesh_init.comp->elem[i];
/* For SIG models */
for (int j = 0; j < elem->model_count; j++) {
bfl_ble_mesh_model_t *sig_model = &elem->models[j];
/* The opcode of sig model should be 1 or 2 bytes. */
if (sig_model && sig_model->op && (sig_model->op->opcode >= 0x10000)) {
err_code = -EINVAL;
btc_ble_mesh_prov_register_complete_cb(err_code);
return;
}
btc_ble_mesh_model_op_add(sig_model);
}
/* For vendor models */
for (int k = 0; k < elem->vnd_model_count; k++) {
bfl_ble_mesh_model_t *vnd_model = &elem->vnd_models[k];
/* The opcode of vendor model should be 3 bytes. */
if (vnd_model && vnd_model->op && vnd_model->op->opcode < 0x10000) {
err_code = -EINVAL;
btc_ble_mesh_prov_register_complete_cb(err_code);
return;
}
btc_ble_mesh_model_op_add(vnd_model);
}
}
#if CONFIG_BLE_MESH_NODE
arg->mesh_init.prov->oob_pub_key_cb = (bfl_ble_mesh_cb_t)btc_ble_mesh_oob_pub_key_cb;
arg->mesh_init.prov->output_num_cb = (bfl_ble_mesh_cb_t)btc_ble_mesh_output_number_cb;
arg->mesh_init.prov->output_str_cb = (bfl_ble_mesh_cb_t)btc_ble_mesh_output_string_cb;
arg->mesh_init.prov->input_cb = (bfl_ble_mesh_cb_t)btc_ble_mesh_input_cb;
arg->mesh_init.prov->link_open_cb = (bfl_ble_mesh_cb_t)btc_ble_mesh_link_open_cb;
arg->mesh_init.prov->link_close_cb = (bfl_ble_mesh_cb_t)btc_ble_mesh_link_close_cb;
arg->mesh_init.prov->complete_cb = (bfl_ble_mesh_cb_t)btc_ble_mesh_complete_cb;
arg->mesh_init.prov->reset_cb = (bfl_ble_mesh_cb_t)btc_ble_mesh_reset_cb;
#endif /* CONFIG_BLE_MESH_NODE */
#if CONFIG_BLE_MESH_PROVISIONER
arg->mesh_init.prov->provisioner_prov_read_oob_pub_key = (bfl_ble_mesh_cb_t)btc_ble_mesh_provisioner_prov_read_oob_pub_key_cb;
arg->mesh_init.prov->provisioner_prov_input = (bfl_ble_mesh_cb_t)btc_ble_mesh_provisioner_prov_input_cb;
arg->mesh_init.prov->provisioner_prov_output = (bfl_ble_mesh_cb_t)btc_ble_mesh_provisioner_prov_output_cb;
arg->mesh_init.prov->provisioner_link_open = (bfl_ble_mesh_cb_t)btc_ble_mesh_provisioner_link_open_cb;
arg->mesh_init.prov->provisioner_link_close = (bfl_ble_mesh_cb_t)btc_ble_mesh_provisioner_link_close_cb;
arg->mesh_init.prov->provisioner_prov_comp = (bfl_ble_mesh_cb_t)btc_ble_mesh_provisioner_prov_complete_cb;
bt_mesh_provisioner_adv_pkt_cb_register(btc_ble_mesh_provisioner_recv_unprov_adv_pkt_cb);
#endif /* CONFIG_BLE_MESH_PROVISIONER */
#if CONFIG_BLE_MESH_LOW_POWER
bt_mesh_lpn_set_cb(btc_ble_mesh_lpn_cb);
#endif /* CONFIG_BLE_MESH_LOW_POWER */
#if CONFIG_BLE_MESH_FRIEND
bt_mesh_friend_set_cb(btc_ble_mesh_friend_cb);
#endif /* CONFIG_BLE_MESH_FRIEND */
#if CONFIG_BLE_MESH_GATT_PROXY_CLIENT
bt_mesh_proxy_client_set_adv_recv_cb(btc_ble_mesh_proxy_client_adv_recv_cb);
bt_mesh_proxy_client_set_conn_cb(btc_ble_mesh_proxy_client_connect_cb);
bt_mesh_proxy_client_set_disconn_cb(btc_ble_mesh_proxy_client_disconnect_cb);
bt_mesh_proxy_client_set_filter_status_cb(btc_ble_mesh_proxy_client_filter_status_recv_cb);
#endif /* CONFIG_BLE_MESH_GATT_PROXY_CLIENT */
err_code = bt_mesh_init((struct bt_mesh_prov *)arg->mesh_init.prov,
(struct bt_mesh_comp *)arg->mesh_init.comp);
/* Give the semaphore when BLE Mesh initialization is finished. */
xSemaphoreGive(arg->mesh_init.semaphore);
btc_ble_mesh_prov_register_complete_cb(err_code);
return;
}
#if CONFIG_BLE_MESH_NODE
case BTC_BLE_MESH_ACT_PROV_ENABLE:
BT_DBG("%s, BTC_BLE_MESH_ACT_PROV_ENABLE, bearers = %d", __func__, arg->node_prov_enable.bearers);
act = BFL_BLE_MESH_NODE_PROV_ENABLE_COMP_EVT;
param.node_prov_enable_comp.err_code = bt_mesh_prov_enable(arg->node_prov_enable.bearers);
break;
case BTC_BLE_MESH_ACT_PROV_DISABLE:
BT_DBG("%s, BTC_BLE_MESH_ACT_PROV_DISABLE, bearers = %d", __func__, arg->node_prov_disable.bearers);
act = BFL_BLE_MESH_NODE_PROV_DISABLE_COMP_EVT;
param.node_prov_disable_comp.err_code = bt_mesh_prov_disable(arg->node_prov_disable.bearers);
break;
case BTC_BLE_MESH_ACT_NODE_RESET:
BT_DBG("%s, BTC_BLE_MESH_ACT_NODE_RESET", __func__);
bt_mesh_reset();
return;
case BTC_BLE_MESH_ACT_SET_OOB_PUB_KEY:
#if 0
act = BFL_BLE_MESH_NODE_PROV_SET_OOB_PUB_KEY_COMP_EVT;
param.node_prov_set_oob_pub_key_comp.err_code =
bt_mesh_set_oob_pub_key(arg->set_oob_pub_key.pub_key_x,
arg->set_oob_pub_key.pub_key_y,
arg->set_oob_pub_key.private_key);
#endif
break;
case BTC_BLE_MESH_ACT_INPUT_NUMBER:
act = BFL_BLE_MESH_NODE_PROV_INPUT_NUMBER_COMP_EVT;
param.node_prov_input_num_comp.err_code = bt_mesh_input_number(arg->input_number.number);
break;
case BTC_BLE_MESH_ACT_INPUT_STRING:
act = BFL_BLE_MESH_NODE_PROV_INPUT_STRING_COMP_EVT;
param.node_prov_input_str_comp.err_code = bt_mesh_input_string(arg->input_string.string);
break;
#endif /* CONFIG_BLE_MESH_NODE */
#if (CONFIG_BLE_MESH_NODE && CONFIG_BLE_MESH_PB_GATT) || \
CONFIG_BLE_MESH_GATT_PROXY_SERVER
case BTC_BLE_MESH_ACT_SET_DEVICE_NAME:
act = BFL_BLE_MESH_NODE_SET_UNPROV_DEV_NAME_COMP_EVT;
param.node_set_unprov_dev_name_comp.err_code = bt_mesh_set_device_name(arg->set_device_name.name);
break;
#if defined(CONFIG_BLE_MESH_GATT_PROXY_SERVER)
case BTC_BLE_MESH_ACT_PROXY_IDENTITY_ENABLE:
act = BFL_BLE_MESH_NODE_PROXY_IDENTITY_ENABLE_COMP_EVT;
param.node_proxy_identity_enable_comp.err_code = bt_mesh_proxy_identity_enable();
break;
case BTC_BLE_MESH_ACT_PROXY_GATT_ENABLE:
act = BFL_BLE_MESH_NODE_PROXY_GATT_ENABLE_COMP_EVT;
param.node_proxy_gatt_enable_comp.err_code = bt_mesh_proxy_gatt_enable();
break;
case BTC_BLE_MESH_ACT_PROXY_GATT_DISABLE:
act = BFL_BLE_MESH_NODE_PROXY_GATT_DISABLE_COMP_EVT;
param.node_proxy_gatt_disable_comp.err_code = bt_mesh_proxy_gatt_disable();
break;
#endif /* CONFIG_BLE_MESH_GATT_PROXY_SERVER */
#endif /* (CONFIG_BLE_MESH_NODE && CONFIG_BLE_MESH_PB_GATT) || CONFIG_BLE_MESH_GATT_PROXY_SERVER */
#if CONFIG_BLE_MESH_PROVISIONER
case BTC_BLE_MESH_ACT_PROVISIONER_READ_OOB_PUB_KEY:
act = BFL_BLE_MESH_PROVISIONER_PROV_READ_OOB_PUB_KEY_COMP_EVT;
param.provisioner_prov_read_oob_pub_key_comp.err_code =
bt_mesh_provisioner_read_oob_pub_key(arg->provisioner_read_oob_pub_key.link_idx,
arg->provisioner_read_oob_pub_key.pub_key_x,
arg->provisioner_read_oob_pub_key.pub_key_y);
break;
case BTC_BLE_MESH_ACT_PROVISIONER_INPUT_STR:
act = BFL_BLE_MESH_PROVISIONER_PROV_INPUT_STRING_COMP_EVT;
param.provisioner_prov_input_str_comp.err_code =
bt_mesh_provisioner_set_oob_input_data(arg->provisioner_input_str.link_idx,
(const u8_t *)&arg->provisioner_input_str.string, false);
break;
case BTC_BLE_MESH_ACT_PROVISIONER_INPUT_NUM:
act = BFL_BLE_MESH_PROVISIONER_PROV_INPUT_NUMBER_COMP_EVT;
param.provisioner_prov_input_num_comp.err_code =
bt_mesh_provisioner_set_oob_input_data(arg->provisioner_input_num.link_idx,
(const u8_t *)&arg->provisioner_input_num.number, true);
break;
case BTC_BLE_MESH_ACT_PROVISIONER_ENABLE:
act = BFL_BLE_MESH_PROVISIONER_PROV_ENABLE_COMP_EVT;
param.provisioner_prov_enable_comp.err_code =
bt_mesh_provisioner_enable(arg->provisioner_enable.bearers);
break;
case BTC_BLE_MESH_ACT_PROVISIONER_DISABLE:
act = BFL_BLE_MESH_PROVISIONER_PROV_DISABLE_COMP_EVT;
param.provisioner_prov_disable_comp.err_code =
bt_mesh_provisioner_disable(arg->provisioner_disable.bearers);
break;
case BTC_BLE_MESH_ACT_PROVISIONER_DEV_ADD: {
struct bt_mesh_unprov_dev_add add_dev = {0};
add_dev.addr_type = arg->provisioner_dev_add.add_dev.addr_type;
add_dev.oob_info = arg->provisioner_dev_add.add_dev.oob_info;
add_dev.bearer = arg->provisioner_dev_add.add_dev.bearer;
memcpy(add_dev.addr, arg->provisioner_dev_add.add_dev.addr, 6);
memcpy(add_dev.uuid, arg->provisioner_dev_add.add_dev.uuid, 16);
act = BFL_BLE_MESH_PROVISIONER_ADD_UNPROV_DEV_COMP_EVT;
param.provisioner_add_unprov_dev_comp.err_code =
bt_mesh_provisioner_add_unprov_dev(&add_dev, arg->provisioner_dev_add.flags);
break;
}
case BTC_BLE_MESH_ACT_PROVISIONER_PROV_DEV_WITH_ADDR:
act = BFL_BLE_MESH_PROVISIONER_PROV_DEV_WITH_ADDR_COMP_EVT;
param.provisioner_prov_dev_with_addr_comp.err_code =
bt_mesh_provisioner_prov_device_with_addr(arg->provisioner_prov_dev_with_addr.uuid,
arg->provisioner_prov_dev_with_addr.addr, arg->provisioner_prov_dev_with_addr.addr_type,
arg->provisioner_prov_dev_with_addr.bearer, arg->provisioner_prov_dev_with_addr.oob_info,
arg->provisioner_prov_dev_with_addr.unicast_addr);
break;
case BTC_BLE_MESH_ACT_PROVISIONER_DEV_DEL: {
struct bt_mesh_device_delete del_dev = {0};
if (arg->provisioner_dev_del.del_dev.flag & DEL_DEV_ADDR_FLAG) {
del_dev.addr_type = arg->provisioner_dev_del.del_dev.addr_type;
memcpy(del_dev.addr, arg->provisioner_dev_del.del_dev.addr, 6);
} else if (arg->provisioner_dev_del.del_dev.flag & DEL_DEV_UUID_FLAG) {
memcpy(del_dev.uuid, arg->provisioner_dev_del.del_dev.uuid, 16);
}
act = BFL_BLE_MESH_PROVISIONER_DELETE_DEV_COMP_EVT;
param.provisioner_delete_dev_comp.err_code = bt_mesh_provisioner_delete_device(&del_dev);
break;
}
case BTC_BLE_MESH_ACT_PROVISIONER_SET_DEV_UUID_MATCH:
act = BFL_BLE_MESH_PROVISIONER_SET_DEV_UUID_MATCH_COMP_EVT;
param.provisioner_set_dev_uuid_match_comp.err_code =
bt_mesh_provisioner_set_dev_uuid_match(arg->set_dev_uuid_match.offset,
arg->set_dev_uuid_match.match_len,
arg->set_dev_uuid_match.match_val,
arg->set_dev_uuid_match.prov_after_match);
break;
case BTC_BLE_MESH_ACT_PROVISIONER_SET_PROV_DATA_INFO: {
struct bt_mesh_prov_data_info info = {0};
info.flag = arg->set_prov_data_info.prov_data.flag;
if (arg->set_prov_data_info.prov_data.flag & PROV_DATA_NET_IDX_FLAG) {
info.net_idx = arg->set_prov_data_info.prov_data.net_idx;
} else if (arg->set_prov_data_info.prov_data.flag & PROV_DATA_FLAGS_FLAG) {
info.flags = arg->set_prov_data_info.prov_data.flags;
} else if (arg->set_prov_data_info.prov_data.flag & PROV_DATA_IV_INDEX_FLAG) {
info.iv_index = arg->set_prov_data_info.prov_data.iv_index;
}
act = BFL_BLE_MESH_PROVISIONER_SET_PROV_DATA_INFO_COMP_EVT;
param.provisioner_set_prov_data_info_comp.err_code =
bt_mesh_provisioner_set_prov_data_info(&info);
break;
}
case BTC_BLE_MESH_ACT_PROVISIONER_SET_STATIC_OOB_VAL:
act = BFL_BLE_MESH_PROVISIONER_SET_STATIC_OOB_VALUE_COMP_EVT;
param.provisioner_set_static_oob_val_comp.err_code =
bt_mesh_provisioner_set_static_oob_value(
arg->set_static_oob_val.value, arg->set_static_oob_val.length);
break;
case BTC_BLE_MESH_ACT_PROVISIONER_SET_PRIMARY_ELEM_ADDR:
act = BFL_BLE_MESH_PROVISIONER_SET_PRIMARY_ELEM_ADDR_COMP_EVT;
param.provisioner_set_primary_elem_addr_comp.err_code =
bt_mesh_provisioner_set_primary_elem_addr(arg->set_primary_elem_addr.addr);
break;
case BTC_BLE_MESH_ACT_PROVISIONER_SET_NODE_NAME:
act = BFL_BLE_MESH_PROVISIONER_SET_NODE_NAME_COMP_EVT;
param.provisioner_set_node_name_comp.node_index = arg->set_node_name.index;
param.provisioner_set_node_name_comp.err_code =
bt_mesh_provisioner_set_node_name(arg->set_node_name.index, arg->set_node_name.name);
break;
case BTC_BLE_MESH_ACT_PROVISIONER_ADD_LOCAL_APP_KEY: {
const u8_t *app_key = NULL;
const u8_t zero[16] = {0};
if (memcmp(arg->add_local_app_key.app_key, zero, 16)) {
app_key = arg->add_local_app_key.app_key;
}
act = BFL_BLE_MESH_PROVISIONER_ADD_LOCAL_APP_KEY_COMP_EVT;
param.provisioner_add_app_key_comp.app_idx = arg->add_local_app_key.app_idx;
param.provisioner_add_app_key_comp.err_code =
bt_mesh_provisioner_local_app_key_add(app_key, arg->add_local_app_key.net_idx,
&arg->add_local_app_key.app_idx);
break;
}
case BTC_BLE_MESH_ACT_PROVISIONER_UPDATE_LOCAL_APP_KEY:
act = BFL_BLE_MESH_PROVISIONER_UPDATE_LOCAL_APP_KEY_COMP_EVT;
param.provisioner_update_app_key_comp.net_idx = arg->update_local_app_key.net_idx;
param.provisioner_update_app_key_comp.app_idx = arg->update_local_app_key.app_idx;
param.provisioner_update_app_key_comp.err_code =
bt_mesh_provisioner_local_app_key_update(arg->update_local_app_key.app_key,
arg->update_local_app_key.net_idx, arg->update_local_app_key.app_idx);
break;
case BTC_BLE_MESH_ACT_PROVISIONER_BIND_LOCAL_MOD_APP:
act = BFL_BLE_MESH_PROVISIONER_BIND_APP_KEY_TO_MODEL_COMP_EVT;
param.provisioner_bind_app_key_to_model_comp.element_addr = arg->local_mod_app_bind.elem_addr;
param.provisioner_bind_app_key_to_model_comp.app_idx = arg->local_mod_app_bind.app_idx;
param.provisioner_bind_app_key_to_model_comp.company_id = arg->local_mod_app_bind.cid;
param.provisioner_bind_app_key_to_model_comp.model_id = arg->local_mod_app_bind.model_id;
param.provisioner_bind_app_key_to_model_comp.err_code =
bt_mesh_provisioner_bind_local_model_app_idx(arg->local_mod_app_bind.elem_addr,
arg->local_mod_app_bind.model_id,
arg->local_mod_app_bind.cid,
arg->local_mod_app_bind.app_idx);
break;
case BTC_BLE_MESH_ACT_PROVISIONER_ADD_LOCAL_NET_KEY: {
const u8_t *net_key = NULL;
const u8_t zero[16] = {0};
if (memcmp(arg->add_local_net_key.net_key, zero, 16)) {
net_key = arg->add_local_net_key.net_key;
}
act = BFL_BLE_MESH_PROVISIONER_ADD_LOCAL_NET_KEY_COMP_EVT;
param.provisioner_add_net_key_comp.net_idx = arg->add_local_net_key.net_idx;
param.provisioner_add_net_key_comp.err_code =
bt_mesh_provisioner_local_net_key_add(net_key, &arg->add_local_net_key.net_idx);
break;
}
case BTC_BLE_MESH_ACT_PROVISIONER_UPDATE_LOCAL_NET_KEY:
act = BFL_BLE_MESH_PROVISIONER_UPDATE_LOCAL_NET_KEY_COMP_EVT;
param.provisioner_update_net_key_comp.net_idx = arg->update_local_net_key.net_idx;
param.provisioner_update_net_key_comp.err_code =
bt_mesh_provisioner_local_net_key_update(arg->update_local_net_key.net_key,
arg->update_local_net_key.net_idx);
break;
case BTC_BLE_MESH_ACT_PROVISIONER_STORE_NODE_COMP_DATA:
act = BFL_BLE_MESH_PROVISIONER_STORE_NODE_COMP_DATA_COMP_EVT;
param.provisioner_store_node_comp_data_comp.addr = arg->store_node_comp_data.unicast_addr;
param.provisioner_store_node_comp_data_comp.err_code =
bt_mesh_provisioner_store_node_comp_data(arg->store_node_comp_data.unicast_addr,
arg->store_node_comp_data.data, arg->store_node_comp_data.length);
break;
case BTC_BLE_MESH_ACT_PROVISIONER_DELETE_NODE_WITH_UUID:
act = BFL_BLE_MESH_PROVISIONER_DELETE_NODE_WITH_UUID_COMP_EVT;
memcpy(param.provisioner_delete_node_with_uuid_comp.uuid, arg->delete_node_with_uuid.uuid, 16);
param.provisioner_delete_node_with_uuid_comp.err_code =
bt_mesh_provisioner_delete_node_with_uuid(arg->delete_node_with_uuid.uuid);
break;
case BTC_BLE_MESH_ACT_PROVISIONER_DELETE_NODE_WITH_ADDR:
act = BFL_BLE_MESH_PROVISIONER_DELETE_NODE_WITH_ADDR_COMP_EVT;
param.provisioner_delete_node_with_addr_comp.unicast_addr = arg->delete_node_with_addr.unicast_addr;
param.provisioner_delete_node_with_addr_comp.err_code =
bt_mesh_provisioner_delete_node_with_node_addr(arg->delete_node_with_addr.unicast_addr);
break;
#endif /* CONFIG_BLE_MESH_PROVISIONER */
#if CONFIG_BLE_MESH_FAST_PROV
case BTC_BLE_MESH_ACT_SET_FAST_PROV_INFO:
act = BFL_BLE_MESH_SET_FAST_PROV_INFO_COMP_EVT;
param.set_fast_prov_info_comp.status_unicast =
bt_mesh_set_fast_prov_unicast_addr_range(arg->set_fast_prov_info.unicast_min,
arg->set_fast_prov_info.unicast_max);
param.set_fast_prov_info_comp.status_net_idx =
bt_mesh_set_fast_prov_net_idx(arg->set_fast_prov_info.net_idx);
bt_mesh_set_fast_prov_flags_iv_index(arg->set_fast_prov_info.flags,
arg->set_fast_prov_info.iv_index);
param.set_fast_prov_info_comp.status_match =
bt_mesh_provisioner_set_dev_uuid_match(arg->set_fast_prov_info.offset,
arg->set_fast_prov_info.match_len,
arg->set_fast_prov_info.match_val, false);
break;
case BTC_BLE_MESH_ACT_SET_FAST_PROV_ACTION:
act = BFL_BLE_MESH_SET_FAST_PROV_ACTION_COMP_EVT;
param.set_fast_prov_action_comp.status_action =
bt_mesh_set_fast_prov_action(arg->set_fast_prov_action.action);
break;
#endif /* CONFIG_BLE_MESH_FAST_PROV */
#if CONFIG_BLE_MESH_LOW_POWER
case BTC_BLE_MESH_ACT_LPN_ENABLE:
act = BFL_BLE_MESH_LPN_ENABLE_COMP_EVT;
param.lpn_enable_comp.err_code = bt_mesh_lpn_set(true, false);
break;
case BTC_BLE_MESH_ACT_LPN_DISABLE:
act = BFL_BLE_MESH_LPN_DISABLE_COMP_EVT;
param.lpn_disable_comp.err_code = bt_mesh_lpn_set(false, arg->lpn_disable.force);
break;
case BTC_BLE_MESH_ACT_LPN_POLL:
act = BFL_BLE_MESH_LPN_POLL_COMP_EVT;
param.lpn_poll_comp.err_code = bt_mesh_lpn_poll();
break;
#endif /* CONFIG_BLE_MESH_LOW_POWER */
#if CONFIG_BLE_MESH_GATT_PROXY_CLIENT
case BTC_BLE_MESH_ACT_PROXY_CLIENT_CONNECT:
act = BFL_BLE_MESH_PROXY_CLIENT_CONNECT_COMP_EVT;
memcpy(param.proxy_client_connect_comp.addr, arg->proxy_client_connect.addr, BD_ADDR_LEN);
param.proxy_client_connect_comp.addr_type = arg->proxy_client_connect.addr_type;
param.proxy_client_connect_comp.net_idx = arg->proxy_client_connect.net_idx;
param.proxy_client_connect_comp.err_code =
bt_mesh_proxy_client_connect(arg->proxy_client_connect.addr,
arg->proxy_client_connect.addr_type,
arg->proxy_client_connect.net_idx);
break;
case BTC_BLE_MESH_ACT_PROXY_CLIENT_DISCONNECT:
act = BFL_BLE_MESH_PROXY_CLIENT_DISCONNECT_COMP_EVT;
param.proxy_client_disconnect_comp.conn_handle = arg->proxy_client_disconnect.conn_handle;
param.proxy_client_disconnect_comp.err_code =
bt_mesh_proxy_client_disconnect(arg->proxy_client_disconnect.conn_handle);
break;
case BTC_BLE_MESH_ACT_PROXY_CLIENT_SET_FILTER_TYPE: {
struct bt_mesh_proxy_cfg_pdu pdu = {
.opcode = BLE_MESH_PROXY_CFG_FILTER_SET,
.set.filter_type = arg->proxy_client_set_filter_type.filter_type,
};
act = BFL_BLE_MESH_PROXY_CLIENT_SET_FILTER_TYPE_COMP_EVT;
param.proxy_client_set_filter_type_comp.conn_handle = arg->proxy_client_set_filter_type.conn_handle;
param.proxy_client_set_filter_type_comp.net_idx = arg->proxy_client_set_filter_type.net_idx;
param.proxy_client_set_filter_type_comp.err_code =
bt_mesh_proxy_client_send_cfg(arg->proxy_client_set_filter_type.conn_handle,
arg->proxy_client_set_filter_type.net_idx, &pdu);
break;
}
case BTC_BLE_MESH_ACT_PROXY_CLIENT_ADD_FILTER_ADDR: {
struct bt_mesh_proxy_cfg_pdu pdu = {
.opcode = BLE_MESH_PROXY_CFG_FILTER_ADD,
.add.addr = arg->proxy_client_add_filter_addr.addr,
.add.addr_num = arg->proxy_client_add_filter_addr.addr_num,
};
act = BFL_BLE_MESH_PROXY_CLIENT_ADD_FILTER_ADDR_COMP_EVT;
param.proxy_client_add_filter_addr_comp.conn_handle = arg->proxy_client_add_filter_addr.conn_handle;
param.proxy_client_add_filter_addr_comp.net_idx = arg->proxy_client_add_filter_addr.net_idx;
param.proxy_client_add_filter_addr_comp.err_code =
bt_mesh_proxy_client_send_cfg(arg->proxy_client_add_filter_addr.conn_handle,
arg->proxy_client_add_filter_addr.net_idx, &pdu);
break;
}
case BTC_BLE_MESH_ACT_PROXY_CLIENT_REMOVE_FILTER_ADDR: {
struct bt_mesh_proxy_cfg_pdu pdu = {
.opcode = BLE_MESH_PROXY_CFG_FILTER_REMOVE,
.remove.addr = arg->proxy_client_remove_filter_addr.addr,
.remove.addr_num = arg->proxy_client_remove_filter_addr.addr_num,
};
act = BFL_BLE_MESH_PROXY_CLIENT_REMOVE_FILTER_ADDR_COMP_EVT;
param.proxy_client_remove_filter_addr_comp.conn_handle = arg->proxy_client_remove_filter_addr.conn_handle;
param.proxy_client_remove_filter_addr_comp.net_idx = arg->proxy_client_remove_filter_addr.net_idx;
param.proxy_client_remove_filter_addr_comp.err_code =
bt_mesh_proxy_client_send_cfg(arg->proxy_client_remove_filter_addr.conn_handle,
arg->proxy_client_remove_filter_addr.net_idx, &pdu);
break;
}
#endif /* CONFIG_BLE_MESH_GATT_PROXY_CLIENT */
#if CONFIG_BLE_MESH_SUPPORT_BLE_ADV
case BTC_BLE_MESH_ACT_START_BLE_ADVERTISING: {
struct bt_mesh_ble_adv_param *set = (struct bt_mesh_ble_adv_param *)&arg->start_ble_advertising.param;
struct bt_mesh_ble_adv_data *data = NULL;
if (arg->start_ble_advertising.data.adv_data_len ||
arg->start_ble_advertising.data.scan_rsp_data_len) {
data = (struct bt_mesh_ble_adv_data *)&arg->start_ble_advertising.data;
}
act = BFL_BLE_MESH_START_BLE_ADVERTISING_COMP_EVT;
param.start_ble_advertising_comp.err_code =
bt_mesh_start_ble_advertising(set, data, ¶m.start_ble_advertising_comp.index);
break;
}
case BTC_BLE_MESH_ACT_STOP_BLE_ADVERTISING:
act = BFL_BLE_MESH_STOP_BLE_ADVERTISING_COMP_EVT;
param.stop_ble_advertising_comp.index = arg->stop_ble_advertising.index;
param.stop_ble_advertising_comp.err_code =
bt_mesh_stop_ble_advertising(arg->stop_ble_advertising.index);
break;
#endif /* CONFIG_BLE_MESH_SUPPORT_BLE_ADV */
case BTC_BLE_MESH_ACT_MODEL_SUBSCRIBE_GROUP_ADDR:
act = BFL_BLE_MESH_MODEL_SUBSCRIBE_GROUP_ADDR_COMP_EVT;
param.model_sub_group_addr_comp.element_addr = arg->model_sub_group_addr.element_addr;
param.model_sub_group_addr_comp.company_id = arg->model_sub_group_addr.company_id;
param.model_sub_group_addr_comp.model_id = arg->model_sub_group_addr.model_id;
param.model_sub_group_addr_comp.group_addr = arg->model_sub_group_addr.group_addr;
param.model_sub_group_addr_comp.err_code =
bt_mesh_model_subscribe_group_addr(arg->model_sub_group_addr.element_addr,
arg->model_sub_group_addr.company_id,
arg->model_sub_group_addr.model_id,
arg->model_sub_group_addr.group_addr);
break;
case BTC_BLE_MESH_ACT_MODEL_UNSUBSCRIBE_GROUP_ADDR:
act = BFL_BLE_MESH_MODEL_UNSUBSCRIBE_GROUP_ADDR_COMP_EVT;
param.model_unsub_group_addr_comp.element_addr = arg->model_unsub_group_addr.element_addr;
param.model_unsub_group_addr_comp.company_id = arg->model_unsub_group_addr.company_id;
param.model_unsub_group_addr_comp.model_id = arg->model_unsub_group_addr.model_id;
param.model_unsub_group_addr_comp.group_addr = arg->model_unsub_group_addr.group_addr;
param.model_unsub_group_addr_comp.err_code =
bt_mesh_model_unsubscribe_group_addr(arg->model_unsub_group_addr.element_addr,
arg->model_unsub_group_addr.company_id,
arg->model_unsub_group_addr.model_id,
arg->model_unsub_group_addr.group_addr);
break;
case BTC_BLE_MESH_ACT_DEINIT_MESH:
act = BFL_BLE_MESH_DEINIT_MESH_COMP_EVT;
#if 0
param.deinit_mesh_comp.err_code = bt_mesh_deinit((struct bt_mesh_deinit_param *)&arg->mesh_deinit.param);
#endif
break;
default:
BT_WARN("%s, Invalid msg->act %d", __func__, msg->act);
return;
}
/* Callback operation completion events */
btc_ble_mesh_prov_set_complete_cb(¶m, act);
if (msg->arg) {
btc_ble_mesh_prov_arg_deep_free(msg);
}
return;
}
void btc_ble_mesh_prov_cb_handler(btc_msg_t *msg)
{
bfl_ble_mesh_prov_cb_param_t *param = NULL;
if (!msg) {
BT_ERR("%s, Invalid parameter", __func__);
return;
}
param = (bfl_ble_mesh_prov_cb_param_t *)(msg->arg);
if (msg->act < BFL_BLE_MESH_PROV_EVT_MAX) {
btc_ble_mesh_prov_cb_to_app(msg->act, param);
} else {
BT_ERR("%s, Unknown msg->act = %d", __func__, msg->act);
}
}
void btc_ble_mesh_model_call_handler(btc_msg_t *msg)
{
btc_ble_mesh_model_args_t *arg = NULL;
int err = 0;
if (!msg || !msg->arg) {
BT_ERR("%s, Invalid parameter", __func__);
return;
}
arg = (btc_ble_mesh_model_args_t *)(msg->arg);
switch (msg->act) {
case BTC_BLE_MESH_ACT_MODEL_PUBLISH: {
if (arg->model_publish.device_role == ROLE_PROVISIONER) {
bt_mesh_role_param_t common = {0};
common.model = (struct bt_mesh_model *)(arg->model_publish.model);
common.role = arg->model_publish.device_role;
if (bt_mesh_set_client_model_role(&common)) {
BT_ERR("%s, Failed to set model role", __func__);
break;
}
}
err = bt_mesh_model_publish((struct bt_mesh_model *)arg->model_publish.model);
btc_ble_mesh_model_publish_comp_cb(arg->model_publish.model, err);
break;
}
case BTC_BLE_MESH_ACT_SERVER_MODEL_SEND: {
/* arg->model_send.length contains opcode & payload, plus extra 4-bytes TransMIC */
struct net_buf_simple *buf = bt_mesh_alloc_buf(arg->model_send.length + BFL_BLE_MESH_MIC_SHORT);
if (!buf) {
BT_ERR("%s, Failed to allocate memory", __func__);
break;
}
net_buf_simple_add_mem(buf, arg->model_send.data, arg->model_send.length);
arg->model_send.ctx->srv_send = true;
err = bt_mesh_model_send((struct bt_mesh_model *)arg->model_send.model,
(struct bt_mesh_msg_ctx *)arg->model_send.ctx,
buf, NULL, NULL);
bt_mesh_free_buf(buf);
btc_ble_mesh_model_send_comp_cb(arg->model_send.model, arg->model_send.ctx,
arg->model_send.opcode, err);
break;
}
case BTC_BLE_MESH_ACT_CLIENT_MODEL_SEND: {
bt_mesh_role_param_t common = {0};
/* arg->model_send.length contains opcode & message, plus extra 4-bytes TransMIC */
struct net_buf_simple *buf = bt_mesh_alloc_buf(arg->model_send.length + BFL_BLE_MESH_MIC_SHORT);
if (!buf) {
BT_ERR("%s, Failed to allocate memory", __func__);
break;
}
net_buf_simple_add_mem(buf, arg->model_send.data, arg->model_send.length);
arg->model_send.ctx->srv_send = false;
common.model = (struct bt_mesh_model *)(arg->model_send.model);
common.role = arg->model_send.device_role;
if (bt_mesh_set_client_model_role(&common)) {
BT_ERR("%s, Failed to set model role", __func__);
break;
}
err = bt_mesh_client_send_msg((struct bt_mesh_model *)arg->model_send.model,
arg->model_send.opcode,
(struct bt_mesh_msg_ctx *)arg->model_send.ctx, buf,
btc_ble_mesh_client_model_timeout_cb, arg->model_send.msg_timeout,
arg->model_send.need_rsp, NULL, NULL);
bt_mesh_free_buf(buf);
btc_ble_mesh_model_send_comp_cb(arg->model_send.model, arg->model_send.ctx,
arg->model_send.opcode, err);
break;
}
case BTC_BLE_MESH_ACT_SERVER_MODEL_UPDATE_STATE:
err = bt_mesh_update_binding_state(
(struct bt_mesh_model *)arg->model_update_state.model, arg->model_update_state.type,
(bt_mesh_server_state_value_t *)arg->model_update_state.value);
btc_ble_mesh_server_model_update_state_comp_cb(arg->model_update_state.model,
arg->model_update_state.type, err);
break;
default:
BT_WARN("%s, Unknown msg->act %d", __func__, msg->act);
break;
}
btc_ble_mesh_model_arg_deep_free(msg);
return;
}
void btc_ble_mesh_model_cb_handler(btc_msg_t *msg)
{
bfl_ble_mesh_model_cb_param_t *param = NULL;
if (!msg || !msg->arg) {
BT_ERR("%s, Invalid parameter", __func__);
return;
}
param = (bfl_ble_mesh_model_cb_param_t *)(msg->arg);
if (msg->act < BFL_BLE_MESH_MODEL_EVT_MAX) {
btc_ble_mesh_model_cb_to_app(msg->act, param);
} else {
BT_ERR("%s, Unknown msg->act = %d", __func__, msg->act);
}
btc_ble_mesh_model_free_req_data(msg);
return;
}
| 40.339489 | 177 | 0.703851 | [
"mesh",
"model"
] |
3394b783a827784d518b9ad42d92b44c34f544af | 105,204 | h | C | ion_arginfo.h | awesomized/ext-ion | 174690b4ff30c8ae29a9c4ca639e94e888c38111 | [
"BSD-2-Clause"
] | 1 | 2022-02-25T12:49:44.000Z | 2022-02-25T12:49:44.000Z | ion_arginfo.h | awesomized/ext-ion | 174690b4ff30c8ae29a9c4ca639e94e888c38111 | [
"BSD-2-Clause"
] | 2 | 2022-02-25T16:26:26.000Z | 2022-03-15T11:16:03.000Z | ion_arginfo.h | awesomized/ext-ion | 174690b4ff30c8ae29a9c4ca639e94e888c38111 | [
"BSD-2-Clause"
] | 1 | 2022-02-01T13:08:22.000Z | 2022-02-01T13:08:22.000Z | /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 8b6aeb4c5c0a8a5af0f5a55cbf09fb2846032c07 */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ion_serialize, 0, 1, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, data, IS_MIXED, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, serializer, ion\\Serializer, MAY_BE_ARRAY|MAY_BE_NULL, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_ion_unserialize, 0, 1, IS_MIXED, 0)
ZEND_ARG_INFO(0, data)
ZEND_ARG_OBJ_TYPE_MASK(0, unserializer, ion\\Unserializer, MAY_BE_ARRAY|MAY_BE_NULL, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Serializer_serialize, 0, 1, IS_MIXED, 0)
ZEND_ARG_TYPE_INFO(0, data, IS_MIXED, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, writer, ion\\Writer, MAY_BE_ARRAY|MAY_BE_NULL, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Unserializer_unserialize, 0, 1, IS_MIXED, 0)
ZEND_ARG_INFO(0, data)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_ion_Symbol___construct, 0, 0, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, value, IS_STRING, 1, "null")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, sid, IS_LONG, 0, "-1")
ZEND_ARG_OBJ_INFO_WITH_DEFAULT_VALUE(0, importLocation, ion\\Symbol\\ImportLocation, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Symbol_equals, 0, 1, _IS_BOOL, 0)
ZEND_ARG_OBJ_INFO(0, symbol, ion\\Symbol, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Symbol___toString, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_ion_Symbol_toString arginfo_class_ion_Symbol___toString
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_ion_Catalog___construct, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Catalog_count, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Catalog_add, 0, 1, IS_VOID, 0)
ZEND_ARG_OBJ_INFO(0, table, ion\\Symbol\\Table, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Catalog_remove, 0, 1, _IS_BOOL, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, table, ion\\Symbol\\Table, MAY_BE_STRING, NULL)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_ion_Catalog_find, 0, 1, ion\\Symbol\\Table, 1)
ZEND_ARG_TYPE_INFO(0, name, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, version, IS_LONG, 0, "0")
ZEND_END_ARG_INFO()
#define arginfo_class_ion_Catalog_findBest arginfo_class_ion_Catalog_find
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_ion_LOB___construct, 0, 0, 1)
ZEND_ARG_TYPE_INFO(0, value, IS_STRING, 0)
ZEND_ARG_OBJ_INFO_WITH_DEFAULT_VALUE(0, type, ion\\Type, 0, "ion\\Type::CLob")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_ion_Decimal___construct, 0, 0, 1)
ZEND_ARG_TYPE_MASK(0, number, MAY_BE_STRING|MAY_BE_LONG, NULL)
ZEND_ARG_OBJ_INFO_WITH_DEFAULT_VALUE(0, context, ion\\Decimal\\Context, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Decimal_equals, 0, 1, _IS_BOOL, 0)
ZEND_ARG_OBJ_INFO(0, decimal, ion\\Decimal, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Decimal_isInt, 0, 0, _IS_BOOL, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_ion_Decimal___toString arginfo_class_ion_Symbol___toString
#define arginfo_class_ion_Decimal_toString arginfo_class_ion_Symbol___toString
#define arginfo_class_ion_Decimal_toInt arginfo_class_ion_Catalog_count
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_ion_Timestamp___construct, 0, 0, 1)
ZEND_ARG_OBJ_TYPE_MASK(0, precision, ion\\Timestamp\\Precision, MAY_BE_LONG, NULL)
ZEND_ARG_OBJ_TYPE_MASK(0, format, ion\\Timestamp\\Format, MAY_BE_STRING|MAY_BE_NULL, "null")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, datetime, IS_STRING, 1, "null")
ZEND_ARG_OBJ_TYPE_MASK(0, timezone, DateTimeZone, MAY_BE_STRING|MAY_BE_NULL, "null")
ZEND_END_ARG_INFO()
#define arginfo_class_ion_Timestamp___toString arginfo_class_ion_Symbol___toString
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_ion_Reader_getType, 0, 0, ion\\Type, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_ion_Reader_hasAnnotations arginfo_class_ion_Decimal_isInt
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Reader_hasAnnotation, 0, 1, _IS_BOOL, 0)
ZEND_ARG_TYPE_INFO(0, annotation, IS_STRING, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_ion_Reader_isNull arginfo_class_ion_Decimal_isInt
#define arginfo_class_ion_Reader_isInStruct arginfo_class_ion_Decimal_isInt
#define arginfo_class_ion_Reader_getFieldName arginfo_class_ion_Symbol___toString
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_ion_Reader_getFieldNameSymbol, 0, 0, ion\\Symbol, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Reader_getAnnotations, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_ion_Reader_getAnnotationSymbols arginfo_class_ion_Reader_getAnnotations
#define arginfo_class_ion_Reader_countAnnotations arginfo_class_ion_Catalog_count
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Reader_getAnnotation, 0, 1, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, index, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_ion_Reader_getAnnotationSymbol, 0, 1, ion\\Symbol, 0)
ZEND_ARG_TYPE_INFO(0, index, IS_LONG, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_ion_Reader_readNull arginfo_class_ion_Reader_getType
#define arginfo_class_ion_Reader_readBool arginfo_class_ion_Decimal_isInt
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_class_ion_Reader_readInt, 0, 0, MAY_BE_LONG|MAY_BE_STRING)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Reader_readFloat, 0, 0, IS_DOUBLE, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_ion_Reader_readDecimal, 0, 0, ion\\Decimal, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_ion_Reader_readTimestamp, 0, 0, ion\\Timestamp, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_ion_Reader_readSymbol arginfo_class_ion_Reader_getFieldNameSymbol
#define arginfo_class_ion_Reader_readString arginfo_class_ion_Symbol___toString
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Reader_readStringPart, 0, 1, _IS_BOOL, 0)
ZEND_ARG_INFO(1, string)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, length, IS_LONG, 0, "0x1000")
ZEND_END_ARG_INFO()
#define arginfo_class_ion_Reader_readLob arginfo_class_ion_Symbol___toString
#define arginfo_class_ion_Reader_readLobPart arginfo_class_ion_Reader_readStringPart
#define arginfo_class_ion_Reader_getPosition arginfo_class_ion_Catalog_count
#define arginfo_class_ion_Reader_getDepth arginfo_class_ion_Catalog_count
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Reader_seek, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, offset, IS_LONG, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, length, IS_LONG, 0, "-1")
ZEND_END_ARG_INFO()
#define arginfo_class_ion_Reader_getValueOffset arginfo_class_ion_Catalog_count
#define arginfo_class_ion_Reader_getValueLength arginfo_class_ion_Catalog_count
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Writer_writeNull, 0, 0, IS_VOID, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Writer_writeTypedNull, 0, 1, IS_VOID, 0)
ZEND_ARG_OBJ_INFO(0, type, ion\\Type, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Writer_writeBool, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, value, _IS_BOOL, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Writer_writeInt, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_MASK(0, value, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Writer_writeFloat, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, value, IS_DOUBLE, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Writer_writeDecimal, 0, 1, IS_VOID, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, value, ion\\Decimal, MAY_BE_STRING, NULL)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Writer_writeTimestamp, 0, 1, IS_VOID, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, value, ion\\Timestamp, MAY_BE_STRING, NULL)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Writer_writeSymbol, 0, 1, IS_VOID, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, value, ion\\Symbol, MAY_BE_STRING, NULL)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Writer_writeString, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, value, IS_STRING, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_ion_Writer_writeCLob arginfo_class_ion_Writer_writeString
#define arginfo_class_ion_Writer_writeBLob arginfo_class_ion_Writer_writeString
#define arginfo_class_ion_Writer_startLob arginfo_class_ion_Writer_writeTypedNull
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Writer_appendLob, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, data, IS_STRING, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_ion_Writer_finishLob arginfo_class_ion_Writer_writeNull
#define arginfo_class_ion_Writer_startContainer arginfo_class_ion_Writer_writeTypedNull
#define arginfo_class_ion_Writer_finishContainer arginfo_class_ion_Writer_writeNull
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Writer_writeFieldName, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, name, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Writer_writeAnnotation, 0, 0, IS_VOID, 0)
ZEND_ARG_VARIADIC_OBJ_TYPE_MASK(0, annotation, ion\\Symbol, MAY_BE_STRING, NULL)
ZEND_END_ARG_INFO()
#define arginfo_class_ion_Writer_getDepth arginfo_class_ion_Catalog_count
#define arginfo_class_ion_Writer_flush arginfo_class_ion_Catalog_count
#define arginfo_class_ion_Writer_finish arginfo_class_ion_Catalog_count
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_ion_Symbol_ImportLocation___construct, 0, 0, 2)
ZEND_ARG_TYPE_INFO(0, name, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, location, IS_LONG, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_ion_Symbol_Enum_toSymbol arginfo_class_ion_Reader_getFieldNameSymbol
#define arginfo_class_ion_Symbol_Enum_toSID arginfo_class_ion_Catalog_count
#define arginfo_class_ion_Symbol_Enum_toString arginfo_class_ion_Symbol___toString
#define arginfo_class_ion_Symbol_Table_getMaxId arginfo_class_ion_Catalog_count
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Symbol_Table_add, 0, 1, IS_LONG, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, symbol, ion\\Symbol, MAY_BE_STRING, NULL)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_ion_Symbol_Table_find, 0, 1, ion\\Symbol, 1)
ZEND_ARG_TYPE_MASK(0, id, MAY_BE_STRING|MAY_BE_LONG, NULL)
ZEND_END_ARG_INFO()
#define arginfo_class_ion_Symbol_Table_findLocal arginfo_class_ion_Symbol_Table_find
#define arginfo_class_ion_Symbol_System_toSymbol arginfo_class_ion_Reader_getFieldNameSymbol
#define arginfo_class_ion_Symbol_System_toSID arginfo_class_ion_Catalog_count
#define arginfo_class_ion_Symbol_System_toString arginfo_class_ion_Symbol___toString
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_ion_Symbol_System_asTable, 0, 0, ion\\Symbol\\Table\\Shared, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_ion_Symbol_PHP_toSymbol arginfo_class_ion_Reader_getFieldNameSymbol
#define arginfo_class_ion_Symbol_PHP_toSID arginfo_class_ion_Catalog_count
#define arginfo_class_ion_Symbol_PHP_toString arginfo_class_ion_Symbol___toString
#define arginfo_class_ion_Symbol_PHP_asTable arginfo_class_ion_Symbol_System_asTable
#define arginfo_class_ion_Symbol_Table_Local___construct arginfo_class_ion_Catalog___construct
#define arginfo_class_ion_Symbol_Table_Local_import arginfo_class_ion_Catalog_add
#define arginfo_class_ion_Symbol_Table_Local_getMaxId arginfo_class_ion_Catalog_count
#define arginfo_class_ion_Symbol_Table_Local_add arginfo_class_ion_Symbol_Table_add
#define arginfo_class_ion_Symbol_Table_Local_find arginfo_class_ion_Symbol_Table_find
#define arginfo_class_ion_Symbol_Table_Local_findLocal arginfo_class_ion_Symbol_Table_find
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_ion_Symbol_Table_Shared___construct, 0, 0, 1)
ZEND_ARG_TYPE_INFO(0, name, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, version, IS_LONG, 0, "1")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, symbols, IS_ARRAY, 1, "null")
ZEND_END_ARG_INFO()
#define arginfo_class_ion_Symbol_Table_Shared_getMaxId arginfo_class_ion_Catalog_count
#define arginfo_class_ion_Symbol_Table_Shared_add arginfo_class_ion_Symbol_Table_add
#define arginfo_class_ion_Symbol_Table_Shared_find arginfo_class_ion_Symbol_Table_find
#define arginfo_class_ion_Symbol_Table_Shared_findLocal arginfo_class_ion_Symbol_Table_find
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_ion_Decimal_Context___construct, 0, 0, 5)
ZEND_ARG_TYPE_INFO(0, digits, IS_LONG, 0)
ZEND_ARG_TYPE_INFO(0, eMax, IS_LONG, 0)
ZEND_ARG_TYPE_INFO(0, eMin, IS_LONG, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, round, ion\\Decimal\\Context\\Rounding, MAY_BE_LONG, NULL)
ZEND_ARG_TYPE_INFO(0, clamp, _IS_BOOL, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_ion_Decimal_Context_Dec32, 0, 0, ion\\Decimal\\Context, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_ion_Decimal_Context_Dec64 arginfo_class_ion_Decimal_Context_Dec32
#define arginfo_class_ion_Decimal_Context_Dec128 arginfo_class_ion_Decimal_Context_Dec32
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_ion_Decimal_Context_DecMax, 0, 0, ion\\Decimal\\Context, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, round, ion\\Decimal\\Context\\Rounding, MAY_BE_LONG, "ion\\Decimal\\Context\\Rounding::HalfEven")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_ion_Reader_Reader___construct, 0, 0, 1)
ZEND_ARG_INFO(0, data)
ZEND_ARG_OBJ_INFO_WITH_DEFAULT_VALUE(0, catalog, ion\\Catalog, 1, "null")
ZEND_ARG_OBJ_INFO_WITH_DEFAULT_VALUE(0, decimalContext, ion\\Decimal\\Context, 1, "null")
ZEND_ARG_OBJ_INFO_WITH_DEFAULT_VALUE(0, onContextChange, Closure, 1, "null")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, returnSystemValues, _IS_BOOL, 0, "false")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, maxContainerDepth, IS_LONG, 0, "10")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, maxAnnotations, IS_LONG, 0, "10")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, annotationBufferSize, IS_LONG, 0, "0x4000")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, tempBufferSize, IS_LONG, 0, "0x4000")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, skipCharacterValidation, _IS_BOOL, 0, "false")
ZEND_END_ARG_INFO()
#define arginfo_class_ion_Reader_Reader_hasChildren arginfo_class_ion_Decimal_isInt
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_ion_Reader_Reader_getChildren, 0, 0, ion\\Reader, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_ion_Reader_Reader_rewind arginfo_class_ion_Writer_writeNull
#define arginfo_class_ion_Reader_Reader_next arginfo_class_ion_Writer_writeNull
#define arginfo_class_ion_Reader_Reader_valid arginfo_class_ion_Decimal_isInt
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Reader_Reader_key, 0, 0, IS_MIXED, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_ion_Reader_Reader_current arginfo_class_ion_Reader_Reader_key
#define arginfo_class_ion_Reader_Reader_getType arginfo_class_ion_Reader_getType
#define arginfo_class_ion_Reader_Reader_hasAnnotations arginfo_class_ion_Decimal_isInt
#define arginfo_class_ion_Reader_Reader_hasAnnotation arginfo_class_ion_Reader_hasAnnotation
#define arginfo_class_ion_Reader_Reader_isNull arginfo_class_ion_Decimal_isInt
#define arginfo_class_ion_Reader_Reader_isInStruct arginfo_class_ion_Decimal_isInt
#define arginfo_class_ion_Reader_Reader_getFieldName arginfo_class_ion_Symbol___toString
#define arginfo_class_ion_Reader_Reader_getFieldNameSymbol arginfo_class_ion_Reader_getFieldNameSymbol
#define arginfo_class_ion_Reader_Reader_getAnnotations arginfo_class_ion_Reader_getAnnotations
#define arginfo_class_ion_Reader_Reader_getAnnotationSymbols arginfo_class_ion_Reader_getAnnotations
#define arginfo_class_ion_Reader_Reader_countAnnotations arginfo_class_ion_Catalog_count
#define arginfo_class_ion_Reader_Reader_getAnnotation arginfo_class_ion_Reader_getAnnotation
#define arginfo_class_ion_Reader_Reader_getAnnotationSymbol arginfo_class_ion_Reader_getAnnotationSymbol
#define arginfo_class_ion_Reader_Reader_readNull arginfo_class_ion_Reader_getType
#define arginfo_class_ion_Reader_Reader_readBool arginfo_class_ion_Decimal_isInt
#define arginfo_class_ion_Reader_Reader_readInt arginfo_class_ion_Reader_readInt
#define arginfo_class_ion_Reader_Reader_readFloat arginfo_class_ion_Reader_readFloat
#define arginfo_class_ion_Reader_Reader_readDecimal arginfo_class_ion_Reader_readDecimal
#define arginfo_class_ion_Reader_Reader_readTimestamp arginfo_class_ion_Reader_readTimestamp
#define arginfo_class_ion_Reader_Reader_readSymbol arginfo_class_ion_Reader_getFieldNameSymbol
#define arginfo_class_ion_Reader_Reader_readString arginfo_class_ion_Symbol___toString
#define arginfo_class_ion_Reader_Reader_readStringPart arginfo_class_ion_Reader_readStringPart
#define arginfo_class_ion_Reader_Reader_readLob arginfo_class_ion_Symbol___toString
#define arginfo_class_ion_Reader_Reader_readLobPart arginfo_class_ion_Reader_readStringPart
#define arginfo_class_ion_Reader_Reader_getPosition arginfo_class_ion_Catalog_count
#define arginfo_class_ion_Reader_Reader_getDepth arginfo_class_ion_Catalog_count
#define arginfo_class_ion_Reader_Reader_seek arginfo_class_ion_Reader_seek
#define arginfo_class_ion_Reader_Reader_getValueOffset arginfo_class_ion_Catalog_count
#define arginfo_class_ion_Reader_Reader_getValueLength arginfo_class_ion_Catalog_count
#define arginfo_class_ion_Reader_Buffer_getBuffer arginfo_class_ion_Symbol___toString
#define arginfo_class_ion_Reader_Stream_getStream arginfo_class_ion_Catalog___construct
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Reader_Stream_resetStream, 0, 1, IS_VOID, 0)
ZEND_ARG_INFO(0, stream)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_ion_Reader_Stream_resetStreamWithLength, 0, 2, IS_VOID, 0)
ZEND_ARG_INFO(0, stream)
ZEND_ARG_TYPE_INFO(0, length, IS_LONG, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_ion_Reader_Buffer_Reader_getBuffer arginfo_class_ion_Symbol___toString
#define arginfo_class_ion_Reader_Stream_Reader_getStream arginfo_class_ion_Catalog___construct
#define arginfo_class_ion_Reader_Stream_Reader_resetStream arginfo_class_ion_Reader_Stream_resetStream
#define arginfo_class_ion_Reader_Stream_Reader_resetStreamWithLength arginfo_class_ion_Reader_Stream_resetStreamWithLength
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_ion_Writer_Writer___construct, 0, 0, 0)
ZEND_ARG_OBJ_INFO_WITH_DEFAULT_VALUE(0, catalog, ion\\Catalog, 1, "null")
ZEND_ARG_OBJ_INFO_WITH_DEFAULT_VALUE(0, decimalContext, ion\\Decimal\\Context, 1, "null")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, outputBinary, _IS_BOOL, 0, "false")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, compactFloats, _IS_BOOL, 0, "false")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, escapeNonAscii, _IS_BOOL, 0, "false")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, prettyPrint, _IS_BOOL, 0, "false")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, indentTabs, _IS_BOOL, 0, "true")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, indentSize, IS_LONG, 0, "2")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, flushEveryValue, _IS_BOOL, 0, "false")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, maxContainerDepth, IS_LONG, 0, "10")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, maxAnnotations, IS_LONG, 0, "10")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, tempBufferSize, IS_LONG, 0, "0x4000")
ZEND_END_ARG_INFO()
#define arginfo_class_ion_Writer_Writer_writeNull arginfo_class_ion_Writer_writeNull
#define arginfo_class_ion_Writer_Writer_writeTypedNull arginfo_class_ion_Writer_writeTypedNull
#define arginfo_class_ion_Writer_Writer_writeBool arginfo_class_ion_Writer_writeBool
#define arginfo_class_ion_Writer_Writer_writeInt arginfo_class_ion_Writer_writeInt
#define arginfo_class_ion_Writer_Writer_writeFloat arginfo_class_ion_Writer_writeFloat
#define arginfo_class_ion_Writer_Writer_writeDecimal arginfo_class_ion_Writer_writeDecimal
#define arginfo_class_ion_Writer_Writer_writeTimestamp arginfo_class_ion_Writer_writeTimestamp
#define arginfo_class_ion_Writer_Writer_writeSymbol arginfo_class_ion_Writer_writeSymbol
#define arginfo_class_ion_Writer_Writer_writeString arginfo_class_ion_Writer_writeString
#define arginfo_class_ion_Writer_Writer_writeCLob arginfo_class_ion_Writer_writeString
#define arginfo_class_ion_Writer_Writer_writeBLob arginfo_class_ion_Writer_writeString
#define arginfo_class_ion_Writer_Writer_startLob arginfo_class_ion_Writer_writeTypedNull
#define arginfo_class_ion_Writer_Writer_appendLob arginfo_class_ion_Writer_appendLob
#define arginfo_class_ion_Writer_Writer_finishLob arginfo_class_ion_Writer_writeNull
#define arginfo_class_ion_Writer_Writer_startContainer arginfo_class_ion_Writer_writeTypedNull
#define arginfo_class_ion_Writer_Writer_finishContainer arginfo_class_ion_Writer_writeNull
#define arginfo_class_ion_Writer_Writer_writeFieldName arginfo_class_ion_Writer_writeFieldName
#define arginfo_class_ion_Writer_Writer_writeAnnotation arginfo_class_ion_Writer_writeAnnotation
#define arginfo_class_ion_Writer_Writer_getDepth arginfo_class_ion_Catalog_count
#define arginfo_class_ion_Writer_Writer_flush arginfo_class_ion_Catalog_count
#define arginfo_class_ion_Writer_Writer_finish arginfo_class_ion_Catalog_count
#define arginfo_class_ion_Writer_Buffer_getBuffer arginfo_class_ion_Symbol___toString
#define arginfo_class_ion_Writer_Buffer_resetBuffer arginfo_class_ion_Writer_writeNull
#define arginfo_class_ion_Writer_Stream_getStream arginfo_class_ion_Catalog___construct
#define arginfo_class_ion_Writer_Buffer_Writer_getBuffer arginfo_class_ion_Symbol___toString
#define arginfo_class_ion_Writer_Buffer_Writer_resetBuffer arginfo_class_ion_Writer_writeNull
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_ion_Writer_Stream_Writer___construct, 0, 0, 1)
ZEND_ARG_INFO(0, stream)
ZEND_ARG_OBJ_INFO_WITH_DEFAULT_VALUE(0, catalog, ion\\Catalog, 1, "null")
ZEND_ARG_OBJ_INFO_WITH_DEFAULT_VALUE(0, decimalContext, ion\\Decimal\\Context, 1, "null")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, outputBinary, _IS_BOOL, 0, "false")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, compactFloats, _IS_BOOL, 0, "false")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, escapeNonAscii, _IS_BOOL, 0, "false")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, prettyPrint, _IS_BOOL, 0, "false")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, indentTabs, _IS_BOOL, 0, "true")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, indentSize, IS_LONG, 0, "2")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, flushEveryValue, _IS_BOOL, 0, "false")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, maxContainerDepth, IS_LONG, 0, "10")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, maxAnnotations, IS_LONG, 0, "10")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, tempBufferSize, IS_LONG, 0, "0x4000")
ZEND_END_ARG_INFO()
#define arginfo_class_ion_Writer_Stream_Writer_getStream arginfo_class_ion_Catalog___construct
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_ion_Serializer_Serializer___construct, 0, 0, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, multiSequence, _IS_BOOL, 0, "false")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, callMagicSerialize, _IS_BOOL, 0, "true")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, callCustomSerialize, IS_STRING, 1, "null")
ZEND_END_ARG_INFO()
#define arginfo_class_ion_Serializer_Serializer_serialize arginfo_class_ion_Serializer_serialize
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_ion_Unserializer_Unserializer___construct, 0, 0, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, multiSequence, _IS_BOOL, 0, "false")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, callMagicUnserialize, _IS_BOOL, 0, "true")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, callCustomUnserialize, IS_STRING, 1, "null")
ZEND_END_ARG_INFO()
#define arginfo_class_ion_Unserializer_Unserializer_unserialize arginfo_class_ion_Unserializer_unserialize
static ZEND_FUNCTION(ion_serialize);
static ZEND_FUNCTION(ion_unserialize);
static ZEND_METHOD(ion_Symbol, __construct);
static ZEND_METHOD(ion_Symbol, equals);
static ZEND_METHOD(ion_Symbol, __toString);
static ZEND_METHOD(ion_Catalog, __construct);
static ZEND_METHOD(ion_Catalog, count);
static ZEND_METHOD(ion_Catalog, add);
static ZEND_METHOD(ion_Catalog, remove);
static ZEND_METHOD(ion_Catalog, find);
static ZEND_METHOD(ion_Catalog, findBest);
static ZEND_METHOD(ion_LOB, __construct);
static ZEND_METHOD(ion_Decimal, __construct);
static ZEND_METHOD(ion_Decimal, equals);
static ZEND_METHOD(ion_Decimal, isInt);
static ZEND_METHOD(ion_Decimal, __toString);
static ZEND_METHOD(ion_Decimal, toInt);
static ZEND_METHOD(ion_Timestamp, __construct);
static ZEND_METHOD(ion_Timestamp, __toString);
static ZEND_METHOD(ion_Symbol_ImportLocation, __construct);
static ZEND_METHOD(ion_Symbol_System, asTable);
static ZEND_METHOD(ion_Symbol_PHP, asTable);
static ZEND_METHOD(ion_Symbol_Table_Local, __construct);
static ZEND_METHOD(ion_Symbol_Table_Local, import);
static ZEND_METHOD(ion_Symbol_Table_Shared, __construct);
static ZEND_METHOD(ion_Decimal_Context, __construct);
static ZEND_METHOD(ion_Decimal_Context, Dec32);
static ZEND_METHOD(ion_Decimal_Context, Dec64);
static ZEND_METHOD(ion_Decimal_Context, Dec128);
static ZEND_METHOD(ion_Decimal_Context, DecMax);
static ZEND_METHOD(ion_Reader_Reader, __construct);
static ZEND_METHOD(ion_Reader_Reader, hasChildren);
static ZEND_METHOD(ion_Reader_Reader, getChildren);
static ZEND_METHOD(ion_Reader_Reader, rewind);
static ZEND_METHOD(ion_Reader_Reader, next);
static ZEND_METHOD(ion_Reader_Reader, valid);
static ZEND_METHOD(ion_Reader_Reader, key);
static ZEND_METHOD(ion_Reader_Reader, current);
static ZEND_METHOD(ion_Reader_Reader, getType);
static ZEND_METHOD(ion_Reader_Reader, hasAnnotations);
static ZEND_METHOD(ion_Reader_Reader, hasAnnotation);
static ZEND_METHOD(ion_Reader_Reader, isNull);
static ZEND_METHOD(ion_Reader_Reader, isInStruct);
static ZEND_METHOD(ion_Reader_Reader, getFieldName);
static ZEND_METHOD(ion_Reader_Reader, getFieldNameSymbol);
static ZEND_METHOD(ion_Reader_Reader, getAnnotations);
static ZEND_METHOD(ion_Reader_Reader, getAnnotationSymbols);
static ZEND_METHOD(ion_Reader_Reader, countAnnotations);
static ZEND_METHOD(ion_Reader_Reader, getAnnotation);
static ZEND_METHOD(ion_Reader_Reader, getAnnotationSymbol);
static ZEND_METHOD(ion_Reader_Reader, readNull);
static ZEND_METHOD(ion_Reader_Reader, readBool);
static ZEND_METHOD(ion_Reader_Reader, readInt);
static ZEND_METHOD(ion_Reader_Reader, readFloat);
static ZEND_METHOD(ion_Reader_Reader, readDecimal);
static ZEND_METHOD(ion_Reader_Reader, readTimestamp);
static ZEND_METHOD(ion_Reader_Reader, readSymbol);
static ZEND_METHOD(ion_Reader_Reader, readString);
static ZEND_METHOD(ion_Reader_Reader, readStringPart);
static ZEND_METHOD(ion_Reader_Reader, readLob);
static ZEND_METHOD(ion_Reader_Reader, readLobPart);
static ZEND_METHOD(ion_Reader_Reader, getPosition);
static ZEND_METHOD(ion_Reader_Reader, getDepth);
static ZEND_METHOD(ion_Reader_Reader, seek);
static ZEND_METHOD(ion_Reader_Reader, getValueOffset);
static ZEND_METHOD(ion_Reader_Reader, getValueLength);
static ZEND_METHOD(ion_Reader_Buffer_Reader, getBuffer);
static ZEND_METHOD(ion_Reader_Stream_Reader, getStream);
static ZEND_METHOD(ion_Reader_Stream_Reader, resetStream);
static ZEND_METHOD(ion_Reader_Stream_Reader, resetStreamWithLength);
static ZEND_METHOD(ion_Writer_Writer, __construct);
static ZEND_METHOD(ion_Writer_Writer, writeNull);
static ZEND_METHOD(ion_Writer_Writer, writeTypedNull);
static ZEND_METHOD(ion_Writer_Writer, writeBool);
static ZEND_METHOD(ion_Writer_Writer, writeInt);
static ZEND_METHOD(ion_Writer_Writer, writeFloat);
static ZEND_METHOD(ion_Writer_Writer, writeDecimal);
static ZEND_METHOD(ion_Writer_Writer, writeTimestamp);
static ZEND_METHOD(ion_Writer_Writer, writeSymbol);
static ZEND_METHOD(ion_Writer_Writer, writeString);
static ZEND_METHOD(ion_Writer_Writer, writeCLob);
static ZEND_METHOD(ion_Writer_Writer, writeBLob);
static ZEND_METHOD(ion_Writer_Writer, startLob);
static ZEND_METHOD(ion_Writer_Writer, appendLob);
static ZEND_METHOD(ion_Writer_Writer, finishLob);
static ZEND_METHOD(ion_Writer_Writer, startContainer);
static ZEND_METHOD(ion_Writer_Writer, finishContainer);
static ZEND_METHOD(ion_Writer_Writer, writeFieldName);
static ZEND_METHOD(ion_Writer_Writer, writeAnnotation);
static ZEND_METHOD(ion_Writer_Writer, getDepth);
static ZEND_METHOD(ion_Writer_Writer, flush);
static ZEND_METHOD(ion_Writer_Writer, finish);
static ZEND_METHOD(ion_Writer_Buffer_Writer, getBuffer);
static ZEND_METHOD(ion_Writer_Buffer_Writer, resetBuffer);
static ZEND_METHOD(ion_Writer_Stream_Writer, __construct);
static ZEND_METHOD(ion_Writer_Stream_Writer, getStream);
static ZEND_METHOD(ion_Serializer_Serializer, __construct);
static ZEND_METHOD(ion_Serializer_Serializer, serialize);
static ZEND_METHOD(ion_Unserializer_Unserializer, __construct);
static ZEND_METHOD(ion_Unserializer_Unserializer, unserialize);
static const zend_function_entry ext_functions[] = {
ZEND_NS_RAW_FENTRY("ion", "serialize", ZEND_FN(ion_serialize), arginfo_ion_serialize, 0)
ZEND_NS_RAW_FENTRY("ion", "unserialize", ZEND_FN(ion_unserialize), arginfo_ion_unserialize, 0)
ZEND_FE_END
};
static const zend_function_entry class_ion_Serializer_methods[] = {
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Serializer, serialize, arginfo_class_ion_Serializer_serialize, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_FE_END
};
static const zend_function_entry class_ion_Unserializer_methods[] = {
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Unserializer, unserialize, arginfo_class_ion_Unserializer_unserialize, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_FE_END
};
static const zend_function_entry class_ion_Exception_methods[] = {
ZEND_FE_END
};
static const zend_function_entry class_ion_Type_methods[] = {
ZEND_FE_END
};
static const zend_function_entry class_ion_Symbol_methods[] = {
ZEND_ME(ion_Symbol, __construct, arginfo_class_ion_Symbol___construct, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Symbol, equals, arginfo_class_ion_Symbol_equals, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Symbol, __toString, arginfo_class_ion_Symbol___toString, ZEND_ACC_PUBLIC)
ZEND_MALIAS(ion_Symbol, toString, __toString, arginfo_class_ion_Symbol_toString, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
static const zend_function_entry class_ion_Catalog_methods[] = {
ZEND_ME(ion_Catalog, __construct, arginfo_class_ion_Catalog___construct, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Catalog, count, arginfo_class_ion_Catalog_count, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Catalog, add, arginfo_class_ion_Catalog_add, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Catalog, remove, arginfo_class_ion_Catalog_remove, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Catalog, find, arginfo_class_ion_Catalog_find, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Catalog, findBest, arginfo_class_ion_Catalog_findBest, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
static const zend_function_entry class_ion_LOB_methods[] = {
ZEND_ME(ion_LOB, __construct, arginfo_class_ion_LOB___construct, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
static const zend_function_entry class_ion_Decimal_methods[] = {
ZEND_ME(ion_Decimal, __construct, arginfo_class_ion_Decimal___construct, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Decimal, equals, arginfo_class_ion_Decimal_equals, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Decimal, isInt, arginfo_class_ion_Decimal_isInt, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Decimal, __toString, arginfo_class_ion_Decimal___toString, ZEND_ACC_PUBLIC)
ZEND_MALIAS(ion_Decimal, toString, __toString, arginfo_class_ion_Decimal_toString, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Decimal, toInt, arginfo_class_ion_Decimal_toInt, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
static const zend_function_entry class_ion_Timestamp_methods[] = {
ZEND_ME(ion_Timestamp, __construct, arginfo_class_ion_Timestamp___construct, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Timestamp, __toString, arginfo_class_ion_Timestamp___toString, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
static const zend_function_entry class_ion_Reader_methods[] = {
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader, getType, arginfo_class_ion_Reader_getType, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader, hasAnnotations, arginfo_class_ion_Reader_hasAnnotations, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader, hasAnnotation, arginfo_class_ion_Reader_hasAnnotation, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader, isNull, arginfo_class_ion_Reader_isNull, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader, isInStruct, arginfo_class_ion_Reader_isInStruct, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader, getFieldName, arginfo_class_ion_Reader_getFieldName, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader, getFieldNameSymbol, arginfo_class_ion_Reader_getFieldNameSymbol, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader, getAnnotations, arginfo_class_ion_Reader_getAnnotations, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader, getAnnotationSymbols, arginfo_class_ion_Reader_getAnnotationSymbols, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader, countAnnotations, arginfo_class_ion_Reader_countAnnotations, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader, getAnnotation, arginfo_class_ion_Reader_getAnnotation, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader, getAnnotationSymbol, arginfo_class_ion_Reader_getAnnotationSymbol, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader, readNull, arginfo_class_ion_Reader_readNull, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader, readBool, arginfo_class_ion_Reader_readBool, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader, readInt, arginfo_class_ion_Reader_readInt, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader, readFloat, arginfo_class_ion_Reader_readFloat, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader, readDecimal, arginfo_class_ion_Reader_readDecimal, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader, readTimestamp, arginfo_class_ion_Reader_readTimestamp, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader, readSymbol, arginfo_class_ion_Reader_readSymbol, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader, readString, arginfo_class_ion_Reader_readString, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader, readStringPart, arginfo_class_ion_Reader_readStringPart, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader, readLob, arginfo_class_ion_Reader_readLob, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader, readLobPart, arginfo_class_ion_Reader_readLobPart, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader, getPosition, arginfo_class_ion_Reader_getPosition, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader, getDepth, arginfo_class_ion_Reader_getDepth, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader, seek, arginfo_class_ion_Reader_seek, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader, getValueOffset, arginfo_class_ion_Reader_getValueOffset, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader, getValueLength, arginfo_class_ion_Reader_getValueLength, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_FE_END
};
static const zend_function_entry class_ion_Writer_methods[] = {
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Writer, writeNull, arginfo_class_ion_Writer_writeNull, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Writer, writeTypedNull, arginfo_class_ion_Writer_writeTypedNull, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Writer, writeBool, arginfo_class_ion_Writer_writeBool, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Writer, writeInt, arginfo_class_ion_Writer_writeInt, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Writer, writeFloat, arginfo_class_ion_Writer_writeFloat, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Writer, writeDecimal, arginfo_class_ion_Writer_writeDecimal, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Writer, writeTimestamp, arginfo_class_ion_Writer_writeTimestamp, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Writer, writeSymbol, arginfo_class_ion_Writer_writeSymbol, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Writer, writeString, arginfo_class_ion_Writer_writeString, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Writer, writeCLob, arginfo_class_ion_Writer_writeCLob, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Writer, writeBLob, arginfo_class_ion_Writer_writeBLob, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Writer, startLob, arginfo_class_ion_Writer_startLob, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Writer, appendLob, arginfo_class_ion_Writer_appendLob, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Writer, finishLob, arginfo_class_ion_Writer_finishLob, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Writer, startContainer, arginfo_class_ion_Writer_startContainer, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Writer, finishContainer, arginfo_class_ion_Writer_finishContainer, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Writer, writeFieldName, arginfo_class_ion_Writer_writeFieldName, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Writer, writeAnnotation, arginfo_class_ion_Writer_writeAnnotation, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Writer, getDepth, arginfo_class_ion_Writer_getDepth, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Writer, flush, arginfo_class_ion_Writer_flush, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Writer, finish, arginfo_class_ion_Writer_finish, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_FE_END
};
static const zend_function_entry class_ion_Symbol_ImportLocation_methods[] = {
ZEND_ME(ion_Symbol_ImportLocation, __construct, arginfo_class_ion_Symbol_ImportLocation___construct, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
static const zend_function_entry class_ion_Symbol_Enum_methods[] = {
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Symbol_Enum, toSymbol, arginfo_class_ion_Symbol_Enum_toSymbol, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Symbol_Enum, toSID, arginfo_class_ion_Symbol_Enum_toSID, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Symbol_Enum, toString, arginfo_class_ion_Symbol_Enum_toString, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_FE_END
};
static const zend_function_entry class_ion_Symbol_Table_methods[] = {
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Symbol_Table, getMaxId, arginfo_class_ion_Symbol_Table_getMaxId, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Symbol_Table, add, arginfo_class_ion_Symbol_Table_add, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Symbol_Table, find, arginfo_class_ion_Symbol_Table_find, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Symbol_Table, findLocal, arginfo_class_ion_Symbol_Table_findLocal, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_FE_END
};
static const zend_function_entry class_ion_Symbol_System_methods[] = {
ZEND_MALIAS(ion_Symbol_Enum, toSymbol, toSymbol, arginfo_class_ion_Symbol_System_toSymbol, ZEND_ACC_PUBLIC)
ZEND_MALIAS(ion_Symbol_Enum, toSID, toSID, arginfo_class_ion_Symbol_System_toSID, ZEND_ACC_PUBLIC)
ZEND_MALIAS(ion_Symbol_Enum, toString, toString, arginfo_class_ion_Symbol_System_toString, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Symbol_System, asTable, arginfo_class_ion_Symbol_System_asTable, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
ZEND_FE_END
};
static const zend_function_entry class_ion_Symbol_PHP_methods[] = {
ZEND_MALIAS(ion_Symbol_Enum, toSymbol, toSymbol, arginfo_class_ion_Symbol_PHP_toSymbol, ZEND_ACC_PUBLIC)
ZEND_MALIAS(ion_Symbol_Enum, toSID, toSID, arginfo_class_ion_Symbol_PHP_toSID, ZEND_ACC_PUBLIC)
ZEND_MALIAS(ion_Symbol_Enum, toString, toString, arginfo_class_ion_Symbol_PHP_toString, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Symbol_PHP, asTable, arginfo_class_ion_Symbol_PHP_asTable, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
ZEND_FE_END
};
static const zend_function_entry class_ion_Symbol_Table_Local_methods[] = {
ZEND_ME(ion_Symbol_Table_Local, __construct, arginfo_class_ion_Symbol_Table_Local___construct, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Symbol_Table_Local, import, arginfo_class_ion_Symbol_Table_Local_import, ZEND_ACC_PUBLIC)
ZEND_MALIAS(ion_Symbol_Table, getMaxId, getMaxId, arginfo_class_ion_Symbol_Table_Local_getMaxId, ZEND_ACC_PUBLIC)
ZEND_MALIAS(ion_Symbol_Table, add, add, arginfo_class_ion_Symbol_Table_Local_add, ZEND_ACC_PUBLIC)
ZEND_MALIAS(ion_Symbol_Table, find, find, arginfo_class_ion_Symbol_Table_Local_find, ZEND_ACC_PUBLIC)
ZEND_MALIAS(ion_Symbol_Table, findLocal, findLocal, arginfo_class_ion_Symbol_Table_Local_findLocal, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
static const zend_function_entry class_ion_Symbol_Table_Shared_methods[] = {
ZEND_ME(ion_Symbol_Table_Shared, __construct, arginfo_class_ion_Symbol_Table_Shared___construct, ZEND_ACC_PUBLIC)
ZEND_MALIAS(ion_Symbol_Table, getMaxId, getMaxId, arginfo_class_ion_Symbol_Table_Shared_getMaxId, ZEND_ACC_PUBLIC)
ZEND_MALIAS(ion_Symbol_Table, add, add, arginfo_class_ion_Symbol_Table_Shared_add, ZEND_ACC_PUBLIC)
ZEND_MALIAS(ion_Symbol_Table, find, find, arginfo_class_ion_Symbol_Table_Shared_find, ZEND_ACC_PUBLIC)
ZEND_MALIAS(ion_Symbol_Table, findLocal, findLocal, arginfo_class_ion_Symbol_Table_Shared_findLocal, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
static const zend_function_entry class_ion_Decimal_Context_methods[] = {
ZEND_ME(ion_Decimal_Context, __construct, arginfo_class_ion_Decimal_Context___construct, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Decimal_Context, Dec32, arginfo_class_ion_Decimal_Context_Dec32, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
ZEND_ME(ion_Decimal_Context, Dec64, arginfo_class_ion_Decimal_Context_Dec64, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
ZEND_ME(ion_Decimal_Context, Dec128, arginfo_class_ion_Decimal_Context_Dec128, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
ZEND_ME(ion_Decimal_Context, DecMax, arginfo_class_ion_Decimal_Context_DecMax, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
ZEND_FE_END
};
static const zend_function_entry class_ion_Decimal_Context_Rounding_methods[] = {
ZEND_FE_END
};
static const zend_function_entry class_ion_Timestamp_Precision_methods[] = {
ZEND_FE_END
};
static const zend_function_entry class_ion_Timestamp_Format_methods[] = {
ZEND_FE_END
};
static const zend_function_entry class_ion_Reader_Reader_methods[] = {
ZEND_ME(ion_Reader_Reader, __construct, arginfo_class_ion_Reader_Reader___construct, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, hasChildren, arginfo_class_ion_Reader_Reader_hasChildren, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, getChildren, arginfo_class_ion_Reader_Reader_getChildren, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, rewind, arginfo_class_ion_Reader_Reader_rewind, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, next, arginfo_class_ion_Reader_Reader_next, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, valid, arginfo_class_ion_Reader_Reader_valid, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, key, arginfo_class_ion_Reader_Reader_key, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, current, arginfo_class_ion_Reader_Reader_current, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, getType, arginfo_class_ion_Reader_Reader_getType, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, hasAnnotations, arginfo_class_ion_Reader_Reader_hasAnnotations, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, hasAnnotation, arginfo_class_ion_Reader_Reader_hasAnnotation, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, isNull, arginfo_class_ion_Reader_Reader_isNull, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, isInStruct, arginfo_class_ion_Reader_Reader_isInStruct, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, getFieldName, arginfo_class_ion_Reader_Reader_getFieldName, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, getFieldNameSymbol, arginfo_class_ion_Reader_Reader_getFieldNameSymbol, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, getAnnotations, arginfo_class_ion_Reader_Reader_getAnnotations, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, getAnnotationSymbols, arginfo_class_ion_Reader_Reader_getAnnotationSymbols, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, countAnnotations, arginfo_class_ion_Reader_Reader_countAnnotations, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, getAnnotation, arginfo_class_ion_Reader_Reader_getAnnotation, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, getAnnotationSymbol, arginfo_class_ion_Reader_Reader_getAnnotationSymbol, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, readNull, arginfo_class_ion_Reader_Reader_readNull, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, readBool, arginfo_class_ion_Reader_Reader_readBool, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, readInt, arginfo_class_ion_Reader_Reader_readInt, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, readFloat, arginfo_class_ion_Reader_Reader_readFloat, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, readDecimal, arginfo_class_ion_Reader_Reader_readDecimal, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, readTimestamp, arginfo_class_ion_Reader_Reader_readTimestamp, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, readSymbol, arginfo_class_ion_Reader_Reader_readSymbol, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, readString, arginfo_class_ion_Reader_Reader_readString, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, readStringPart, arginfo_class_ion_Reader_Reader_readStringPart, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, readLob, arginfo_class_ion_Reader_Reader_readLob, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, readLobPart, arginfo_class_ion_Reader_Reader_readLobPart, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, getPosition, arginfo_class_ion_Reader_Reader_getPosition, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, getDepth, arginfo_class_ion_Reader_Reader_getDepth, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, seek, arginfo_class_ion_Reader_Reader_seek, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, getValueOffset, arginfo_class_ion_Reader_Reader_getValueOffset, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Reader, getValueLength, arginfo_class_ion_Reader_Reader_getValueLength, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
static const zend_function_entry class_ion_Reader_Buffer_methods[] = {
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader_Buffer, getBuffer, arginfo_class_ion_Reader_Buffer_getBuffer, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_FE_END
};
static const zend_function_entry class_ion_Reader_Stream_methods[] = {
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader_Stream, getStream, arginfo_class_ion_Reader_Stream_getStream, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader_Stream, resetStream, arginfo_class_ion_Reader_Stream_resetStream, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Reader_Stream, resetStreamWithLength, arginfo_class_ion_Reader_Stream_resetStreamWithLength, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_FE_END
};
static const zend_function_entry class_ion_Reader_Buffer_Reader_methods[] = {
ZEND_ME(ion_Reader_Buffer_Reader, getBuffer, arginfo_class_ion_Reader_Buffer_Reader_getBuffer, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
static const zend_function_entry class_ion_Reader_Stream_Reader_methods[] = {
ZEND_ME(ion_Reader_Stream_Reader, getStream, arginfo_class_ion_Reader_Stream_Reader_getStream, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Stream_Reader, resetStream, arginfo_class_ion_Reader_Stream_Reader_resetStream, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Reader_Stream_Reader, resetStreamWithLength, arginfo_class_ion_Reader_Stream_Reader_resetStreamWithLength, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
static const zend_function_entry class_ion_Writer_Writer_methods[] = {
ZEND_ME(ion_Writer_Writer, __construct, arginfo_class_ion_Writer_Writer___construct, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Writer_Writer, writeNull, arginfo_class_ion_Writer_Writer_writeNull, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Writer_Writer, writeTypedNull, arginfo_class_ion_Writer_Writer_writeTypedNull, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Writer_Writer, writeBool, arginfo_class_ion_Writer_Writer_writeBool, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Writer_Writer, writeInt, arginfo_class_ion_Writer_Writer_writeInt, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Writer_Writer, writeFloat, arginfo_class_ion_Writer_Writer_writeFloat, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Writer_Writer, writeDecimal, arginfo_class_ion_Writer_Writer_writeDecimal, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Writer_Writer, writeTimestamp, arginfo_class_ion_Writer_Writer_writeTimestamp, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Writer_Writer, writeSymbol, arginfo_class_ion_Writer_Writer_writeSymbol, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Writer_Writer, writeString, arginfo_class_ion_Writer_Writer_writeString, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Writer_Writer, writeCLob, arginfo_class_ion_Writer_Writer_writeCLob, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Writer_Writer, writeBLob, arginfo_class_ion_Writer_Writer_writeBLob, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Writer_Writer, startLob, arginfo_class_ion_Writer_Writer_startLob, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Writer_Writer, appendLob, arginfo_class_ion_Writer_Writer_appendLob, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Writer_Writer, finishLob, arginfo_class_ion_Writer_Writer_finishLob, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Writer_Writer, startContainer, arginfo_class_ion_Writer_Writer_startContainer, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Writer_Writer, finishContainer, arginfo_class_ion_Writer_Writer_finishContainer, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Writer_Writer, writeFieldName, arginfo_class_ion_Writer_Writer_writeFieldName, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Writer_Writer, writeAnnotation, arginfo_class_ion_Writer_Writer_writeAnnotation, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Writer_Writer, getDepth, arginfo_class_ion_Writer_Writer_getDepth, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Writer_Writer, flush, arginfo_class_ion_Writer_Writer_flush, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Writer_Writer, finish, arginfo_class_ion_Writer_Writer_finish, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
static const zend_function_entry class_ion_Writer_Buffer_methods[] = {
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Writer_Buffer, getBuffer, arginfo_class_ion_Writer_Buffer_getBuffer, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Writer_Buffer, resetBuffer, arginfo_class_ion_Writer_Buffer_resetBuffer, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_FE_END
};
static const zend_function_entry class_ion_Writer_Stream_methods[] = {
ZEND_ABSTRACT_ME_WITH_FLAGS(ion_Writer_Stream, getStream, arginfo_class_ion_Writer_Stream_getStream, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_FE_END
};
static const zend_function_entry class_ion_Writer_Buffer_Writer_methods[] = {
ZEND_ME(ion_Writer_Buffer_Writer, getBuffer, arginfo_class_ion_Writer_Buffer_Writer_getBuffer, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Writer_Buffer_Writer, resetBuffer, arginfo_class_ion_Writer_Buffer_Writer_resetBuffer, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
static const zend_function_entry class_ion_Writer_Stream_Writer_methods[] = {
ZEND_ME(ion_Writer_Stream_Writer, __construct, arginfo_class_ion_Writer_Stream_Writer___construct, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Writer_Stream_Writer, getStream, arginfo_class_ion_Writer_Stream_Writer_getStream, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
static const zend_function_entry class_ion_Serializer_Serializer_methods[] = {
ZEND_ME(ion_Serializer_Serializer, __construct, arginfo_class_ion_Serializer_Serializer___construct, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Serializer_Serializer, serialize, arginfo_class_ion_Serializer_Serializer_serialize, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
static const zend_function_entry class_ion_Unserializer_Unserializer_methods[] = {
ZEND_ME(ion_Unserializer_Unserializer, __construct, arginfo_class_ion_Unserializer_Unserializer___construct, ZEND_ACC_PUBLIC)
ZEND_ME(ion_Unserializer_Unserializer, unserialize, arginfo_class_ion_Unserializer_Unserializer_unserialize, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
static zend_class_entry *register_class_ion_Serializer(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "ion", "Serializer", class_ion_Serializer_methods);
class_entry = zend_register_internal_interface(&ce);
return class_entry;
}
static zend_class_entry *register_class_ion_Unserializer(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "ion", "Unserializer", class_ion_Unserializer_methods);
class_entry = zend_register_internal_interface(&ce);
return class_entry;
}
static zend_class_entry *register_class_ion_Exception(zend_class_entry *class_entry_Exception)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "ion", "Exception", class_ion_Exception_methods);
class_entry = zend_register_internal_class_ex(&ce, class_entry_Exception);
return class_entry;
}
static zend_class_entry *register_class_ion_Type(void)
{
zend_class_entry *class_entry = zend_register_internal_enum("ion\\Type", IS_LONG, class_ion_Type_methods);
zval enum_case_Null_value;
ZVAL_LONG(&enum_case_Null_value, 0);
zend_enum_add_case_cstr(class_entry, "Null", &enum_case_Null_value);
zval enum_case_Bool_value;
ZVAL_LONG(&enum_case_Bool_value, 256);
zend_enum_add_case_cstr(class_entry, "Bool", &enum_case_Bool_value);
zval enum_case_Int_value;
ZVAL_LONG(&enum_case_Int_value, 512);
zend_enum_add_case_cstr(class_entry, "Int", &enum_case_Int_value);
zval enum_case_Float_value;
ZVAL_LONG(&enum_case_Float_value, 1024);
zend_enum_add_case_cstr(class_entry, "Float", &enum_case_Float_value);
zval enum_case_Decimal_value;
ZVAL_LONG(&enum_case_Decimal_value, 1280);
zend_enum_add_case_cstr(class_entry, "Decimal", &enum_case_Decimal_value);
zval enum_case_Timestamp_value;
ZVAL_LONG(&enum_case_Timestamp_value, 1536);
zend_enum_add_case_cstr(class_entry, "Timestamp", &enum_case_Timestamp_value);
zval enum_case_Symbol_value;
ZVAL_LONG(&enum_case_Symbol_value, 1792);
zend_enum_add_case_cstr(class_entry, "Symbol", &enum_case_Symbol_value);
zval enum_case_String_value;
ZVAL_LONG(&enum_case_String_value, 2048);
zend_enum_add_case_cstr(class_entry, "String", &enum_case_String_value);
zval enum_case_CLob_value;
ZVAL_LONG(&enum_case_CLob_value, 2304);
zend_enum_add_case_cstr(class_entry, "CLob", &enum_case_CLob_value);
zval enum_case_BLob_value;
ZVAL_LONG(&enum_case_BLob_value, 2560);
zend_enum_add_case_cstr(class_entry, "BLob", &enum_case_BLob_value);
zval enum_case_List_value;
ZVAL_LONG(&enum_case_List_value, 2816);
zend_enum_add_case_cstr(class_entry, "List", &enum_case_List_value);
zval enum_case_SExp_value;
ZVAL_LONG(&enum_case_SExp_value, 3072);
zend_enum_add_case_cstr(class_entry, "SExp", &enum_case_SExp_value);
zval enum_case_Struct_value;
ZVAL_LONG(&enum_case_Struct_value, 3328);
zend_enum_add_case_cstr(class_entry, "Struct", &enum_case_Struct_value);
zval enum_case_Datagram_value;
ZVAL_LONG(&enum_case_Datagram_value, 3840);
zend_enum_add_case_cstr(class_entry, "Datagram", &enum_case_Datagram_value);
zval enum_case_EOF_value;
ZVAL_LONG(&enum_case_EOF_value, -256);
zend_enum_add_case_cstr(class_entry, "EOF", &enum_case_EOF_value);
zval enum_case_NONE_value;
ZVAL_LONG(&enum_case_NONE_value, -512);
zend_enum_add_case_cstr(class_entry, "NONE", &enum_case_NONE_value);
return class_entry;
}
static zend_class_entry *register_class_ion_Symbol(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "ion", "Symbol", class_ion_Symbol_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
zval property_value_default_value;
ZVAL_UNDEF(&property_value_default_value);
zend_string *property_value_name = zend_string_init("value", sizeof("value") - 1, 1);
zend_declare_typed_property(class_entry, property_value_name, &property_value_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING|MAY_BE_NULL));
zend_string_release(property_value_name);
zval property_sid_default_value;
ZVAL_UNDEF(&property_sid_default_value);
zend_string *property_sid_name = zend_string_init("sid", sizeof("sid") - 1, 1);
zend_declare_typed_property(class_entry, property_sid_name, &property_sid_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zend_string_release(property_sid_name);
zend_string *property_importLocation_class_ion_Symbol_ImportLocation = zend_string_init("ion\\Symbol\\ImportLocation", sizeof("ion\\Symbol\\ImportLocation")-1, 1);
zval property_importLocation_default_value;
ZVAL_UNDEF(&property_importLocation_default_value);
zend_string *property_importLocation_name = zend_string_init("importLocation", sizeof("importLocation") - 1, 1);
zend_declare_typed_property(class_entry, property_importLocation_name, &property_importLocation_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_importLocation_class_ion_Symbol_ImportLocation, 0, MAY_BE_NULL));
zend_string_release(property_importLocation_name);
return class_entry;
}
static zend_class_entry *register_class_ion_Catalog(zend_class_entry *class_entry_Countable)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "ion", "Catalog", class_ion_Catalog_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
zend_class_implements(class_entry, 1, class_entry_Countable);
zval property_symbolTables_default_value;
ZVAL_EMPTY_ARRAY(&property_symbolTables_default_value);
zend_string *property_symbolTables_name = zend_string_init("symbolTables", sizeof("symbolTables") - 1, 1);
zend_declare_typed_property(class_entry, property_symbolTables_name, &property_symbolTables_default_value, ZEND_ACC_PRIVATE, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_ARRAY));
zend_string_release(property_symbolTables_name);
return class_entry;
}
static zend_class_entry *register_class_ion_LOB(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "ion", "LOB", class_ion_LOB_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
zval property_value_default_value;
ZVAL_UNDEF(&property_value_default_value);
zend_string *property_value_name = zend_string_init("value", sizeof("value") - 1, 1);
zend_declare_typed_property(class_entry, property_value_name, &property_value_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING));
zend_string_release(property_value_name);
zend_string *property_type_class_ion_Type = zend_string_init("ion\\Type", sizeof("ion\\Type")-1, 1);
zval property_type_default_value;
ZVAL_UNDEF(&property_type_default_value);
zend_string *property_type_name = zend_string_init("type", sizeof("type") - 1, 1);
zend_declare_typed_property(class_entry, property_type_name, &property_type_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_type_class_ion_Type, 0, 0));
zend_string_release(property_type_name);
return class_entry;
}
static zend_class_entry *register_class_ion_Decimal(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "ion", "Decimal", class_ion_Decimal_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
zval property_number_default_value;
ZVAL_UNDEF(&property_number_default_value);
zend_string *property_number_name = zend_string_init("number", sizeof("number") - 1, 1);
zend_declare_typed_property(class_entry, property_number_name, &property_number_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING|MAY_BE_LONG));
zend_string_release(property_number_name);
zend_string *property_context_class_ion_Decimal_Context = zend_string_init("ion\\Decimal\\Context", sizeof("ion\\Decimal\\Context")-1, 1);
zval property_context_default_value;
ZVAL_UNDEF(&property_context_default_value);
zend_string *property_context_name = zend_string_init("context", sizeof("context") - 1, 1);
zend_declare_typed_property(class_entry, property_context_name, &property_context_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_context_class_ion_Decimal_Context, 0, MAY_BE_NULL));
zend_string_release(property_context_name);
return class_entry;
}
static zend_class_entry *register_class_ion_Timestamp(zend_class_entry *class_entry_DateTime)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "ion", "Timestamp", class_ion_Timestamp_methods);
class_entry = zend_register_internal_class_ex(&ce, class_entry_DateTime);
zval property_precision_default_value;
ZVAL_UNDEF(&property_precision_default_value);
zend_string *property_precision_name = zend_string_init("precision", sizeof("precision") - 1, 1);
zend_declare_typed_property(class_entry, property_precision_name, &property_precision_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zend_string_release(property_precision_name);
zval property_format_default_value;
ZVAL_UNDEF(&property_format_default_value);
zend_string *property_format_name = zend_string_init("format", sizeof("format") - 1, 1);
zend_declare_typed_property(class_entry, property_format_name, &property_format_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING));
zend_string_release(property_format_name);
return class_entry;
}
static zend_class_entry *register_class_ion_Reader(zend_class_entry *class_entry_RecursiveIterator)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "ion", "Reader", class_ion_Reader_methods);
class_entry = zend_register_internal_interface(&ce);
zend_class_implements(class_entry, 1, class_entry_RecursiveIterator);
return class_entry;
}
static zend_class_entry *register_class_ion_Writer(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "ion", "Writer", class_ion_Writer_methods);
class_entry = zend_register_internal_interface(&ce);
return class_entry;
}
static zend_class_entry *register_class_ion_Symbol_ImportLocation(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "ion\\Symbol", "ImportLocation", class_ion_Symbol_ImportLocation_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
zval property_name_default_value;
ZVAL_UNDEF(&property_name_default_value);
zend_string *property_name_name = zend_string_init("name", sizeof("name") - 1, 1);
zend_declare_typed_property(class_entry, property_name_name, &property_name_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING));
zend_string_release(property_name_name);
zval property_location_default_value;
ZVAL_UNDEF(&property_location_default_value);
zend_string *property_location_name = zend_string_init("location", sizeof("location") - 1, 1);
zend_declare_typed_property(class_entry, property_location_name, &property_location_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zend_string_release(property_location_name);
return class_entry;
}
static zend_class_entry *register_class_ion_Symbol_Enum(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "ion\\Symbol", "Enum", class_ion_Symbol_Enum_methods);
class_entry = zend_register_internal_interface(&ce);
return class_entry;
}
static zend_class_entry *register_class_ion_Symbol_Table(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "ion\\Symbol", "Table", class_ion_Symbol_Table_methods);
class_entry = zend_register_internal_interface(&ce);
return class_entry;
}
static zend_class_entry *register_class_ion_Symbol_System(zend_class_entry *class_entry_ion_Symbol_Enum)
{
zend_class_entry *class_entry = zend_register_internal_enum("ion\\Symbol\\System", IS_STRING, class_ion_Symbol_System_methods);
zend_class_implements(class_entry, 1, class_entry_ion_Symbol_Enum);
zval enum_case_Ion_value;
zend_string *enum_case_Ion_value_str = zend_string_init("$ion", sizeof("$ion") - 1, 1);
ZVAL_STR(&enum_case_Ion_value, enum_case_Ion_value_str);
zend_enum_add_case_cstr(class_entry, "Ion", &enum_case_Ion_value);
zval enum_case_Ivm_1_0_value;
zend_string *enum_case_Ivm_1_0_value_str = zend_string_init("$ion_1_0", sizeof("$ion_1_0") - 1, 1);
ZVAL_STR(&enum_case_Ivm_1_0_value, enum_case_Ivm_1_0_value_str);
zend_enum_add_case_cstr(class_entry, "Ivm_1_0", &enum_case_Ivm_1_0_value);
zval enum_case_IonSymbolTable_value;
zend_string *enum_case_IonSymbolTable_value_str = zend_string_init("$ion_symbol_table", sizeof("$ion_symbol_table") - 1, 1);
ZVAL_STR(&enum_case_IonSymbolTable_value, enum_case_IonSymbolTable_value_str);
zend_enum_add_case_cstr(class_entry, "IonSymbolTable", &enum_case_IonSymbolTable_value);
zval enum_case_Name_value;
zend_string *enum_case_Name_value_str = zend_string_init("name", sizeof("name") - 1, 1);
ZVAL_STR(&enum_case_Name_value, enum_case_Name_value_str);
zend_enum_add_case_cstr(class_entry, "Name", &enum_case_Name_value);
zval enum_case_Version_value;
zend_string *enum_case_Version_value_str = zend_string_init("version", sizeof("version") - 1, 1);
ZVAL_STR(&enum_case_Version_value, enum_case_Version_value_str);
zend_enum_add_case_cstr(class_entry, "Version", &enum_case_Version_value);
zval enum_case_Imports_value;
zend_string *enum_case_Imports_value_str = zend_string_init("imports", sizeof("imports") - 1, 1);
ZVAL_STR(&enum_case_Imports_value, enum_case_Imports_value_str);
zend_enum_add_case_cstr(class_entry, "Imports", &enum_case_Imports_value);
zval enum_case_Symbols_value;
zend_string *enum_case_Symbols_value_str = zend_string_init("symbols", sizeof("symbols") - 1, 1);
ZVAL_STR(&enum_case_Symbols_value, enum_case_Symbols_value_str);
zend_enum_add_case_cstr(class_entry, "Symbols", &enum_case_Symbols_value);
zval enum_case_MaxId_value;
zend_string *enum_case_MaxId_value_str = zend_string_init("max_id", sizeof("max_id") - 1, 1);
ZVAL_STR(&enum_case_MaxId_value, enum_case_MaxId_value_str);
zend_enum_add_case_cstr(class_entry, "MaxId", &enum_case_MaxId_value);
zval enum_case_SharedSymbolTable_value;
zend_string *enum_case_SharedSymbolTable_value_str = zend_string_init("$ion_shared_symbol_table", sizeof("$ion_shared_symbol_table") - 1, 1);
ZVAL_STR(&enum_case_SharedSymbolTable_value, enum_case_SharedSymbolTable_value_str);
zend_enum_add_case_cstr(class_entry, "SharedSymbolTable", &enum_case_SharedSymbolTable_value);
return class_entry;
}
static zend_class_entry *register_class_ion_Symbol_PHP(zend_class_entry *class_entry_ion_Symbol_Enum)
{
zend_class_entry *class_entry = zend_register_internal_enum("ion\\Symbol\\PHP", IS_STRING, class_ion_Symbol_PHP_methods);
zend_class_implements(class_entry, 1, class_entry_ion_Symbol_Enum);
zval enum_case_PHP_value;
zend_string *enum_case_PHP_value_str = zend_string_init("PHP", sizeof("PHP") - 1, 1);
ZVAL_STR(&enum_case_PHP_value, enum_case_PHP_value_str);
zend_enum_add_case_cstr(class_entry, "PHP", &enum_case_PHP_value);
zval enum_case_Reference_value;
zend_string *enum_case_Reference_value_str = zend_string_init("R", sizeof("R") - 1, 1);
ZVAL_STR(&enum_case_Reference_value, enum_case_Reference_value_str);
zend_enum_add_case_cstr(class_entry, "Reference", &enum_case_Reference_value);
zval enum_case_Backref_value;
zend_string *enum_case_Backref_value_str = zend_string_init("r", sizeof("r") - 1, 1);
ZVAL_STR(&enum_case_Backref_value, enum_case_Backref_value_str);
zend_enum_add_case_cstr(class_entry, "Backref", &enum_case_Backref_value);
zval enum_case_Property_value;
zend_string *enum_case_Property_value_str = zend_string_init("p", sizeof("p") - 1, 1);
ZVAL_STR(&enum_case_Property_value, enum_case_Property_value_str);
zend_enum_add_case_cstr(class_entry, "Property", &enum_case_Property_value);
zval enum_case_Object_value;
zend_string *enum_case_Object_value_str = zend_string_init("o", sizeof("o") - 1, 1);
ZVAL_STR(&enum_case_Object_value, enum_case_Object_value_str);
zend_enum_add_case_cstr(class_entry, "Object", &enum_case_Object_value);
zval enum_case_ClassObject_value;
zend_string *enum_case_ClassObject_value_str = zend_string_init("c", sizeof("c") - 1, 1);
ZVAL_STR(&enum_case_ClassObject_value, enum_case_ClassObject_value_str);
zend_enum_add_case_cstr(class_entry, "ClassObject", &enum_case_ClassObject_value);
zval enum_case_MagicObject_value;
zend_string *enum_case_MagicObject_value_str = zend_string_init("O", sizeof("O") - 1, 1);
ZVAL_STR(&enum_case_MagicObject_value, enum_case_MagicObject_value_str);
zend_enum_add_case_cstr(class_entry, "MagicObject", &enum_case_MagicObject_value);
zval enum_case_CustomObject_value;
zend_string *enum_case_CustomObject_value_str = zend_string_init("C", sizeof("C") - 1, 1);
ZVAL_STR(&enum_case_CustomObject_value, enum_case_CustomObject_value_str);
zend_enum_add_case_cstr(class_entry, "CustomObject", &enum_case_CustomObject_value);
zval enum_case_Enum_value;
zend_string *enum_case_Enum_value_str = zend_string_init("E", sizeof("E") - 1, 1);
ZVAL_STR(&enum_case_Enum_value, enum_case_Enum_value_str);
zend_enum_add_case_cstr(class_entry, "Enum", &enum_case_Enum_value);
zval enum_case_Serializable_value;
zend_string *enum_case_Serializable_value_str = zend_string_init("S", sizeof("S") - 1, 1);
ZVAL_STR(&enum_case_Serializable_value, enum_case_Serializable_value_str);
zend_enum_add_case_cstr(class_entry, "Serializable", &enum_case_Serializable_value);
return class_entry;
}
static zend_class_entry *register_class_ion_Symbol_Table_Local(zend_class_entry *class_entry_ion_Symbol_Table)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "ion\\Symbol\\Table", "Local", class_ion_Symbol_Table_Local_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
zend_class_implements(class_entry, 1, class_entry_ion_Symbol_Table);
zval property_imports_default_value;
ZVAL_EMPTY_ARRAY(&property_imports_default_value);
zend_string *property_imports_name = zend_string_init("imports", sizeof("imports") - 1, 1);
zend_declare_typed_property(class_entry, property_imports_name, &property_imports_default_value, ZEND_ACC_PRIVATE, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_ARRAY));
zend_string_release(property_imports_name);
zval property_symbols_default_value;
ZVAL_EMPTY_ARRAY(&property_symbols_default_value);
zend_string *property_symbols_name = zend_string_init("symbols", sizeof("symbols") - 1, 1);
zend_declare_typed_property(class_entry, property_symbols_name, &property_symbols_default_value, ZEND_ACC_PRIVATE, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_ARRAY));
zend_string_release(property_symbols_name);
return class_entry;
}
static zend_class_entry *register_class_ion_Symbol_Table_Shared(zend_class_entry *class_entry_ion_Symbol_Table)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "ion\\Symbol\\Table", "Shared", class_ion_Symbol_Table_Shared_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
zend_class_implements(class_entry, 1, class_entry_ion_Symbol_Table);
zval property_name_default_value;
ZVAL_UNDEF(&property_name_default_value);
zend_string *property_name_name = zend_string_init("name", sizeof("name") - 1, 1);
zend_declare_typed_property(class_entry, property_name_name, &property_name_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING));
zend_string_release(property_name_name);
zval property_version_default_value;
ZVAL_UNDEF(&property_version_default_value);
zend_string *property_version_name = zend_string_init("version", sizeof("version") - 1, 1);
zend_declare_typed_property(class_entry, property_version_name, &property_version_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zend_string_release(property_version_name);
zval property_symbols_default_value;
ZVAL_EMPTY_ARRAY(&property_symbols_default_value);
zend_string *property_symbols_name = zend_string_init("symbols", sizeof("symbols") - 1, 1);
zend_declare_typed_property(class_entry, property_symbols_name, &property_symbols_default_value, ZEND_ACC_PRIVATE, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_ARRAY));
zend_string_release(property_symbols_name);
return class_entry;
}
static zend_class_entry *register_class_ion_Decimal_Context(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "ion\\Decimal", "Context", class_ion_Decimal_Context_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
zval property_digits_default_value;
ZVAL_UNDEF(&property_digits_default_value);
zend_string *property_digits_name = zend_string_init("digits", sizeof("digits") - 1, 1);
zend_declare_typed_property(class_entry, property_digits_name, &property_digits_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zend_string_release(property_digits_name);
zval property_eMax_default_value;
ZVAL_UNDEF(&property_eMax_default_value);
zend_string *property_eMax_name = zend_string_init("eMax", sizeof("eMax") - 1, 1);
zend_declare_typed_property(class_entry, property_eMax_name, &property_eMax_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zend_string_release(property_eMax_name);
zval property_eMin_default_value;
ZVAL_UNDEF(&property_eMin_default_value);
zend_string *property_eMin_name = zend_string_init("eMin", sizeof("eMin") - 1, 1);
zend_declare_typed_property(class_entry, property_eMin_name, &property_eMin_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zend_string_release(property_eMin_name);
zend_string *property_round_class_ion_Decimal_Context_Rounding = zend_string_init("ion\\Decimal\\Context\\Rounding", sizeof("ion\\Decimal\\Context\\Rounding")-1, 1);
zval property_round_default_value;
ZVAL_UNDEF(&property_round_default_value);
zend_string *property_round_name = zend_string_init("round", sizeof("round") - 1, 1);
zend_declare_typed_property(class_entry, property_round_name, &property_round_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_round_class_ion_Decimal_Context_Rounding, 0, MAY_BE_LONG));
zend_string_release(property_round_name);
zval property_clamp_default_value;
ZVAL_UNDEF(&property_clamp_default_value);
zend_string *property_clamp_name = zend_string_init("clamp", sizeof("clamp") - 1, 1);
zend_declare_typed_property(class_entry, property_clamp_name, &property_clamp_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_BOOL));
zend_string_release(property_clamp_name);
return class_entry;
}
static zend_class_entry *register_class_ion_Decimal_Context_Rounding(void)
{
zend_class_entry *class_entry = zend_register_internal_enum("ion\\Decimal\\Context\\Rounding", IS_LONG, class_ion_Decimal_Context_Rounding_methods);
zval enum_case_Ceiling_value;
ZVAL_LONG(&enum_case_Ceiling_value, 0);
zend_enum_add_case_cstr(class_entry, "Ceiling", &enum_case_Ceiling_value);
zval enum_case_Up_value;
ZVAL_LONG(&enum_case_Up_value, 1);
zend_enum_add_case_cstr(class_entry, "Up", &enum_case_Up_value);
zval enum_case_HalfUp_value;
ZVAL_LONG(&enum_case_HalfUp_value, 2);
zend_enum_add_case_cstr(class_entry, "HalfUp", &enum_case_HalfUp_value);
zval enum_case_HalfEven_value;
ZVAL_LONG(&enum_case_HalfEven_value, 3);
zend_enum_add_case_cstr(class_entry, "HalfEven", &enum_case_HalfEven_value);
zval enum_case_HalfDown_value;
ZVAL_LONG(&enum_case_HalfDown_value, 4);
zend_enum_add_case_cstr(class_entry, "HalfDown", &enum_case_HalfDown_value);
zval enum_case_Down_value;
ZVAL_LONG(&enum_case_Down_value, 5);
zend_enum_add_case_cstr(class_entry, "Down", &enum_case_Down_value);
zval enum_case_Floor_value;
ZVAL_LONG(&enum_case_Floor_value, 6);
zend_enum_add_case_cstr(class_entry, "Floor", &enum_case_Floor_value);
zval enum_case_Down05Up_value;
ZVAL_LONG(&enum_case_Down05Up_value, 7);
zend_enum_add_case_cstr(class_entry, "Down05Up", &enum_case_Down05Up_value);
return class_entry;
}
static zend_class_entry *register_class_ion_Timestamp_Precision(void)
{
zend_class_entry *class_entry = zend_register_internal_enum("ion\\Timestamp\\Precision", IS_LONG, class_ion_Timestamp_Precision_methods);
zval enum_case_Year_value;
ZVAL_LONG(&enum_case_Year_value, 1);
zend_enum_add_case_cstr(class_entry, "Year", &enum_case_Year_value);
zval enum_case_Month_value;
ZVAL_LONG(&enum_case_Month_value, 3);
zend_enum_add_case_cstr(class_entry, "Month", &enum_case_Month_value);
zval enum_case_Day_value;
ZVAL_LONG(&enum_case_Day_value, 7);
zend_enum_add_case_cstr(class_entry, "Day", &enum_case_Day_value);
zval enum_case_Min_value;
ZVAL_LONG(&enum_case_Min_value, 23);
zend_enum_add_case_cstr(class_entry, "Min", &enum_case_Min_value);
zval enum_case_Sec_value;
ZVAL_LONG(&enum_case_Sec_value, 55);
zend_enum_add_case_cstr(class_entry, "Sec", &enum_case_Sec_value);
zval enum_case_Frac_value;
ZVAL_LONG(&enum_case_Frac_value, 119);
zend_enum_add_case_cstr(class_entry, "Frac", &enum_case_Frac_value);
zval enum_case_MinTZ_value;
ZVAL_LONG(&enum_case_MinTZ_value, 151);
zend_enum_add_case_cstr(class_entry, "MinTZ", &enum_case_MinTZ_value);
zval enum_case_SecTZ_value;
ZVAL_LONG(&enum_case_SecTZ_value, 183);
zend_enum_add_case_cstr(class_entry, "SecTZ", &enum_case_SecTZ_value);
zval enum_case_FracTZ_value;
ZVAL_LONG(&enum_case_FracTZ_value, 247);
zend_enum_add_case_cstr(class_entry, "FracTZ", &enum_case_FracTZ_value);
return class_entry;
}
static zend_class_entry *register_class_ion_Timestamp_Format(void)
{
zend_class_entry *class_entry = zend_register_internal_enum("ion\\Timestamp\\Format", IS_STRING, class_ion_Timestamp_Format_methods);
zval enum_case_Year_value;
zend_string *enum_case_Year_value_str = zend_string_init("Y\\T", sizeof("Y\\T") - 1, 1);
ZVAL_STR(&enum_case_Year_value, enum_case_Year_value_str);
zend_enum_add_case_cstr(class_entry, "Year", &enum_case_Year_value);
zval enum_case_Month_value;
zend_string *enum_case_Month_value_str = zend_string_init("Y-m\\T", sizeof("Y-m\\T") - 1, 1);
ZVAL_STR(&enum_case_Month_value, enum_case_Month_value_str);
zend_enum_add_case_cstr(class_entry, "Month", &enum_case_Month_value);
zval enum_case_Day_value;
zend_string *enum_case_Day_value_str = zend_string_init("Y-m-d\\T", sizeof("Y-m-d\\T") - 1, 1);
ZVAL_STR(&enum_case_Day_value, enum_case_Day_value_str);
zend_enum_add_case_cstr(class_entry, "Day", &enum_case_Day_value);
zval enum_case_Min_value;
zend_string *enum_case_Min_value_str = zend_string_init("Y-m-d\\TH:i", sizeof("Y-m-d\\TH:i") - 1, 1);
ZVAL_STR(&enum_case_Min_value, enum_case_Min_value_str);
zend_enum_add_case_cstr(class_entry, "Min", &enum_case_Min_value);
zval enum_case_Sec_value;
zend_string *enum_case_Sec_value_str = zend_string_init("Y-m-d\\TH:i:s", sizeof("Y-m-d\\TH:i:s") - 1, 1);
ZVAL_STR(&enum_case_Sec_value, enum_case_Sec_value_str);
zend_enum_add_case_cstr(class_entry, "Sec", &enum_case_Sec_value);
zval enum_case_Frac_value;
zend_string *enum_case_Frac_value_str = zend_string_init("Y-m-d\\TH:i:s.v", sizeof("Y-m-d\\TH:i:s.v") - 1, 1);
ZVAL_STR(&enum_case_Frac_value, enum_case_Frac_value_str);
zend_enum_add_case_cstr(class_entry, "Frac", &enum_case_Frac_value);
zval enum_case_MinTZ_value;
zend_string *enum_case_MinTZ_value_str = zend_string_init("Y-m-d\\TH:iP", sizeof("Y-m-d\\TH:iP") - 1, 1);
ZVAL_STR(&enum_case_MinTZ_value, enum_case_MinTZ_value_str);
zend_enum_add_case_cstr(class_entry, "MinTZ", &enum_case_MinTZ_value);
zval enum_case_SecTZ_value;
zend_string *enum_case_SecTZ_value_str = zend_string_init("Y-m-d\\TH:i:sP", sizeof("Y-m-d\\TH:i:sP") - 1, 1);
ZVAL_STR(&enum_case_SecTZ_value, enum_case_SecTZ_value_str);
zend_enum_add_case_cstr(class_entry, "SecTZ", &enum_case_SecTZ_value);
zval enum_case_FracTZ_value;
zend_string *enum_case_FracTZ_value_str = zend_string_init("Y-m-d\\TH:i:s.vP", sizeof("Y-m-d\\TH:i:s.vP") - 1, 1);
ZVAL_STR(&enum_case_FracTZ_value, enum_case_FracTZ_value_str);
zend_enum_add_case_cstr(class_entry, "FracTZ", &enum_case_FracTZ_value);
return class_entry;
}
static zend_class_entry *register_class_ion_Reader_Reader(zend_class_entry *class_entry_ion_Reader)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "ion\\Reader", "Reader", class_ion_Reader_Reader_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_ABSTRACT;
zend_class_implements(class_entry, 1, class_entry_ion_Reader);
zend_string *property_catalog_class_ion_Catalog = zend_string_init("ion\\Catalog", sizeof("ion\\Catalog")-1, 1);
zval property_catalog_default_value;
ZVAL_UNDEF(&property_catalog_default_value);
zend_string *property_catalog_name = zend_string_init("catalog", sizeof("catalog") - 1, 1);
zend_declare_typed_property(class_entry, property_catalog_name, &property_catalog_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_catalog_class_ion_Catalog, 0, MAY_BE_NULL));
zend_string_release(property_catalog_name);
zend_string *property_decimalContext_class_ion_Decimal_Context = zend_string_init("ion\\Decimal\\Context", sizeof("ion\\Decimal\\Context")-1, 1);
zval property_decimalContext_default_value;
ZVAL_UNDEF(&property_decimalContext_default_value);
zend_string *property_decimalContext_name = zend_string_init("decimalContext", sizeof("decimalContext") - 1, 1);
zend_declare_typed_property(class_entry, property_decimalContext_name, &property_decimalContext_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_decimalContext_class_ion_Decimal_Context, 0, MAY_BE_NULL));
zend_string_release(property_decimalContext_name);
zend_string *property_onContextChange_class_Closure = zend_string_init("Closure", sizeof("Closure")-1, 1);
zval property_onContextChange_default_value;
ZVAL_UNDEF(&property_onContextChange_default_value);
zend_string *property_onContextChange_name = zend_string_init("onContextChange", sizeof("onContextChange") - 1, 1);
zend_declare_typed_property(class_entry, property_onContextChange_name, &property_onContextChange_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_onContextChange_class_Closure, 0, MAY_BE_NULL));
zend_string_release(property_onContextChange_name);
zval property_returnSystemValues_default_value;
ZVAL_UNDEF(&property_returnSystemValues_default_value);
zend_string *property_returnSystemValues_name = zend_string_init("returnSystemValues", sizeof("returnSystemValues") - 1, 1);
zend_declare_typed_property(class_entry, property_returnSystemValues_name, &property_returnSystemValues_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_BOOL));
zend_string_release(property_returnSystemValues_name);
zval property_maxContainerDepth_default_value;
ZVAL_UNDEF(&property_maxContainerDepth_default_value);
zend_string *property_maxContainerDepth_name = zend_string_init("maxContainerDepth", sizeof("maxContainerDepth") - 1, 1);
zend_declare_typed_property(class_entry, property_maxContainerDepth_name, &property_maxContainerDepth_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zend_string_release(property_maxContainerDepth_name);
zval property_maxAnnotations_default_value;
ZVAL_UNDEF(&property_maxAnnotations_default_value);
zend_string *property_maxAnnotations_name = zend_string_init("maxAnnotations", sizeof("maxAnnotations") - 1, 1);
zend_declare_typed_property(class_entry, property_maxAnnotations_name, &property_maxAnnotations_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zend_string_release(property_maxAnnotations_name);
zval property_annotationBufferSize_default_value;
ZVAL_UNDEF(&property_annotationBufferSize_default_value);
zend_string *property_annotationBufferSize_name = zend_string_init("annotationBufferSize", sizeof("annotationBufferSize") - 1, 1);
zend_declare_typed_property(class_entry, property_annotationBufferSize_name, &property_annotationBufferSize_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zend_string_release(property_annotationBufferSize_name);
zval property_tempBufferSize_default_value;
ZVAL_UNDEF(&property_tempBufferSize_default_value);
zend_string *property_tempBufferSize_name = zend_string_init("tempBufferSize", sizeof("tempBufferSize") - 1, 1);
zend_declare_typed_property(class_entry, property_tempBufferSize_name, &property_tempBufferSize_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zend_string_release(property_tempBufferSize_name);
zval property_skipCharacterValidation_default_value;
ZVAL_UNDEF(&property_skipCharacterValidation_default_value);
zend_string *property_skipCharacterValidation_name = zend_string_init("skipCharacterValidation", sizeof("skipCharacterValidation") - 1, 1);
zend_declare_typed_property(class_entry, property_skipCharacterValidation_name, &property_skipCharacterValidation_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_BOOL));
zend_string_release(property_skipCharacterValidation_name);
return class_entry;
}
static zend_class_entry *register_class_ion_Reader_Buffer(zend_class_entry *class_entry_ion_Reader)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "ion\\Reader", "Buffer", class_ion_Reader_Buffer_methods);
class_entry = zend_register_internal_interface(&ce);
zend_class_implements(class_entry, 1, class_entry_ion_Reader);
return class_entry;
}
static zend_class_entry *register_class_ion_Reader_Stream(zend_class_entry *class_entry_ion_Reader)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "ion\\Reader", "Stream", class_ion_Reader_Stream_methods);
class_entry = zend_register_internal_interface(&ce);
zend_class_implements(class_entry, 1, class_entry_ion_Reader);
return class_entry;
}
static zend_class_entry *register_class_ion_Reader_Buffer_Reader(zend_class_entry *class_entry_ion_Reader_Reader, zend_class_entry *class_entry_ion_Reader_Buffer)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "ion\\Reader\\Buffer", "Reader", class_ion_Reader_Buffer_Reader_methods);
class_entry = zend_register_internal_class_ex(&ce, class_entry_ion_Reader_Reader);
zend_class_implements(class_entry, 1, class_entry_ion_Reader_Buffer);
return class_entry;
}
static zend_class_entry *register_class_ion_Reader_Stream_Reader(zend_class_entry *class_entry_ion_Reader_Reader, zend_class_entry *class_entry_ion_Reader_Stream)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "ion\\Reader\\Stream", "Reader", class_ion_Reader_Stream_Reader_methods);
class_entry = zend_register_internal_class_ex(&ce, class_entry_ion_Reader_Reader);
zend_class_implements(class_entry, 1, class_entry_ion_Reader_Stream);
return class_entry;
}
static zend_class_entry *register_class_ion_Writer_Writer(zend_class_entry *class_entry_ion_Writer)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "ion\\Writer", "Writer", class_ion_Writer_Writer_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_ABSTRACT;
zend_class_implements(class_entry, 1, class_entry_ion_Writer);
zend_string *property_catalog_class_ion_Catalog = zend_string_init("ion\\Catalog", sizeof("ion\\Catalog")-1, 1);
zval property_catalog_default_value;
ZVAL_UNDEF(&property_catalog_default_value);
zend_string *property_catalog_name = zend_string_init("catalog", sizeof("catalog") - 1, 1);
zend_declare_typed_property(class_entry, property_catalog_name, &property_catalog_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_catalog_class_ion_Catalog, 0, MAY_BE_NULL));
zend_string_release(property_catalog_name);
zend_string *property_decimalContext_class_ion_Decimal_Context = zend_string_init("ion\\Decimal\\Context", sizeof("ion\\Decimal\\Context")-1, 1);
zval property_decimalContext_default_value;
ZVAL_UNDEF(&property_decimalContext_default_value);
zend_string *property_decimalContext_name = zend_string_init("decimalContext", sizeof("decimalContext") - 1, 1);
zend_declare_typed_property(class_entry, property_decimalContext_name, &property_decimalContext_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_decimalContext_class_ion_Decimal_Context, 0, MAY_BE_NULL));
zend_string_release(property_decimalContext_name);
zval property_outputBinary_default_value;
ZVAL_UNDEF(&property_outputBinary_default_value);
zend_string *property_outputBinary_name = zend_string_init("outputBinary", sizeof("outputBinary") - 1, 1);
zend_declare_typed_property(class_entry, property_outputBinary_name, &property_outputBinary_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_BOOL));
zend_string_release(property_outputBinary_name);
zval property_compactFloats_default_value;
ZVAL_UNDEF(&property_compactFloats_default_value);
zend_string *property_compactFloats_name = zend_string_init("compactFloats", sizeof("compactFloats") - 1, 1);
zend_declare_typed_property(class_entry, property_compactFloats_name, &property_compactFloats_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_BOOL));
zend_string_release(property_compactFloats_name);
zval property_escapeNonAscii_default_value;
ZVAL_UNDEF(&property_escapeNonAscii_default_value);
zend_string *property_escapeNonAscii_name = zend_string_init("escapeNonAscii", sizeof("escapeNonAscii") - 1, 1);
zend_declare_typed_property(class_entry, property_escapeNonAscii_name, &property_escapeNonAscii_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_BOOL));
zend_string_release(property_escapeNonAscii_name);
zval property_prettyPrint_default_value;
ZVAL_UNDEF(&property_prettyPrint_default_value);
zend_string *property_prettyPrint_name = zend_string_init("prettyPrint", sizeof("prettyPrint") - 1, 1);
zend_declare_typed_property(class_entry, property_prettyPrint_name, &property_prettyPrint_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_BOOL));
zend_string_release(property_prettyPrint_name);
zval property_indentTabs_default_value;
ZVAL_UNDEF(&property_indentTabs_default_value);
zend_string *property_indentTabs_name = zend_string_init("indentTabs", sizeof("indentTabs") - 1, 1);
zend_declare_typed_property(class_entry, property_indentTabs_name, &property_indentTabs_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_BOOL));
zend_string_release(property_indentTabs_name);
zval property_indentSize_default_value;
ZVAL_UNDEF(&property_indentSize_default_value);
zend_string *property_indentSize_name = zend_string_init("indentSize", sizeof("indentSize") - 1, 1);
zend_declare_typed_property(class_entry, property_indentSize_name, &property_indentSize_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zend_string_release(property_indentSize_name);
zval property_flushEveryValue_default_value;
ZVAL_UNDEF(&property_flushEveryValue_default_value);
zend_string *property_flushEveryValue_name = zend_string_init("flushEveryValue", sizeof("flushEveryValue") - 1, 1);
zend_declare_typed_property(class_entry, property_flushEveryValue_name, &property_flushEveryValue_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_BOOL));
zend_string_release(property_flushEveryValue_name);
zval property_maxContainerDepth_default_value;
ZVAL_UNDEF(&property_maxContainerDepth_default_value);
zend_string *property_maxContainerDepth_name = zend_string_init("maxContainerDepth", sizeof("maxContainerDepth") - 1, 1);
zend_declare_typed_property(class_entry, property_maxContainerDepth_name, &property_maxContainerDepth_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zend_string_release(property_maxContainerDepth_name);
zval property_maxAnnotations_default_value;
ZVAL_UNDEF(&property_maxAnnotations_default_value);
zend_string *property_maxAnnotations_name = zend_string_init("maxAnnotations", sizeof("maxAnnotations") - 1, 1);
zend_declare_typed_property(class_entry, property_maxAnnotations_name, &property_maxAnnotations_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zend_string_release(property_maxAnnotations_name);
zval property_tempBufferSize_default_value;
ZVAL_UNDEF(&property_tempBufferSize_default_value);
zend_string *property_tempBufferSize_name = zend_string_init("tempBufferSize", sizeof("tempBufferSize") - 1, 1);
zend_declare_typed_property(class_entry, property_tempBufferSize_name, &property_tempBufferSize_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zend_string_release(property_tempBufferSize_name);
return class_entry;
}
static zend_class_entry *register_class_ion_Writer_Buffer(zend_class_entry *class_entry_ion_Writer)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "ion\\Writer", "Buffer", class_ion_Writer_Buffer_methods);
class_entry = zend_register_internal_interface(&ce);
zend_class_implements(class_entry, 1, class_entry_ion_Writer);
return class_entry;
}
static zend_class_entry *register_class_ion_Writer_Stream(zend_class_entry *class_entry_ion_Writer)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "ion\\Writer", "Stream", class_ion_Writer_Stream_methods);
class_entry = zend_register_internal_interface(&ce);
zend_class_implements(class_entry, 1, class_entry_ion_Writer);
return class_entry;
}
static zend_class_entry *register_class_ion_Writer_Buffer_Writer(zend_class_entry *class_entry_ion_Writer_Writer, zend_class_entry *class_entry_ion_Writer_Buffer)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "ion\\Writer\\Buffer", "Writer", class_ion_Writer_Buffer_Writer_methods);
class_entry = zend_register_internal_class_ex(&ce, class_entry_ion_Writer_Writer);
zend_class_implements(class_entry, 1, class_entry_ion_Writer_Buffer);
return class_entry;
}
static zend_class_entry *register_class_ion_Writer_Stream_Writer(zend_class_entry *class_entry_ion_Writer_Writer, zend_class_entry *class_entry_ion_Writer_Stream)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "ion\\Writer\\Stream", "Writer", class_ion_Writer_Stream_Writer_methods);
class_entry = zend_register_internal_class_ex(&ce, class_entry_ion_Writer_Writer);
zend_class_implements(class_entry, 1, class_entry_ion_Writer_Stream);
zend_string *property_catalog_class_ion_Catalog = zend_string_init("ion\\Catalog", sizeof("ion\\Catalog")-1, 1);
zval property_catalog_default_value;
ZVAL_UNDEF(&property_catalog_default_value);
zend_string *property_catalog_name = zend_string_init("catalog", sizeof("catalog") - 1, 1);
zend_declare_typed_property(class_entry, property_catalog_name, &property_catalog_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_catalog_class_ion_Catalog, 0, MAY_BE_NULL));
zend_string_release(property_catalog_name);
zend_string *property_decimalContext_class_ion_Decimal_Context = zend_string_init("ion\\Decimal\\Context", sizeof("ion\\Decimal\\Context")-1, 1);
zval property_decimalContext_default_value;
ZVAL_UNDEF(&property_decimalContext_default_value);
zend_string *property_decimalContext_name = zend_string_init("decimalContext", sizeof("decimalContext") - 1, 1);
zend_declare_typed_property(class_entry, property_decimalContext_name, &property_decimalContext_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_decimalContext_class_ion_Decimal_Context, 0, MAY_BE_NULL));
zend_string_release(property_decimalContext_name);
zval property_outputBinary_default_value;
ZVAL_UNDEF(&property_outputBinary_default_value);
zend_string *property_outputBinary_name = zend_string_init("outputBinary", sizeof("outputBinary") - 1, 1);
zend_declare_typed_property(class_entry, property_outputBinary_name, &property_outputBinary_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_BOOL));
zend_string_release(property_outputBinary_name);
zval property_compactFloats_default_value;
ZVAL_UNDEF(&property_compactFloats_default_value);
zend_string *property_compactFloats_name = zend_string_init("compactFloats", sizeof("compactFloats") - 1, 1);
zend_declare_typed_property(class_entry, property_compactFloats_name, &property_compactFloats_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_BOOL));
zend_string_release(property_compactFloats_name);
zval property_escapeNonAscii_default_value;
ZVAL_UNDEF(&property_escapeNonAscii_default_value);
zend_string *property_escapeNonAscii_name = zend_string_init("escapeNonAscii", sizeof("escapeNonAscii") - 1, 1);
zend_declare_typed_property(class_entry, property_escapeNonAscii_name, &property_escapeNonAscii_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_BOOL));
zend_string_release(property_escapeNonAscii_name);
zval property_prettyPrint_default_value;
ZVAL_UNDEF(&property_prettyPrint_default_value);
zend_string *property_prettyPrint_name = zend_string_init("prettyPrint", sizeof("prettyPrint") - 1, 1);
zend_declare_typed_property(class_entry, property_prettyPrint_name, &property_prettyPrint_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_BOOL));
zend_string_release(property_prettyPrint_name);
zval property_indentTabs_default_value;
ZVAL_UNDEF(&property_indentTabs_default_value);
zend_string *property_indentTabs_name = zend_string_init("indentTabs", sizeof("indentTabs") - 1, 1);
zend_declare_typed_property(class_entry, property_indentTabs_name, &property_indentTabs_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_BOOL));
zend_string_release(property_indentTabs_name);
zval property_indentSize_default_value;
ZVAL_UNDEF(&property_indentSize_default_value);
zend_string *property_indentSize_name = zend_string_init("indentSize", sizeof("indentSize") - 1, 1);
zend_declare_typed_property(class_entry, property_indentSize_name, &property_indentSize_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zend_string_release(property_indentSize_name);
zval property_flushEveryValue_default_value;
ZVAL_UNDEF(&property_flushEveryValue_default_value);
zend_string *property_flushEveryValue_name = zend_string_init("flushEveryValue", sizeof("flushEveryValue") - 1, 1);
zend_declare_typed_property(class_entry, property_flushEveryValue_name, &property_flushEveryValue_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_BOOL));
zend_string_release(property_flushEveryValue_name);
zval property_maxContainerDepth_default_value;
ZVAL_UNDEF(&property_maxContainerDepth_default_value);
zend_string *property_maxContainerDepth_name = zend_string_init("maxContainerDepth", sizeof("maxContainerDepth") - 1, 1);
zend_declare_typed_property(class_entry, property_maxContainerDepth_name, &property_maxContainerDepth_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zend_string_release(property_maxContainerDepth_name);
zval property_maxAnnotations_default_value;
ZVAL_UNDEF(&property_maxAnnotations_default_value);
zend_string *property_maxAnnotations_name = zend_string_init("maxAnnotations", sizeof("maxAnnotations") - 1, 1);
zend_declare_typed_property(class_entry, property_maxAnnotations_name, &property_maxAnnotations_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zend_string_release(property_maxAnnotations_name);
zval property_tempBufferSize_default_value;
ZVAL_UNDEF(&property_tempBufferSize_default_value);
zend_string *property_tempBufferSize_name = zend_string_init("tempBufferSize", sizeof("tempBufferSize") - 1, 1);
zend_declare_typed_property(class_entry, property_tempBufferSize_name, &property_tempBufferSize_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zend_string_release(property_tempBufferSize_name);
return class_entry;
}
static zend_class_entry *register_class_ion_Serializer_Serializer(zend_class_entry *class_entry_ion_Serializer)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "ion\\Serializer", "Serializer", class_ion_Serializer_Serializer_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
zend_class_implements(class_entry, 1, class_entry_ion_Serializer);
zval property_multiSequence_default_value;
ZVAL_UNDEF(&property_multiSequence_default_value);
zend_string *property_multiSequence_name = zend_string_init("multiSequence", sizeof("multiSequence") - 1, 1);
zend_declare_typed_property(class_entry, property_multiSequence_name, &property_multiSequence_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_BOOL));
zend_string_release(property_multiSequence_name);
zval property_callMagicSerialize_default_value;
ZVAL_UNDEF(&property_callMagicSerialize_default_value);
zend_string *property_callMagicSerialize_name = zend_string_init("callMagicSerialize", sizeof("callMagicSerialize") - 1, 1);
zend_declare_typed_property(class_entry, property_callMagicSerialize_name, &property_callMagicSerialize_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_BOOL));
zend_string_release(property_callMagicSerialize_name);
zval property_callCustomSerialize_default_value;
ZVAL_UNDEF(&property_callCustomSerialize_default_value);
zend_string *property_callCustomSerialize_name = zend_string_init("callCustomSerialize", sizeof("callCustomSerialize") - 1, 1);
zend_declare_typed_property(class_entry, property_callCustomSerialize_name, &property_callCustomSerialize_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING|MAY_BE_NULL));
zend_string_release(property_callCustomSerialize_name);
return class_entry;
}
static zend_class_entry *register_class_ion_Unserializer_Unserializer(zend_class_entry *class_entry_ion_Unserializer)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "ion\\Unserializer", "Unserializer", class_ion_Unserializer_Unserializer_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
zend_class_implements(class_entry, 1, class_entry_ion_Unserializer);
zval property_multiSequence_default_value;
ZVAL_UNDEF(&property_multiSequence_default_value);
zend_string *property_multiSequence_name = zend_string_init("multiSequence", sizeof("multiSequence") - 1, 1);
zend_declare_typed_property(class_entry, property_multiSequence_name, &property_multiSequence_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_BOOL));
zend_string_release(property_multiSequence_name);
zval property_callMagicUnserialize_default_value;
ZVAL_UNDEF(&property_callMagicUnserialize_default_value);
zend_string *property_callMagicUnserialize_name = zend_string_init("callMagicUnserialize", sizeof("callMagicUnserialize") - 1, 1);
zend_declare_typed_property(class_entry, property_callMagicUnserialize_name, &property_callMagicUnserialize_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_BOOL));
zend_string_release(property_callMagicUnserialize_name);
zval property_callCustomUnserialize_default_value;
ZVAL_UNDEF(&property_callCustomUnserialize_default_value);
zend_string *property_callCustomUnserialize_name = zend_string_init("callCustomUnserialize", sizeof("callCustomUnserialize") - 1, 1);
zend_declare_typed_property(class_entry, property_callCustomUnserialize_name, &property_callCustomUnserialize_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING|MAY_BE_NULL));
zend_string_release(property_callCustomUnserialize_name);
return class_entry;
}
| 53.375951 | 260 | 0.864511 | [
"object"
] |
339ef3a7ddc912dc6a4feca024e359938cc82f16 | 369 | h | C | lexical_analysis.h | Omrigan/legendary-compiler | 00f1c952a809a13c174414768432c86482f19d17 | [
"MIT"
] | null | null | null | lexical_analysis.h | Omrigan/legendary-compiler | 00f1c952a809a13c174414768432c86482f19d17 | [
"MIT"
] | 3 | 2016-04-20T13:40:32.000Z | 2016-04-20T14:14:50.000Z | lexical_analysis.h | Omrigan/legendary-compiler | 00f1c952a809a13c174414768432c86482f19d17 | [
"MIT"
] | null | null | null | //
// Created by oleg on 4/4/16.
//
#include <bits/stdc++.h>
#include <iostream>
#ifndef COMPILER_LEXICAL_ANALYSIS_H
#define COMPILER_LEXICAL_ANALYSIS_H
#include "lexem_types.h"
using namespace std;
void build();
bool possible(vertex cur, char c);
vertex go_ahead(vertex cur, char c);
vector<lexem> lexicalAnalysis(string s);
#endif //COMPILER_LEXICAL_ANALYSIS_H
| 17.571429 | 40 | 0.758808 | [
"vector"
] |
33a25dcf21f77764dd7b352c9cbdf9a0e53fd67d | 755 | h | C | chapter_4/lesson_21/RenderSystem.h | sergey-shambir/cg_course_examples | 921b6218d71731bcb79ddddcc92c9d04a72c62ab | [
"MIT"
] | 5 | 2017-05-13T20:47:13.000Z | 2020-04-18T18:18:03.000Z | chapter_4/lesson_21/RenderSystem.h | sergey-shambir/cg_course_examples | 921b6218d71731bcb79ddddcc92c9d04a72c62ab | [
"MIT"
] | null | null | null | chapter_4/lesson_21/RenderSystem.h | sergey-shambir/cg_course_examples | 921b6218d71731bcb79ddddcc92c9d04a72c62ab | [
"MIT"
] | 8 | 2016-10-24T16:24:21.000Z | 2021-03-15T11:23:57.000Z | #pragma once
#include "Components.h"
#include "PlanetProgram.h"
#include <anax/System.hpp>
class CPlanetRenderer3D;
class CRenderSystem
: public anax::System<anax::Requires<CMeshComponent, CTransformComponent>>
{
public:
CRenderSystem();
void SetupLight0(const glm::vec4 &position,
const glm::vec4 &diffuse,
const glm::vec4 &specular);
void Render(const glm::mat4 &view, const glm::mat4 &projection);
private:
struct LightSource
{
glm::vec4 m_position;
glm::vec4 m_diffuse;
glm::vec4 m_specular;
};
void DoRenderPass(CMeshComponent::Category category, CPlanetRenderer3D &renderer);
CPlanetProgram m_planetProgram;
LightSource m_light0;
};
| 23.59375 | 86 | 0.66755 | [
"render"
] |
33a9df7ebe323a914edb27de3ae6636493a4bf73 | 3,448 | h | C | 3rdparty/metaioar_clv2/metaioSDK/include/metaioSDK/IARELInterpreterCallback.h | PlusToolkit/OvrvisionPro | ed64cade144ce47d17423369476fb43ea69b124d | [
"MIT"
] | null | null | null | 3rdparty/metaioar_clv2/metaioSDK/include/metaioSDK/IARELInterpreterCallback.h | PlusToolkit/OvrvisionPro | ed64cade144ce47d17423369476fb43ea69b124d | [
"MIT"
] | null | null | null | 3rdparty/metaioar_clv2/metaioSDK/include/metaioSDK/IARELInterpreterCallback.h | PlusToolkit/OvrvisionPro | ed64cade144ce47d17423369476fb43ea69b124d | [
"MIT"
] | null | null | null | // Copyright 2007-2013 metaio GmbH. All rights reserved.
#ifndef _IAREL_INTERPRETER_CALLBACK_H_
#define _IAREL_INTERPRETER_CALLBACK_H_
#include <metaioSDK/ARELSceneOptions.h>
#include <metaioSDK/STLCompatibility.h>
#include <map>
#include <string>
namespace metaio
{
struct ByteBuffer; // fwd decl.
class IARELObject; // fwd decl.
/**
* Interface to receive the callbacks form the ARELInterpreter
*/
class IARELInterpreterCallback
{
public:
/**
* Destructor.
*/
virtual ~IARELInterpreterCallback() {};
/**
* The implementation should play a video from a given URL
* \param videoURL the url to the video
* \return true if handled by the callback, false to use the default implementation
*/
virtual bool playVideo(const stlcompat::String& videoURL) { return false; }
/**
* Open the URL
* \param url the url to the website
* \param openInExternalApp true to open in external app, false otherwise
* \return true if handled by the callback, false to use the default implementation
*/
virtual bool openWebsite(const stlcompat::String& url, bool openInExternalApp = false) { return false; }
/**
* This is triggered as soon as the SDK is ready, e.g. splash screen is finished.
*/
virtual void onSDKReady() {};
/**
* Called after scene options were parsed from AREL XML file (always called even if there are no
* scene options) but before those options are applied internally so that the options can
* still be overridden/removed
*
* Note that EARELSO_CAMERA and EARELSO_PADDING_TO_ANNOTATIONS are handled internally already.
*
* \param sceneOptions Vector containing options from the XML file (see ARELSceneOptions.h for
* possible keys and their values)
*/
virtual void onSceneOptionsParsed(stlcompat::Vector<metaio::ARELSceneOption>& sceneOptions) {};
/**
* This is triggered as soon as the AREL is ready, including the loading of XML geometries.
*/
virtual void onSceneReady() {};
/** This method is called when an AREL developer wants to open the sharing screen
* \param image the image (screenshot)
* \param saveToGalleryWithoutDialog if true, then the application will only save it to the gallery
* without displaying the sharing dialog
*/
virtual void shareScreenshot(metaio::ByteBuffer* image, bool saveToGalleryWithoutDialog) {};
/** Callback function that should open POI detail view
* The ARELInterpreter must be informed when the detail view is closed by calling
* onDetailViewClosed
* \param poi the poi that should be displayed
*/
virtual void openPOIDetail(const metaio::IARELObject* poi) {};
private:
/**
* \deprecated You must use the method signature with stlcompat::Vector instead. The other method
* replaces this one!
*/
virtual void onSceneOptionsParsed(const std::map<std::string, std::string>& sceneOptions) METAIOSDK_CPP11_FINAL {};
/**
* \deprecated You must use the method signature with stlcompat::String instead. The other method
* replaces this one!
*/
virtual bool openWebsite(const std::string& url, bool openInExternalApp = false) METAIOSDK_CPP11_FINAL { return false; }
/**
* \deprecated You must use the method signature with stlcompat::String instead. The other method
* replaces this one!
*/
virtual bool playVideo(const std::string& videoURL) METAIOSDK_CPP11_FINAL { return false; }
};
}
#endif
| 32.528302 | 121 | 0.724188 | [
"vector"
] |
33b82f3ede92b9f97bf5de66cf3d5a5e330c8440 | 2,516 | h | C | Engine/Source/Runtime/Engine/Classes/Particles/SubUV/ParticleModuleSubUV.h | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | Engine/Source/Runtime/Engine/Classes/Particles/SubUV/ParticleModuleSubUV.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/SubUV/ParticleModuleSubUV.h | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "Particles/SubUV/ParticleModuleSubUVBase.h"
#include "Particles/ParticleEmitter.h"
#include "ParticleModuleSubUV.generated.h"
UCLASS(editinlinenew, hidecategories=Object, MinimalAPI, meta=(DisplayName = "SubImage Index"))
class UParticleModuleSubUV : public UParticleModuleSubUVBase
{
GENERATED_UCLASS_BODY()
/**
* The index of the sub-image that should be used for the particle.
* The value is retrieved using the RelativeTime of the particles.
*/
UPROPERTY(EditAnywhere, Category=SubUV)
struct FRawDistributionFloat SubImageIndex;
/**
* If true, use *real* time when updating the image index.
* The movie will update regardless of the slomo settings of the game.
*/
UPROPERTY(EditAnywhere, Category=Realtime)
uint32 bUseRealTime:1;
/** Initializes the default values for this property */
void InitializeDefaults();
//Begin UObject Interface
#if WITH_EDITOR
virtual void PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) override;
#endif // WITH_EDITOR
virtual void PostInitProperties() override;
//End UObject Interface
// Begin UParticleModule Interface
virtual void CompileModule( struct FParticleEmitterBuildInfo& EmitterInfo ) override;
virtual void Spawn(FParticleEmitterInstance* Owner, int32 Offset, float SpawnTime, FBaseParticle* ParticleBase) override;
virtual void Update(FParticleEmitterInstance* Owner, int32 Offset, float DeltaTime) override;
virtual void SetToSensibleDefaults(UParticleEmitter* Owner) override;
// End UParticleModule Interface
/**
* Determine the current image index to use...
*
* @param Owner The emitter instance being updated.
* @param Offset The offset to the particle payload for this module.
* @param Particle The particle that the image index is being determined for.
* @param InterpMethod The EParticleSubUVInterpMethod method used to update the subUV.
* @param SubUVPayload The FFullSubUVPayload for this particle.
*
* @return float The image index with interpolation amount as the fractional portion.
*/
virtual float DetermineImageIndex(FParticleEmitterInstance* Owner, int32 Offset, FBaseParticle* Particle,
EParticleSubUVInterpMethod InterpMethod, FFullSubUVPayload& SubUVPayload, float DeltaTime);
#if WITH_EDITOR
virtual bool IsValidForLODLevel(UParticleLODLevel* LODLevel, FString& OutErrorString) override;
#endif
protected:
friend class FParticleModuleSubUVDetails;
};
| 36.463768 | 122 | 0.786963 | [
"object"
] |
33ba4c47ae9cdf175dc6bf62f0169ce10e5399b2 | 112,756 | c | C | kernel/huawei/hwp7/drivers/video/hi6620/edc_overlay.c | NightOfTwelve/android_device_huawei_hwp7 | a0a1c28e44210ce485a4177ac53d3fd580008a1e | [
"Apache-2.0"
] | 1 | 2020-04-03T14:00:34.000Z | 2020-04-03T14:00:34.000Z | kernel/huawei/hwp7/drivers/video/hi6620/edc_overlay.c | NightOfTwelve/android_device_huawei_hwp7 | a0a1c28e44210ce485a4177ac53d3fd580008a1e | [
"Apache-2.0"
] | null | null | null | kernel/huawei/hwp7/drivers/video/hi6620/edc_overlay.c | NightOfTwelve/android_device_huawei_hwp7 | a0a1c28e44210ce485a4177ac53d3fd580008a1e | [
"Apache-2.0"
] | 1 | 2020-04-03T14:00:39.000Z | 2020-04-03T14:00:39.000Z | /* Copyright (c) 2008-2010, Hisilicon Tech. Co., Ltd. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*
*/
#include <linux/fb.h>
#include <linux/clk.h>
#include <linux/regulator/consumer.h>
#include <linux/delay.h>
#include <mach/boardid.h>
#include <trace/trace_kernel.h>
#include "k3_fb.h"
#include "edc_reg.h"
#include "ldi_reg.h"
#include "mipi_reg.h"
#include "sbl_reg.h"
#include <mach/hisi_mem.h>
#ifdef CONFIG_FOLLOWABILITY
#include "fb_monitor.h"
#endif
#define CAMERA_XRES_TEST 320
#define CAMERA_YRES_TEST 480
#define DDR_FREQ_POWER_ON 533000
/*--------------------VERTICLE--------------------*/
/* enlarge */
static s16 gfxcoefficient4_cubic[16][4] = {
{0, 511, 0, 0, },
{-37, 509, 42, -2, },
{-64, 499, 86, -9, },
{-82, 484, 129, -19, },
{-94, 463, 174, -31, },
{-98, 438, 217, -45, },
{-98, 409, 260, -59, },
{-92, 376, 300, -72, },
{-83, 339, 339, -83, },
{-72, 300, 376, -92, },
{-59, 260, 409, -98, },
{-45, 217, 438, -98, },
{-31, 174, 463, -94, },
{-19, 129, 484, -82, },
{-9, 86, 499, -64, },
{-2, 42, 509, -37, }
};
/* scaler down below 4/3 times */
static s16 gfxcoefficient4_lanczos2_6M_a15[16][4] = {
{79, 383, 79, -29},
{58, 384, 102, -32},
{40, 380, 127, -35},
{23, 374, 153, -38},
{8, 363, 180, -39},
{-6, 349, 208, -39},
{-16, 331, 235, -38},
{-25, 311, 262, -36},
{-31, 287, 287, -31},
{-36, 262, 311, -25},
{-38, 235, 331, -16},
{-39, 208, 349, -6},
{-39, 180, 363, 8},
{-38, 153, 374, 23},
{-35, 127, 380, 40},
{-32, 102, 384, 58}
};
/* scaler down below 2 times */
static s16 gfxcoefficient4_lanczos2_5M_a15[16][4] = {
{103, 328, 103, -22},
{85, 328, 121, -22},
{69, 324, 141, -22},
{53, 319, 161, -21},
{40, 311, 181, -20},
{27, 301, 201, -17},
{16, 288, 221, -13},
{7, 273, 240, -8},
{-2, 258, 258, -2},
{-8, 240, 273, 7},
{-13, 221, 288, 16},
{-17, 201, 301, 27},
{-20, 181, 311, 40},
{-21, 161, 319, 53},
{-22, 141, 324, 69},
{-22, 121, 328, 85}
};
/*--------------------HORIZONTAL--------------------*/
/* enlarge */
static s16 gfxcoefficient8_cubic[8][8] = {
{0, 0, 0, 511, 0, 0, 0, 0, },
{-3, 11, -41, 496, 61, -16, 4, 0, },
{-4, 17, -63, 451, 138, -35, 9, -1, },
{-4, 18, -70, 386, 222, -52, 14, -2, },
{-3, 17, -65, 307, 307, -65, 17, -3, },
{-2, 14, -52, 222, 386, -70, 18, -4, },
{-1, 9, -35, 138, 451, -63, 17, -4, },
{0, 4, -16, 61, 496, -41, 11, -3, }
};
/* scaler down */
static s16 gfxcoefficient8_lanczos2_8tap[8][8] = {
{-16, 0, 145, 254, 145, 0, -16, 0},
{-13, -9, 123, 252, 167, 11, -19, 0},
{-10, -15, 101, 245, 188, 25, -21, -1},
{-7, -19, 80, 236, 206, 41, -22, -3},
{-5, -21, 60, 222, 222, 60, -21, -5},
{-3, -22, 41, 206, 236, 80, -19, -7},
{-1, -21, 25, 188, 245, 101, -15, -10},
{0, -19, 11, 167, 252, 123, -9, -13}
};
static bool isAlphaRGBType(int format)
{
switch (format) {
case EDC_ARGB_1555:
case EDC_ARGB_8888:
return true;
default:
return false;
}
return false;
}
static int get_bytespp(int format)
{
switch (format) {
case EDC_ARGB_1555:
case EDC_RGB_565:
return 2;
case EDC_XRGB_8888:
case EDC_ARGB_8888:
return 4;
case EDC_YUYV_I:
case EDC_UYVY_I:
case EDC_YVYU_I:
case EDC_VYUY_I:
default:
return 2;
}
}
static int g_ovly2ch_map[OVERLAY_SURFACE_MAX - 1] = {OVERLAY_TO_CHANELL_MAP_INVALID,
OVERLAY_TO_CHANELL_MAP_INVALID,
OVERLAY_TO_CHANELL_MAP_INVALID,
OVERLAY_TO_CHANELL_MAP_INVALID};
static struct st_overlay_surf_reg_func g_overlay_surf_func[OVERLAY_SURFACE_MAX] = {
{NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
set_EDC_CROSS_CTL_ovly_1_sel}, /* ovly_1 */
{set_EDC_CH12_OVLY_alp_blend_en,
set_EDC_CH12_OVLY_alp_src,
set_EDC_CH12_OVLY_ch1_alp_sel,
set_EDC_CH12_OVLY_pix_alp_src,
set_EDC_CH12_OVLY_ch2_alp_sel,
set_EDC_CH12_GLB_ALP_VAL,
set_EDC_CH12_OVLY_ch2_top,
set_EDC_CROSS_CTL_ovly_2_sel}, /* ovly_2 */
{set_EDC_OVERLAY_3_blend_en,
set_EDC_OVERLAY_3_alpha_mode,
set_EDC_OVERLAY_3_under_alpha_sel,
NULL, /* alpha_src is null */
set_EDC_OVERLAY_3_alpha_sel,
set_EDC_OVERLAY_3_glb_alpha,
NULL,
set_EDC_CROSS_CTL_ovly_3_sel}, /* ovly_3 */
{set_EDC_OVERLAY_4_blend_en,
set_EDC_OVERLAY_4_alpha_mode,
set_EDC_OVERLAY_4_under_alpha_sel,
NULL,
set_EDC_OVERLAY_4_alpha_sel,
set_EDC_OVERLAY_4_glb_alpha,
NULL,
set_EDC_CROSS_CTL_ovly_4_sel}, /* ovly_4 */
{set_EDC_CRS_CTL_alp_blend_en,
set_EDC_CRS_CTL_alp_src,
set_EDC_CRS_CTL_under_alp_sel,
NULL,
set_EDC_CRS_CTL_alp_sel,
set_EDC_CRS_GLB_ALP_VAL,
NULL,
NULL} /* always,ovly_5 is cursor layer */
};
static bool is64BytesOddAlign(int type, u32 stride)
{
if (type == FB_64BYTES_ODD_ALIGN_NONE) {
return true;
} else {
return (((stride / 64) % 2 == 0) ? false : true);
}
}
static bool isNeedDither(struct k3_fb_data_type *k3fd)
{
BUG_ON(k3fd == NULL);
if (k3fd->fb_imgType > EDC_ARGB_8888) {
return false;
}
if (((k3fd->panel_info.bpp == EDC_OUT_RGB_565) && (k3fd->fb_imgType == EDC_RGB_565)) ||
((k3fd->panel_info.bpp == EDC_OUT_RGB_888) && (k3fd->fb_imgType == EDC_ARGB_8888)) ||
((k3fd->panel_info.bpp == EDC_OUT_RGB_888) && (k3fd->fb_imgType == EDC_XRGB_8888))) {
return false;
}
return true;
}
static u32 computeDisplayAddr(struct k3fb_img *img,
u32 rotation, struct k3fb_rect *src)
{
u32 addr = 0;
u32 temp = 0;
BUG_ON(img == NULL || src == NULL);
switch (rotation) {
case EDC_ROT_NOP:
{
addr = img->phy_addr + img->stride * src->y +
src->x * get_bytespp(img->format);
}
break;
case EDC_ROT_90:
{
addr = img->phy_addr + img->stride * src->y +
src->x * get_bytespp(img->format);
temp = src->w;
src->w = src->h;
src->h = temp;
}
break;
case EDC_ROT_180:
{
addr = img->phy_addr + img->stride * (src->y + src->h - 1) +
src->x * get_bytespp(img->format);
}
break;
case EDC_ROT_270:
{
addr = img->phy_addr + img->stride * (src->y + src->h - 1) +
src->x * get_bytespp(img->format);
temp = src->w;
src->w = src->h;
src->h = temp;
}
break;
default:
k3fb_loge("Unsupported rotation(%d)!\n", rotation);
break;
}
return addr;
}
#if defined(CONFIG_OVERLAY_PIXEL_ALIGN_SUPPORT)
static void resetSizeByClip(u32* w, u32* h, u32 rotation, u32 clip_right, u32 clip_bottom, int rate)
{
switch(rotation)
{
case EDC_ROT_NOP:
case EDC_ROT_180:
*w = *w + rate * clip_right;
*h = *h + rate * clip_bottom;
break;
case EDC_ROT_90:
case EDC_ROT_270:
*w = *w + rate * clip_bottom;
*h = *h + rate * clip_right;
break;
default:
break;
}
}
static int alignCompute(int format, int alignMask)
{
int i = 1;
int a = 0;
int b = 0;
int bpp = get_bytespp(format);
if (bpp > alignMask){
a = bpp;
b = alignMask;
}
else {
a = alignMask;
b = bpp;
}
while(((a * i) % b) != 0){
i++;
}
return (a * i) / bpp;
}
static void computeAlignSrc(struct k3fb_img *img, struct overlay_info * info, struct k3fb_rect * src, struct k3fb_rect * outSrc)
{
u32 addr = 0;
uint32_t height = img->height;
uint32_t srcW = src->w - info->clip_right;
int wAlign = alignCompute(img->format, 16);
int hAlign = 2;
int leftClip = 0;
int topClip = 0;
outSrc->x = src->x;
outSrc->y = src->y;
outSrc->w = src->w;
outSrc->h = src->h;
//printk("outSrc->h:%d outSrc->y: %d height:%d alignheight: %d", outSrc->h, outSrc->y, height, ALIGN_UP(height, hAlign));
topClip = (outSrc->h + outSrc->y) - ALIGN_UP(height, hAlign);
//printk("topClip: %d \n", topClip);
if (topClip < 0){
topClip = 0;
}
info->clip_bottom -= topClip;
outSrc->y -= topClip;
//printk("info->clip_bottom: %d \n", info->clip_bottom);
addr = computeDisplayAddr(img, EDC_ROT_NOP, outSrc);
//printk("addr: %X \n", addr);
//128bit(16byte) align
if (addr & 0x0f) {
leftClip = (addr & 0x0f) / get_bytespp(img->format);
outSrc->x -= leftClip;
//printk("outSrc->x: %d,srcW: %d \n", outSrc->x, srcW);
outSrc->w = ALIGN_UP((srcW + leftClip), wAlign);
//printk("outSrc->w: %d \n", outSrc->w);
info->clip_right = outSrc->w - (srcW + leftClip);
}
return;
}
#endif
int edc_mtcos_enable(u32 fb_index)
{
int i = 0;
u32 pw_en_bit = 3;
u32 edc_mtcos_state = 0x8;
if (0 == fb_index) {
pw_en_bit = 3;
edc_mtcos_state = 0x8; /* bit3 */
} else if (1 == fb_index) {
pw_en_bit = 4;
edc_mtcos_state = 0x10; /* bit4 */
} else {
k3fb_loge("fb index is not support index = %d \n", fb_index);
return -1;
}
soc_ao_sctrl_reg_wr(SOC_AO_SCTRL_SC_PW_EN0_ADDR(0),pw_en_bit, pw_en_bit, 1);
(void)udelay(10);
for (i = 0; i < 200; i++)
{
if ((edc_mtcos_state & soc_ao_sctrl_reg_rd(SOC_AO_SCTRL_SC_MTCMOS_STAT0_ADDR(0))) == edc_mtcos_state) {
break;
}
}
if (200 == i) {
k3fb_loge("mtcmos status no ready \n");
return -1;
}
return 0;
}
int edc_mtcos_disable(u32 fb_index)
{
u32 pw_dis_bit = 3;
if (0 == fb_index) {
pw_dis_bit = 3; /* bit3 */
} else if (1 == fb_index) {
pw_dis_bit = 4; /* bit4 */
} else {
k3fb_loge("fb index is not support index = %d \n", fb_index);
return -1;
}
soc_ao_sctrl_reg_wr(SOC_AO_SCTRL_SC_PW_DIS0_ADDR(0),pw_dis_bit, pw_dis_bit, 1);
udelay(10);
return 0;
}
static void edc_overlay_pipe_init4ch1(struct edc_overlay_pipe *pipe)
{
BUG_ON(pipe == NULL);
pipe->edc_ch_info.cap.ckey_enable = 0;
pipe->edc_ch_info.ckeymin = 0xffffcc;
pipe->edc_ch_info.ckeymax = 0xffffec;
pipe->edc_ch_info.cap.alpha_enable = 1;
pipe->edc_ch_info.alp_src = EDC_ALP_PIXEL;
pipe->edc_ch_info.alpha0 = 0x7f;
pipe->edc_ch_info.alpha1 = 0x7f;
pipe->edc_ch_info.cap.filter_enable = 1;
pipe->edc_ch_info.cap.csc_enable = 1;
pipe->req_info.overlay_num = OVERLAY_SURFACE_1;
pipe->set_EDC_CHL_ADDR = set_EDC_CH1L_ADDR;
pipe->set_EDC_CHR_ADDR = set_EDC_CH1R_ADDR;
pipe->set_EDC_CH_CTL_ch_en = set_EDC_CH1_CTL_ch1_en;
pipe->set_EDC_CH_CTL_secu_line = set_EDC_CH1_CTL_secu_line;
pipe->set_EDC_CH_CTL_bgr = set_EDC_CH1_CTL_bgr;
pipe->set_EDC_CH_CTL_pix_fmt = set_EDC_CH1_CTL_pix_fmt;
pipe->set_EDC_CH_CTL_colork_en = set_EDC_CH1_CTL_colork_en;
pipe->set_EDC_CH_COLORK_MIN = set_EDC_CH1_COLORK_MIN;
pipe->set_EDC_CH_COLORK_MAX = set_EDC_CH1_COLORK_MAX;
pipe->set_EDC_CH_XY = set_EDC_CH1_XY;
pipe->set_EDC_CH_SIZE = set_EDC_CH1_SIZE;
pipe->set_EDC_CH_STRIDE = set_EDC_CH1_STRIDE;
/*begin support edc pixels algin modified by weiyi 00175802*/
#if defined(CONFIG_OVERLAY_PIXEL_ALIGN_SUPPORT)
pipe->set_EDC_CH_CLIP_bottom = set_EDC_CH1_CLIP_bottom_clip;
pipe->set_EDC_CH_CLIP_right = set_EDC_CH1_CLIP_right_clip;
pipe->set_EDC_CH_CLIP_left = set_EDC_CH1_CLIP_left_clip;
pipe->set_EDC_CH_CLIP_top = set_EDC_CH1_CLIP_top_clip;
#endif
/*end support edc pixels algin modified by weiyi 00175802*/
pipe->set_EDC_CH_CSCIDC_csc_en = set_EDC_CH1_CSCIDC_csc_en;
pipe->set_EDC_CH_CSCIDC = set_EDC_CH1_CSCIDC;
pipe->set_EDC_CH_CSCODC = set_EDC_CH1_CSCODC;
pipe->set_EDC_CH_CSCP0 = set_EDC_CH1_CSCP0;
pipe->set_EDC_CH_CSCP1 = set_EDC_CH1_CSCP1;
pipe->set_EDC_CH_CSCP2 = set_EDC_CH1_CSCP2;
pipe->set_EDC_CH_CSCP3 = set_EDC_CH1_CSCP3;
pipe->set_EDC_CH_CSCP4 = set_EDC_CH1_CSCP4;
#if defined(CONFIG_OVERLAY_COMPOSE)
pipe->set_OVC_CH_CSCIDC = set_OVC_CH1_CSCIDC;
pipe->set_OVC_CH_CSCODC = set_OVC_CH1_CSCODC;
pipe->set_OVC_CH_CSCP0 = set_OVC_CH1_CSCP0;
pipe->set_OVC_CH_CSCP1 = set_OVC_CH1_CSCP1;
pipe->set_OVC_CH_CSCP2 = set_OVC_CH1_CSCP2;
pipe->set_OVC_CH_CSCP3 = set_OVC_CH1_CSCP3;
pipe->set_OVC_CH_CSCP4 = set_OVC_CH1_CSCP4;
#endif //CONFIG_OVERLAY_COMPOSE
}
static void edc_overlay_pipe_init4ch2(struct edc_overlay_pipe *pipe)
{
BUG_ON(pipe == NULL);
pipe->edc_ch_info.cap.ckey_enable = 0;
pipe->edc_ch_info.ckeymin = 0xffffcc;
pipe->edc_ch_info.ckeymax = 0xffffec;
pipe->edc_ch_info.cap.alpha_enable = 1;
pipe->edc_ch_info.alp_src = EDC_ALP_PIXEL;
pipe->edc_ch_info.alpha0 = 0x7f;
pipe->edc_ch_info.alpha1 = 0x7f;
pipe->edc_ch_info.cap.filter_enable = 1;
pipe->edc_ch_info.cap.csc_enable = 1;
/* added by gongyu for five edc layer compose, this is default config */
pipe->req_info.overlay_num = OVERLAY_SURFACE_2;
pipe->set_EDC_CHL_ADDR = set_EDC_CH2L_ADDR;
pipe->set_EDC_CHR_ADDR = set_EDC_CH2R_ADDR;
pipe->set_EDC_CH_CTL_ch_en = set_EDC_CH2_CTL_ch2_en;
pipe->set_EDC_CH_CTL_secu_line = set_EDC_CH2_CTL_secu_line;
pipe->set_EDC_CH_CTL_bgr = set_EDC_CH2_CTL_bgr;
pipe->set_EDC_CH_CTL_pix_fmt = set_EDC_CH2_CTL_pix_fmt;
pipe->set_EDC_CH_CTL_colork_en = set_EDC_CH2_CTL_colork_en;
pipe->set_EDC_CH_COLORK_MIN = set_EDC_CH2_COLORK_MIN;
pipe->set_EDC_CH_COLORK_MAX = set_EDC_CH2_COLORK_MAX;
pipe->set_EDC_CH_XY = set_EDC_CH2_XY;
pipe->set_EDC_CH_SIZE = set_EDC_CH2_SIZE;
pipe->set_EDC_CH_STRIDE = set_EDC_CH2_STRIDE;
/*begin support edc pixels algin modified by weiyi 00175802*/
#if defined(CONFIG_OVERLAY_PIXEL_ALIGN_SUPPORT)
pipe->set_EDC_CH_CLIP_bottom = set_EDC_CH2_CLIP_bottom_clip;
pipe->set_EDC_CH_CLIP_right = set_EDC_CH2_CLIP_right_clip;
pipe->set_EDC_CH_CLIP_left = set_EDC_CH2_CLIP_left_clip;
pipe->set_EDC_CH_CLIP_top = set_EDC_CH2_CLIP_top_clip;
#endif
/*end support edc pixels algin modified by weiyi 00175802*/
pipe->set_EDC_CH_CSCIDC_csc_en = set_EDC_CH2_CSCIDC_csc_en;
pipe->set_EDC_CH_CSCIDC = set_EDC_CH2_CSCIDC;
pipe->set_EDC_CH_CSCODC = set_EDC_CH2_CSCODC;
pipe->set_EDC_CH_CSCP0 = set_EDC_CH2_CSCP0;
pipe->set_EDC_CH_CSCP1 = set_EDC_CH2_CSCP1;
pipe->set_EDC_CH_CSCP2 = set_EDC_CH2_CSCP2;
pipe->set_EDC_CH_CSCP3 = set_EDC_CH2_CSCP3;
pipe->set_EDC_CH_CSCP4 = set_EDC_CH2_CSCP4;
#if defined(CONFIG_OVERLAY_COMPOSE)
pipe->set_OVC_CH_CSCIDC = set_OVC_CH2_CSCIDC;
pipe->set_OVC_CH_CSCODC = set_OVC_CH2_CSCODC;
pipe->set_OVC_CH_CSCP0 = set_OVC_CH2_CSCP0;
pipe->set_OVC_CH_CSCP1 = set_OVC_CH2_CSCP1;
pipe->set_OVC_CH_CSCP2 = set_OVC_CH2_CSCP2;
pipe->set_OVC_CH_CSCP3 = set_OVC_CH2_CSCP3;
pipe->set_OVC_CH_CSCP4 = set_OVC_CH2_CSCP4;
#endif //CONFIG_OVERLAY_COMPOSE
}
#if defined(CONFIG_OVERLAY_COMPOSE)
static void edc_overlay_pipe_init4crs(struct edc_overlay_pipe *pipe)
{
BUG_ON(pipe == NULL);
pipe->edc_ch_info.cap.ckey_enable = 0;
pipe->edc_ch_info.ckeymin = 0xffffcc;
pipe->edc_ch_info.ckeymax = 0xffffec;
pipe->edc_ch_info.cap.alpha_enable = 1;
pipe->edc_ch_info.alp_src = EDC_ALP_PIXEL;
pipe->edc_ch_info.alpha0 = 0x7f;
pipe->edc_ch_info.alpha1 = 0x7f;
pipe->edc_ch_info.cap.filter_enable = 0;
pipe->edc_ch_info.cap.csc_enable = 0;
/* added by gongyu for five edc layer compose, this is default config */
pipe->req_info.overlay_num = OVERLAY_SURFACE_5;
pipe->set_EDC_CHL_ADDR = set_EDC_CRSL_ADDR;
pipe->set_EDC_CHR_ADDR = set_EDC_CRSR_ADDR;
pipe->set_EDC_CH_CTL_ch_en = set_EDC_CRS_CTL_en;
pipe->set_EDC_CH_CTL_secu_line = set_EDC_CRS_CTL_secu_line;
pipe->set_EDC_CH_CTL_bgr = set_EDC_CRS_CTL_bgr;
pipe->set_EDC_CH_CTL_pix_fmt = set_EDC_CRS_CTL_pix_fmt;
pipe->set_EDC_CH_CTL_colork_en = set_EDC_CRS_CTL_colork_en;
pipe->set_EDC_CH_COLORK_MIN = set_EDC_CRS_COLORK_MIN;
pipe->set_EDC_CH_COLORK_MAX = set_EDC_CRS_COLORK_MAX;
pipe->set_EDC_CH_XY = set_EDC_CRS_XY;
pipe->set_EDC_CH_SIZE = set_EDC_CRS_SIZE;
pipe->set_EDC_CH_STRIDE = set_EDC_CRS_STRIDE;
/*begin support edc pixels algin modified by weiyi 00175802*/
#if defined(CONFIG_OVERLAY_PIXEL_ALIGN_SUPPORT)
pipe->set_EDC_CH_CLIP_bottom = set_EDC_CRS_CLIP_bottom_clip;
pipe->set_EDC_CH_CLIP_right = set_EDC_CRS_CLIP_right_clip;
pipe->set_EDC_CH_CLIP_left = set_EDC_CRS_CLIP_left_clip;
pipe->set_EDC_CH_CLIP_top = set_EDC_CRS_CLIP_top_clip;
#endif
/*end support edc pixels algin modified by weiyi 00175802*/
pipe->set_EDC_CH_CSCIDC_csc_en = NULL;
pipe->set_EDC_CH_CSCIDC = NULL;
pipe->set_EDC_CH_CSCODC = NULL;
pipe->set_EDC_CH_CSCP0 = NULL;
pipe->set_EDC_CH_CSCP1 = NULL;
pipe->set_EDC_CH_CSCP2 = NULL;
pipe->set_EDC_CH_CSCP3 = NULL;
pipe->set_EDC_CH_CSCP4 = NULL;
pipe->set_OVC_CH_CSCIDC = NULL;
pipe->set_OVC_CH_CSCODC = NULL;
pipe->set_OVC_CH_CSCP0 = NULL;
pipe->set_OVC_CH_CSCP1 = NULL;
pipe->set_OVC_CH_CSCP2 = NULL;
pipe->set_OVC_CH_CSCP3 = NULL;
pipe->set_OVC_CH_CSCP4 = NULL;
}
static void edc_overlay_pipe_init4gnew1(struct edc_overlay_pipe *pipe)
{
BUG_ON(pipe == NULL);
pipe->edc_ch_info.cap.ckey_enable = 0;
pipe->edc_ch_info.ckeymin = 0xffffcc;
pipe->edc_ch_info.ckeymax = 0xffffec;
pipe->edc_ch_info.cap.alpha_enable = 1;
pipe->edc_ch_info.alp_src = EDC_ALP_PIXEL;
pipe->edc_ch_info.alpha0 = 0x7f;
pipe->edc_ch_info.alpha1 = 0x7f;
pipe->edc_ch_info.cap.filter_enable = 0;
pipe->edc_ch_info.cap.csc_enable = 0;
/* added by gongyu for five edc layer compose */
pipe->req_info.overlay_num = OVERLAY_SURFACE_3;
pipe->set_EDC_CHL_ADDR = set_EDC_GNEW1_ADDR;
pipe->set_EDC_CHR_ADDR = NULL;
pipe->set_EDC_CH_CTL_ch_en = set_EDC_GNEW1_CTL_ch_en;
pipe->set_EDC_CH_CTL_secu_line = NULL;
pipe->set_EDC_CH_CTL_bgr = set_EDC_GNEW1_CTL_bgr;
pipe->set_EDC_CH_CTL_pix_fmt = set_EDC_GNEW1_CTL_pix_fmt;
pipe->set_EDC_CH_CTL_colork_en = NULL;
pipe->set_EDC_CH_COLORK_MIN = NULL;
pipe->set_EDC_CH_COLORK_MAX = NULL;
pipe->set_EDC_CH_XY = set_EDC_GNEW1_XY;
pipe->set_EDC_CH_SIZE = set_EDC_GNEW1_SIZE;
pipe->set_EDC_CH_STRIDE = set_EDC_GNEW1_STRIDE;
/*begin support edc pixels algin modified by weiyi 00175802*/
#if defined(CONFIG_OVERLAY_PIXEL_ALIGN_SUPPORT)
pipe->set_EDC_CH_CLIP_bottom = set_EDC_GNEW_CLIP_gnew1_bottom_clip;
pipe->set_EDC_CH_CLIP_right = set_EDC_GNEW_CLIP_gnew1_right_clip;
pipe->set_EDC_CH_CLIP_left = set_EDC_GNEW_CLIP_gnew1_left_clip;
pipe->set_EDC_CH_CLIP_top = set_EDC_GNEW_CLIP_gnew1_top_clip;
#endif
/*end support edc pixels algin modified by weiyi 00175802*/
pipe->set_EDC_CH_CSCIDC_csc_en = NULL;
pipe->set_EDC_CH_CSCIDC = NULL;
pipe->set_EDC_CH_CSCODC = NULL;
pipe->set_EDC_CH_CSCP0 = NULL;
pipe->set_EDC_CH_CSCP1 = NULL;
pipe->set_EDC_CH_CSCP2 = NULL;
pipe->set_EDC_CH_CSCP3 = NULL;
pipe->set_EDC_CH_CSCP4 = NULL;
pipe->set_OVC_CH_CSCIDC = NULL;
pipe->set_OVC_CH_CSCODC = NULL;
pipe->set_OVC_CH_CSCP0 = NULL;
pipe->set_OVC_CH_CSCP1 = NULL;
pipe->set_OVC_CH_CSCP2 = NULL;
pipe->set_OVC_CH_CSCP3 = NULL;
pipe->set_OVC_CH_CSCP4 = NULL;
}
static void edc_overlay_pipe_init4gnew2(struct edc_overlay_pipe *pipe)
{
BUG_ON(pipe == NULL);
pipe->edc_ch_info.cap.ckey_enable = 0;
pipe->edc_ch_info.ckeymin = 0xffffcc;
pipe->edc_ch_info.ckeymax = 0xffffec;
pipe->edc_ch_info.cap.alpha_enable = 1;
pipe->edc_ch_info.alp_src = EDC_ALP_PIXEL;
pipe->edc_ch_info.alpha0 = 0x7f;
pipe->edc_ch_info.alpha1 = 0x7f;
pipe->edc_ch_info.cap.filter_enable = 0;
pipe->edc_ch_info.cap.csc_enable = 0;
/* added by gongyu for five edc layer compose */
pipe->req_info.overlay_num = OVERLAY_SURFACE_4;
pipe->set_EDC_CHL_ADDR = set_EDC_GNEW2_ADDR;
pipe->set_EDC_CHR_ADDR = NULL;
pipe->set_EDC_CH_CTL_ch_en = set_EDC_GNEW2_CTL_ch_en;
pipe->set_EDC_CH_CTL_secu_line = NULL;
pipe->set_EDC_CH_CTL_bgr = set_EDC_GNEW2_CTL_bgr;
pipe->set_EDC_CH_CTL_pix_fmt = set_EDC_GNEW2_CTL_pix_fmt;
pipe->set_EDC_CH_CTL_colork_en = NULL;
pipe->set_EDC_CH_COLORK_MIN = NULL;
pipe->set_EDC_CH_COLORK_MAX = NULL;
pipe->set_EDC_CH_XY = set_EDC_GNEW2_XY;
pipe->set_EDC_CH_SIZE = set_EDC_GNEW2_SIZE;
pipe->set_EDC_CH_STRIDE = set_EDC_GNEW2_STRIDE;
/*begin support edc pixels algin modified by weiyi 00175802*/
#if defined(CONFIG_OVERLAY_PIXEL_ALIGN_SUPPORT)
pipe->set_EDC_CH_CLIP_bottom = set_EDC_GNEW_CLIP_gnew2_bottom_clip;
pipe->set_EDC_CH_CLIP_right = set_EDC_GNEW_CLIP_gnew2_right_clip;
pipe->set_EDC_CH_CLIP_left = set_EDC_GNEW_CLIP_gnew2_left_clip;
pipe->set_EDC_CH_CLIP_top = set_EDC_GNEW_CLIP_gnew2_top_clip;
#endif
/*end support edc pixels algin modified by weiyi 00175802*/
pipe->set_EDC_CH_CSCIDC_csc_en = NULL;
pipe->set_EDC_CH_CSCIDC = NULL;
pipe->set_EDC_CH_CSCODC = NULL;
pipe->set_EDC_CH_CSCP0 = NULL;
pipe->set_EDC_CH_CSCP1 = NULL;
pipe->set_EDC_CH_CSCP2 = NULL;
pipe->set_EDC_CH_CSCP3 = NULL;
pipe->set_EDC_CH_CSCP4 = NULL;
pipe->set_OVC_CH_CSCIDC = NULL;
pipe->set_OVC_CH_CSCODC = NULL;
pipe->set_OVC_CH_CSCP0 = NULL;
pipe->set_OVC_CH_CSCP1 = NULL;
pipe->set_OVC_CH_CSCP2 = NULL;
pipe->set_OVC_CH_CSCP3 = NULL;
pipe->set_OVC_CH_CSCP4 = NULL;
}
#endif //CONFIG_OVERLAY_COMPOSE
/* initialize infomation for 4 pipes of overlay*/
void edc_overlay_init(struct edc_overlay_ctrl *ctrl)
{
struct edc_overlay_pipe *pipe = NULL;
BUG_ON(ctrl == NULL);
pr_info("%s enter succ!\n",__func__);
pipe = &ctrl->plist[OVERLAY_PIPE_EDC0_CH1];
pipe->pipe_type = OVERLAY_TYPE_CHCAP_ALL,
pipe->pipe_num = OVERLAY_PIPE_EDC0_CH1,
pipe->edc_base = k3fd_reg_base_edc0,
edc_overlay_pipe_init4ch1(pipe);
pipe = &ctrl->plist[OVERLAY_PIPE_EDC0_CH2];
pipe->pipe_type = OVERLAY_TYPE_CHCAP_PARTIAL,
pipe->pipe_num = OVERLAY_PIPE_EDC0_CH2,
pipe->edc_base = k3fd_reg_base_edc0,
edc_overlay_pipe_init4ch2(pipe);
#if defined(CONFIG_OVERLAY_COMPOSE)
pipe = &ctrl->plist[OVERLAY_PIPE_EDC0_GNEW1];
pipe->pipe_type = OVERLAY_TYPE_CHCAP_PARTIAL,
pipe->pipe_num = OVERLAY_PIPE_EDC0_GNEW1,
pipe->edc_base = k3fd_reg_base_edc0,
edc_overlay_pipe_init4gnew1(pipe);
pipe = &ctrl->plist[OVERLAY_PIPE_EDC0_GNEW2];
pipe->pipe_type = OVERLAY_TYPE_CHCAP_PARTIAL,
pipe->pipe_num = OVERLAY_PIPE_EDC0_GNEW2,
pipe->edc_base = k3fd_reg_base_edc0,
edc_overlay_pipe_init4gnew2(pipe);
pipe = &ctrl->plist[OVERLAY_PIPE_EDC0_CURSOR];
pipe->pipe_type = OVERLAY_TYPE_CHCAP_PARTIAL,
pipe->pipe_num = OVERLAY_PIPE_EDC0_CURSOR,
pipe->edc_base = k3fd_reg_base_edc0,
edc_overlay_pipe_init4crs(pipe);
#endif //CONFIG_OVERLAY_COMPOSE
pipe = &ctrl->plist[OVERLAY_PIPE_EDC1_CH1];
pipe->pipe_type = OVERLAY_TYPE_CHCAP_ALL,
pipe->pipe_num = OVERLAY_PIPE_EDC1_CH1,
pipe->edc_base = k3fd_reg_base_edc1,
edc_overlay_pipe_init4ch1(pipe);
pipe = &ctrl->plist[OVERLAY_PIPE_EDC1_CH2];
pipe->pipe_type = OVERLAY_TYPE_CHCAP_PARTIAL,
pipe->pipe_num = OVERLAY_PIPE_EDC1_CH2,
pipe->edc_base = k3fd_reg_base_edc1,
edc_overlay_pipe_init4ch2(pipe);
pr_info("%s exit succ!\n",__func__);
}
struct edc_overlay_pipe *edc_overlay_ndx2pipe(struct fb_info *info, int ndx)
{
struct k3_fb_data_type *k3fd = NULL;
struct edc_overlay_ctrl *ctrl = NULL;
struct edc_overlay_pipe *pipe = NULL;
BUG_ON(info == NULL || info->par == NULL);
k3fd = (struct k3_fb_data_type *)info->par;
if (ndx < 0 || ndx >= OVERLAY_PIPE_MAX)
return NULL;
ctrl = &k3fd->ctrl;
pipe = &ctrl->plist[ndx];
return pipe;
}
int edc_overlay_get(struct fb_info *info, struct overlay_info *req)
{
struct edc_overlay_pipe *pipe = NULL;
BUG_ON(info == NULL || req == NULL);
pipe = edc_overlay_ndx2pipe(info, req->id);
if (pipe == NULL) {
k3fb_loge("id=%d not able to get pipe!\n", req->id);
return -ENODEV;
}
/* *req = pipe->req_info; */
memcpy(req, &pipe->req_info, sizeof(struct overlay_info));
return 0;
}
int edc_overlay_set(struct fb_info *info, struct overlay_info *req)
{
struct edc_overlay_pipe *pipe = NULL;
struct k3_fb_data_type *k3fd = NULL;
BUG_ON(info == NULL || req == NULL);
k3fd = (struct k3_fb_data_type *)info->par;
BUG_ON(k3fd == NULL);
pipe = edc_overlay_ndx2pipe(info, req->id);
if (pipe == NULL) {
k3fb_loge("id=%d not able to get pipe!\n", req->id);
return -ENODEV;
}
memcpy(&pipe->req_info, req, sizeof(struct overlay_info));
pipe->req_info.is_pipe_used = 1;
return 0;
}
void edc_overlay_ch_unset(struct edc_overlay_pipe *pipe, u32 edc_base)
{
if (NULL == pipe) {
k3fb_loge("invalid pipe!");
return;
}
/*begin support edc pixels algin modified by weiyi 00175802*/
#if defined(CONFIG_OVERLAY_PIXEL_ALIGN_SUPPORT)
pipe->set_EDC_CH_CLIP_bottom(edc_base,0x0);
pipe->set_EDC_CH_CLIP_right(edc_base,0x0);
pipe->set_EDC_CH_CLIP_left(edc_base,0x0);
pipe->set_EDC_CH_CLIP_top(edc_base,0x0);
#endif
/*end support edc pixels algin modified by weiyi 00175802*/
pipe->set_EDC_CHL_ADDR(edc_base, HISI_FRAME_BUFFER_BASE);
pipe->set_EDC_CH_XY(edc_base, 0x0, 0x0);
pipe->set_EDC_CH_SIZE(edc_base, 0x0, 0x0);
pipe->set_EDC_CH_STRIDE(edc_base, 0x0);
pipe->set_EDC_CH_CTL_bgr(edc_base, 0x0);
pipe->set_EDC_CH_CTL_pix_fmt(edc_base, 0x0);
pipe->set_EDC_CH_CTL_ch_en(edc_base, 0x0);
if (pipe->set_EDC_CHR_ADDR) {
pipe->set_EDC_CHR_ADDR(edc_base, 0x0);
}
if (pipe->set_EDC_CH_CTL_colork_en) {
pipe->set_EDC_CH_CTL_colork_en(edc_base, 0x0);
}
if (pipe->set_EDC_CH_COLORK_MIN) {
pipe->set_EDC_CH_COLORK_MIN(edc_base, 0x0);
}
if (pipe->set_EDC_CH_COLORK_MAX) {
pipe->set_EDC_CH_COLORK_MAX(edc_base, 0x0);
}
if (pipe->set_EDC_CH_CSCIDC_csc_en) {
pipe->set_EDC_CH_CSCIDC_csc_en(edc_base, 0x0);
}
if (pipe->set_EDC_CH_CSCIDC) {
pipe->set_EDC_CH_CSCIDC(edc_base, 0x0);
}
if (pipe->set_EDC_CH_CSCODC) {
pipe->set_EDC_CH_CSCODC(edc_base, 0x0);
}
if (pipe->set_EDC_CH_CSCP0) {
pipe->set_EDC_CH_CSCP0(edc_base, 0x0);
}
if (pipe->set_EDC_CH_CSCP1) {
pipe->set_EDC_CH_CSCP1(edc_base, 0x0);
}
if (pipe->set_EDC_CH_CSCP2) {
pipe->set_EDC_CH_CSCP2(edc_base, 0x0);
}
if (pipe->set_EDC_CH_CSCP3) {
pipe->set_EDC_CH_CSCP3(edc_base, 0x0);
}
if (pipe->set_EDC_CH_CSCP4) {
pipe->set_EDC_CH_CSCP4(edc_base, 0x0);
}
if (pipe->pipe_type == OVERLAY_TYPE_CHCAP_ALL) {
set_EDC_CH1_CTL_rot(edc_base, 0x0);
set_EDC_CH1_SCL_IRES(edc_base, 0x0, 0x0);
set_EDC_CH1_SCL_ORES(edc_base, 0x0, 0x0);
set_EDC_CH1_SCL_HSP_hsc_en(edc_base, 0x0);
set_EDC_CH1_SCL_HSP_hratio(edc_base, 0x0);
set_EDC_CH1_SCL_HSP_hafir_en(edc_base, 0x0);
set_EDC_CH1_SCL_HSP_hfir_en(edc_base, 0x0);
set_EDC_CH1_SCL_VSP_vsc_en(edc_base, 0x0);
set_EDC_CH1_SCL_VSR_vratio(edc_base, 0x0);
set_EDC_CH1_SCL_VSP_vafir_en(edc_base, 0x0);
set_EDC_CH1_SCL_VSP_vfir_en(edc_base, 0x0);
}
}
void edc_overlay_surface_unset(u32 edc_base, int overlay_num)
{
struct st_overlay_surf_reg_func *ovly_surf = NULL;
if (overlay_num < 0 || overlay_num > OVERLAY_SURFACE_MAX) {
k3fb_loge("invalid overlay_num! \n");
return;
}
ovly_surf = &(g_overlay_surf_func[overlay_num]);
if (ovly_surf == NULL) {
k3fb_loge("ovly_surf is null! \n");
return;
}
if (ovly_surf->set_overlay_src_blend_en) {
ovly_surf->set_overlay_src_blend_en(edc_base, 0x0);
}
if (ovly_surf->set_overlay_alpha_mode) {
ovly_surf->set_overlay_alpha_mode(edc_base, 0x0);
}
if (ovly_surf->set_overlay_under_alpha_sel) {
ovly_surf->set_overlay_under_alpha_sel(edc_base, 0x0);
}
if (ovly_surf->set_overlay_alpha_src) {
ovly_surf->set_overlay_alpha_src(edc_base, 0x0);
}
if (ovly_surf->set_overlay_alpha_sel) {
ovly_surf->set_overlay_alpha_sel(edc_base, 0x0);
}
if (ovly_surf->set_overlay_glp_alpha) {
ovly_surf->set_overlay_glp_alpha(edc_base, 0x0, 0x0);
}
if (ovly_surf->set_overlay_top) {
ovly_surf->set_overlay_top(edc_base, 0x1);
}
if (edc_base == k3fd_reg_base_edc0) {
set_EDC_CROSS_CTRL_default_val(edc_base);
}
}
int edc_overlay_unset(struct fb_info *info, int ndx)
{
struct edc_overlay_pipe *pipe = NULL;
struct k3_fb_data_type *k3fd = NULL;
u32 edc_base = 0;
int i = 0;
uint32_t ovly_surf_max = EDC1_OVERLAY_SURFACE_MAX;
uint32_t overlay_num;
BUG_ON(info == NULL || info->par == NULL);
k3fd = (struct k3_fb_data_type *)info->par;
BUG_ON(k3fd == NULL);
pipe = edc_overlay_ndx2pipe(info, ndx);
if (pipe == NULL) {
k3fb_loge("id=%d not able to get pipe!\n", ndx);
return -ENODEV;
}
overlay_num = pipe->req_info.overlay_num;
#if defined(CONFIG_OVERLAY_COMPOSE)
//unset it in pan display
if (pipe->req_info.is_overlay_compose) {
/* pipe->req_info.is_overlay_compose = 0; */
memset(&pipe->req_info, 0, sizeof(struct overlay_info));
pipe->req_info.need_unset = 1;
pipe->req_info.overlay_num = overlay_num;
return 0;
}
#endif
edc_base = pipe->edc_base;
down(&k3fd->sem);
memset(&pipe->req_info, 0, sizeof(struct overlay_info));
if (!k3fd->panel_power_on) {
up(&k3fd->sem);
k3fb_logw("id=%d has power down!\n", ndx);
return 0;
}
if (k3fd->panel_info.type == PANEL_MIPI_CMD) {
#if CLK_SWITCH
/* enable edc0 clk */
clk_enable(k3fd->edc_clk);
/* enable ldi clk */
clk_enable(k3fd->ldi_clk);
#endif
}
/* clear ch reg */
edc_overlay_ch_unset(pipe, edc_base);
if (k3fd_reg_base_edc0 == edc_base) {
ovly_surf_max = OVERLAY_SURFACE_MAX;
}
/* clear all ovlay_surface */
for (i = 0; i < ovly_surf_max; i++) {
edc_overlay_surface_unset(edc_base, i);
}
/* new add */
/* clear the record map to invalid value */
memset(&g_ovly2ch_map, OVERLAY_TO_CHANELL_MAP_INVALID, sizeof(g_ovly2ch_map));
set_EDC_DISP_CTL_cfg_ok(edc_base, EDC_CFG_OK_YES);
if (k3fd->panel_info.type == PANEL_MIPI_CMD) {
#if CLK_SWITCH
/* disable edc0 clk */
clk_disable(k3fd->edc_clk);
/* disable ldi clk */
clk_disable(k3fd->ldi_clk);
#endif
}
up(&k3fd->sem);
return 0;
}
#if defined(CONFIG_OVERLAY_COMPOSE)
#define EDC_BIT_MASK (0x1)
#define EDC_CFG_OK_BIT (1)
#define CH1_ROTATE_BIT (21)
#define CH1_EN_BIT (24)
#define CH2_EN_BIT (21)
#define CH2_FMT_BIT (16)
#define CH2_FMT_MASK (0x7)
#define CRS_EN_BIT (27)
#define GNEW1_EN_BIT (27)
#define GNEW2_EN_BIT (27)
#define EDC_CH_X_MASK (0xFFFFFFF)
#define EDC_CH_Y_MASK (0xFFF)
#define EDC_CH_BIT (16)
#define EDC_CH_WIDTH_MASK (0xFFFFFFF)
#define EDC_CH_HEIGHT_MASK (0xFFF)
#if defined(EDC_CH_CHG_SUPPORT)
enum {
CH_CHG_DISABLE,
CH_CHG_ENABLE
};
enum {
CFG_SEL_EDC1,
CFG_SEL_EDC0
};
#endif //EDC_CH_CHG_SUPPORT
volatile u32 edc_overlay_compose_get_cfg_ok(struct k3_fb_data_type *k3fd)
{
volatile u32 edc_ctl;
BUG_ON(k3fd == NULL);
edc_ctl = inp32(k3fd->edc_base + EDC_DISP_CTL_OFFSET);
return ((edc_ctl >> EDC_CFG_OK_BIT) & EDC_BIT_MASK);
}
volatile u32 edc_overlay_compose_reg_get_ch1_rotation(struct k3_fb_data_type *k3fd)
{
volatile u32 ch1_ctl;
BUG_ON(k3fd == NULL);
ch1_ctl = inp32(k3fd->edc_base + EDC_CH1_CTL_OFFSET);
return ((ch1_ctl >> CH1_ROTATE_BIT) & 0x3);
}
volatile u32 edc_overlay_compose_get_ch1_state(struct k3_fb_data_type *k3fd)
{
volatile u32 ch1_ctl;
BUG_ON(k3fd == NULL);
ch1_ctl = inp32(k3fd->edc_base + EDC_CH1_CTL_OFFSET);
return ((ch1_ctl >> CH1_EN_BIT) & EDC_BIT_MASK);
}
volatile u32 edc_overlay_compose_get_ch1_start_x(struct k3_fb_data_type *k3fd)
{
volatile u32 ch1_ctl;
BUG_ON(k3fd == NULL);
ch1_ctl = inp32(k3fd->edc_base + EDC_CH1_XY_OFFSET);
return ((ch1_ctl & EDC_CH_X_MASK) >> EDC_CH_BIT);
}
volatile u32 edc_overlay_compose_get_ch1_start_y(struct k3_fb_data_type *k3fd)
{
volatile u32 ch1_ctl;
BUG_ON(k3fd == NULL);
ch1_ctl = inp32(k3fd->edc_base + EDC_CH1_XY_OFFSET);
return (ch1_ctl & EDC_CH_Y_MASK);
}
volatile u32 edc_overlay_compose_get_ch1_width(struct k3_fb_data_type *k3fd)
{
volatile u32 ch1_ctl;
BUG_ON(k3fd == NULL);
ch1_ctl = inp32(k3fd->edc_base + EDC_CH1_SIZE_OFFSET);
return (((ch1_ctl & EDC_CH_WIDTH_MASK) >> EDC_CH_BIT) +1);
}
volatile u32 edc_overlay_compose_get_ch1_height(struct k3_fb_data_type *k3fd)
{
volatile u32 ch1_ctl;
BUG_ON(k3fd == NULL);
ch1_ctl = inp32(k3fd->edc_base + EDC_CH1_SIZE_OFFSET);
return ((ch1_ctl & EDC_CH_HEIGHT_MASK) +1);
}
volatile u32 edc_overlay_compose_get_ch2_state(struct k3_fb_data_type *k3fd)
{
volatile u32 ch2_ctl;
BUG_ON(k3fd == NULL);
ch2_ctl = inp32(k3fd->edc_base + EDC_CH2_CTL_OFFSET);
return ((ch2_ctl >> CH2_EN_BIT) & EDC_BIT_MASK);
}
volatile u32 edc_overlay_compose_get_ch2_start_x(struct k3_fb_data_type *k3fd)
{
volatile u32 ch2_ctl;
BUG_ON(k3fd == NULL);
ch2_ctl = inp32(k3fd->edc_base + EDC_CH2_XY_OFFSET);
return ((ch2_ctl & EDC_CH_X_MASK) >> EDC_CH_BIT);
}
volatile u32 edc_overlay_compose_get_ch2_start_y(struct k3_fb_data_type *k3fd)
{
volatile u32 ch2_ctl;
BUG_ON(k3fd == NULL);
ch2_ctl = inp32(k3fd->edc_base + EDC_CH2_XY_OFFSET);
return (ch2_ctl & EDC_CH_Y_MASK);
}
volatile u32 edc_overlay_compose_get_ch2_width(struct k3_fb_data_type *k3fd)
{
volatile u32 ch2_ctl;
BUG_ON(k3fd == NULL);
ch2_ctl = inp32(k3fd->edc_base + EDC_CH2_SIZE_OFFSET);
return (((ch2_ctl & EDC_CH_WIDTH_MASK) >> EDC_CH_BIT) +1);
}
volatile u32 edc_overlay_compose_get_ch2_height(struct k3_fb_data_type *k3fd)
{
volatile u32 ch2_ctl;
BUG_ON(k3fd == NULL);
ch2_ctl = inp32(k3fd->edc_base + EDC_CH2_SIZE_OFFSET);
return ((ch2_ctl & EDC_CH_HEIGHT_MASK) +1);
}
volatile u32 edc_overlay_compose_get_ch2_fmt(struct k3_fb_data_type *k3fd)
{
volatile u32 ch2_ctl;
BUG_ON(k3fd == NULL);
ch2_ctl = inp32(k3fd->edc_base + EDC_CH2_CTL_OFFSET);
return ((ch2_ctl >> CH2_FMT_BIT) & CH2_FMT_MASK);
}
volatile u32 edc_overlay_compose_get_crs_state(struct k3_fb_data_type *k3fd)
{
volatile u32 crs_ctl;
BUG_ON(k3fd == NULL);
crs_ctl = inp32(k3fd->edc_base + EDC_CRS_CTL_OFFSET);
return ((crs_ctl >> CRS_EN_BIT) & EDC_BIT_MASK);
}
volatile u32 edc_overlay_compose_get_gnew1_state(struct k3_fb_data_type *k3fd)
{
volatile u32 gnew1_ctl;
BUG_ON(k3fd == NULL);
gnew1_ctl = inp32(k3fd->edc_base + EDC_GNEW1_CTL_OFFSET);
return ((gnew1_ctl >> GNEW1_EN_BIT) & EDC_BIT_MASK);
}
volatile u32 edc_overlay_compose_get_gnew1_start_x(struct k3_fb_data_type *k3fd)
{
volatile u32 gnew1_ctl;
BUG_ON(k3fd == NULL);
gnew1_ctl = inp32(k3fd->edc_base + EDC_GNEW1_XY_OFFSET);
return ((gnew1_ctl & EDC_CH_X_MASK) >> EDC_CH_BIT);
}
volatile u32 edc_overlay_compose_get_gnew1_start_y(struct k3_fb_data_type *k3fd)
{
volatile u32 gnew1_ctl;
BUG_ON(k3fd == NULL);
gnew1_ctl = inp32(k3fd->edc_base + EDC_GNEW1_XY_OFFSET);
return (gnew1_ctl & EDC_CH_Y_MASK);
}
volatile u32 edc_overlay_compose_get_gnew1_width(struct k3_fb_data_type *k3fd)
{
volatile u32 gnew1_ctl;
BUG_ON(k3fd == NULL);
gnew1_ctl = inp32(k3fd->edc_base + EDC_GNEW1_SIZE_OFFSET);
return (((gnew1_ctl & EDC_CH_WIDTH_MASK) >> EDC_CH_BIT) +1);
}
volatile u32 edc_overlay_compose_get_gnew1_height(struct k3_fb_data_type *k3fd)
{
volatile u32 gnew1_ctl;
BUG_ON(k3fd == NULL);
gnew1_ctl = inp32(k3fd->edc_base + EDC_GNEW1_SIZE_OFFSET);
return ((gnew1_ctl & EDC_CH_HEIGHT_MASK) +1);
}
volatile u32 edc_overlay_compose_get_gnew2_state(struct k3_fb_data_type *k3fd)
{
volatile u32 gnew2_ctl;
BUG_ON(k3fd == NULL);
gnew2_ctl = inp32(k3fd->edc_base + EDC_GNEW2_CTL_OFFSET);
return ((gnew2_ctl >> GNEW2_EN_BIT) & EDC_BIT_MASK);
}
volatile u32 edc_overlay_compose_get_gnew2_start_x(struct k3_fb_data_type *k3fd)
{
volatile u32 gnew2_ctl;
BUG_ON(k3fd == NULL);
gnew2_ctl = inp32(k3fd->edc_base + EDC_GNEW2_XY_OFFSET);
return ((gnew2_ctl & EDC_CH_X_MASK) >> EDC_CH_BIT);
}
volatile u32 edc_overlay_compose_get_gnew2_start_y(struct k3_fb_data_type *k3fd)
{
volatile u32 gnew2_ctl;
BUG_ON(k3fd == NULL);
gnew2_ctl = inp32(k3fd->edc_base + EDC_GNEW2_XY_OFFSET);
return (gnew2_ctl & EDC_CH_Y_MASK);
}
volatile u32 edc_overlay_compose_get_gnew2_width(struct k3_fb_data_type *k3fd)
{
volatile u32 gnew2_ctl;
BUG_ON(k3fd == NULL);
gnew2_ctl = inp32(k3fd->edc_base + EDC_GNEW2_SIZE_OFFSET);
return (((gnew2_ctl & EDC_CH_WIDTH_MASK) >> EDC_CH_BIT) +1);
}
volatile u32 edc_overlay_compose_get_gnew2_height(struct k3_fb_data_type *k3fd)
{
volatile u32 gnew2_ctl;
BUG_ON(k3fd == NULL);
gnew2_ctl = inp32(k3fd->edc_base + EDC_GNEW2_SIZE_OFFSET);
return ((gnew2_ctl & EDC_CH_HEIGHT_MASK) +1);
}
u32 edc_overlay_compose_get_state(struct fb_info *info, u32 pipe_id)
{
struct edc_overlay_pipe *pipe = NULL;
pipe = edc_overlay_ndx2pipe(info, pipe_id);
if (pipe == NULL) {
k3fb_loge("id=%d not able to get pipe!", pipe_id);
return 0;
}
return pipe->req_info.is_overlay_compose;
}
bool edc_overlay_compose_get_overlay_0_ch(struct fb_info *info, u32 pipe_id)
{
struct edc_overlay_pipe *pipe = NULL;
pipe = edc_overlay_ndx2pipe(info, pipe_id);
if (pipe == NULL) {
k3fb_loge("id=%d not able to get pipe!", pipe_id);
return 0;
}
return pipe->req_info.overlay_num == OVERLAY_SURFACE_1 ? true : false;
}
u32 edc_overlay_compose_get_cfg_disable(struct fb_info *info, u32 pipe_id)
{
struct edc_overlay_pipe *pipe = NULL;
pipe = edc_overlay_ndx2pipe(info, pipe_id);
if (pipe == NULL) {
k3fb_loge("id=%d not able to get pipe!", pipe_id);
return 1;
}
return pipe->req_info.cfg_disable;
}
u32 edc_overlay_compose_get_ch1_rotation(struct fb_info *info, u32 pipe_id)
{
struct edc_overlay_pipe *pipe = NULL;
pipe = edc_overlay_ndx2pipe(info, pipe_id);
if (pipe == NULL) {
k3fb_loge("id=%d not able to get pipe!", pipe_id);
return 0;
}
return pipe->req_info.rotation;
}
int edc_overlay_compose_set_cross(int overlay, int ch)
{
int i;
for (i = 0; i < (OVERLAY_SURFACE_MAX - 1); i++) {
if (g_ovly2ch_map[i] == ch) {
k3fb_loge("The cross channel[%d] overlay[%d] selected has already been used! at g_ovly2ch_map[%d] \n"
, ch, overlay,i);
return -EINVAL;
}
}
if (g_ovly2ch_map[overlay] != OVERLAY_TO_CHANELL_MAP_INVALID) {
k3fb_loge("Overlay[%d] has already selected channel[%d]"
, overlay, g_ovly2ch_map[overlay]);
return -EINVAL;
}
g_ovly2ch_map[overlay] = ch;
return 0;
}
/* check the cross ctl req, make sure don't have same value for ovlys,
* before display, have clear the cross ctl to 0 in edc_overlay_surface_unset function.
*/
void edc_overlay_compose_check_cross_ctl(u32 edc_base)
{
int i;
int j;
int ch_left[OVERLAY_SURFACE_MAX - 1];
EDC_CROSS_CTL_VALUE cross_value;
for (i = 0; i < (OVERLAY_SURFACE_MAX - 1); i++) {
ch_left[i] = i;
}
// Find and record which channel has been not selected, update ch_left[]
for (i = 0; i < (OVERLAY_SURFACE_MAX - 1); i++) {
for (j = 0; j < (OVERLAY_SURFACE_MAX - 1); j++) {
if (g_ovly2ch_map[i] == j) {
if (ch_left[j] != OVERLAY_TO_CHANELL_MAP_INVALID) {
// Mark the channel that has been selected
// with OVERLAY_TO_CHANELL_MAP_INVALID
ch_left[j] = OVERLAY_TO_CHANELL_MAP_INVALID;
} else {
// This channel already has been used,
// so clear this element of g_ovly2ch_map[]
// to fill with new distinct value later.
g_ovly2ch_map[i] = OVERLAY_TO_CHANELL_MAP_INVALID;
}
}
}
}
j = 0;
for (i = 0; i < (OVERLAY_SURFACE_MAX - 1); i++) {
if (OVERLAY_TO_CHANELL_MAP_INVALID == g_ovly2ch_map[i]) {
for (; j < (OVERLAY_SURFACE_MAX - 1); j++) {
if (ch_left[j] != OVERLAY_TO_CHANELL_MAP_INVALID) {
g_ovly2ch_map[i] = ch_left[j++];
break;
}
}
}
}
cross_value.bits.ovly1_sel = g_ovly2ch_map[0];
cross_value.bits.ovly2_sel = g_ovly2ch_map[1];
cross_value.bits.ovly3_sel = g_ovly2ch_map[2];
cross_value.bits.ovly4_sel = g_ovly2ch_map[3];
outp32(edc_base + EDC_CROSS_CTL_OFFSET, cross_value.ul32);
}
static void edc_overlay_compose_graphic_alpha_set(struct overlay_data *req, u32 edc_base, struct st_overlay_surf_reg_func *pst_overlay_func)
{
#define HWC_BLENDING_PREMULT (0x0105)
#define HWC_BLENDING_COVERAGE (0x0405)
int32_t blending;
/* Get perpixelAlpha enabling state. */
bool perpixelAlpha;
/* Get plane alpha value. */
u32 planeAlpha;
if ((NULL == pst_overlay_func) || (NULL == req)) {
k3fb_loge("para is null,pst_overlay_func = %x, req = %x \n",(uint32_t)pst_overlay_func, (uint32_t)req);
return;
}
blending = req->src.blending;
planeAlpha = blending >> 16;
perpixelAlpha = isAlphaRGBType(req->src.format);
k3fb_logi_display_debugfs("req->id = %d, blending = %d, perpixelAlpha = %d \n", req->id, blending, perpixelAlpha);
switch (blending & 0xFFFF)
{
case HWC_BLENDING_PREMULT:
SET_OVERLAY_SRC_BLEND_EN(pst_overlay_func, edc_base, K3_ENABLE);
if (perpixelAlpha) {
SET_OVERLAY_ALPHA_MODE(pst_overlay_func, edc_base, EDC_ALP_PIXEL);
SET_OVERLAY_ALPHA_SRC(pst_overlay_func, edc_base, EDC_PIX_ALP_SRC_CH2);
SET_OVERLAY_UNDER_ALPH_SEL(pst_overlay_func, edc_base, EDC_ALP_MUL_COEFF_1);
SET_OVERLAY_ALPHA_SEL(pst_overlay_func, edc_base, EDC_ALP_MUL_COEFF_3);
} else if (planeAlpha < 0xFF) {
SET_OVERLAY_ALPHA_MODE(pst_overlay_func, edc_base, EDC_ALP_GLOBAL);
SET_OVERLAY_GLP_ALPHA(pst_overlay_func, edc_base, planeAlpha, 0);
SET_OVERLAY_UNDER_ALPH_SEL(pst_overlay_func, edc_base, EDC_ALP_MUL_COEFF_1);
SET_OVERLAY_ALPHA_SEL(pst_overlay_func, edc_base, EDC_ALP_MUL_COEFF_0);
} else {
SET_OVERLAY_SRC_BLEND_EN(pst_overlay_func, edc_base, K3_DISABLE);
}
break;
case HWC_BLENDING_COVERAGE:
SET_OVERLAY_SRC_BLEND_EN(pst_overlay_func, edc_base, K3_ENABLE);
if (perpixelAlpha) {
SET_OVERLAY_ALPHA_MODE(pst_overlay_func, edc_base, EDC_ALP_PIXEL);
SET_OVERLAY_ALPHA_SRC(pst_overlay_func, edc_base, EDC_PIX_ALP_SRC_CH2);
SET_OVERLAY_UNDER_ALPH_SEL(pst_overlay_func, edc_base, EDC_ALP_MUL_COEFF_1);
SET_OVERLAY_ALPHA_SEL(pst_overlay_func, edc_base, EDC_ALP_MUL_COEFF_0);
} else if (planeAlpha < 0xFF) {
SET_OVERLAY_ALPHA_MODE(pst_overlay_func, edc_base, EDC_ALP_GLOBAL);
SET_OVERLAY_GLP_ALPHA(pst_overlay_func, edc_base, planeAlpha, 0);
SET_OVERLAY_UNDER_ALPH_SEL(pst_overlay_func, edc_base, EDC_ALP_MUL_COEFF_1);
SET_OVERLAY_ALPHA_SEL(pst_overlay_func, edc_base, EDC_ALP_MUL_COEFF_0);
} else {
SET_OVERLAY_SRC_BLEND_EN(pst_overlay_func, edc_base, K3_DISABLE);
}
break;
default:
SET_OVERLAY_SRC_BLEND_EN(pst_overlay_func, edc_base, K3_DISABLE);
break;
}
}
#if 0
static void edc_overlay_compose_partial_graphic_alpha_set(struct overlay_info *req_info, u32 edc_base)
{
struct st_overlay_surf_reg_func *pst_overlay_func = NULL;
struct overlay_data req;
if (NULL == req_info) {
k3fb_loge("req_info is null \n");
return;
}
if (req_info->partial_overlay_num >= OVERLAY_SURFACE_MAX) {
k3fb_loge("req_info overlay_num %d is overflow \n", req_info->partial_overlay_num);
return;
}
pst_overlay_func = &(g_overlay_surf_func[req_info->partial_overlay_num]);
req.id = req_info->partial_ch_num;
req.src.blending = req_info->partial_blending;
req.src.format = req_info->partial_format;
edc_overlay_compose_graphic_alpha_set(&req, edc_base, pst_overlay_func);
}
/* compose_pan_display, must be last channel, and this channel will not get overlay_num for cross switch
* so, must calculate the overlay_num from the other three channel.
*
*/
int edc_overlay_compose_pan_display_ovly_surf_set(struct overlay_info *req_info, u32 edc_base)
{
int ret = 0;
struct st_overlay_surf_reg_func *overlay_surf_func = NULL;
if (NULL == req_info) {
k3fb_loge("req_info is null \n");
return -EINVAL;
}
/* set pan display ovly_num */
if (req_info->partial_overlay_num >= OVERLAY_SURFACE_MAX) {
k3fb_loge("overlay_num %d is overflow \n", req_info->partial_overlay_num);
return -EOVERFLOW;
}
overlay_surf_func = &(g_overlay_surf_func[req_info->partial_overlay_num]);
if (overlay_surf_func->set_overlay_cross_switch_sel) {
ret = edc_overlay_compose_set_cross(req_info->partial_overlay_num, req_info->partial_ch_num);
if (ret < 0) {
/* clear the record map to invalid value */
memset(&g_ovly2ch_map, OVERLAY_TO_CHANELL_MAP_INVALID, sizeof(g_ovly2ch_map));
k3fb_loge("edc_overlay_compose_set_cross is error \n");
return -EINVAL;
}
}
/* must sure the cross ctl config value don't have conflict */
edc_overlay_compose_check_cross_ctl(edc_base);
return ret;
}
#endif
static void edc_overlay_compose_ch_csc_unset(struct edc_overlay_pipe *pipe, u32 edc_base)
{
if (pipe == NULL) {
k3fb_loge("invalid pipe!");
return;
}
if (pipe->set_EDC_CH_CSCIDC_csc_en) {
pipe->set_EDC_CH_CSCIDC_csc_en(edc_base, 0x0);
}
if (pipe->set_OVC_CH_CSCIDC) {
pipe->set_OVC_CH_CSCIDC(edc_base, 0x0, 0x0, 0x0);
}
if (pipe->set_OVC_CH_CSCODC) {
pipe->set_OVC_CH_CSCODC(edc_base, 0x0, 0x0, 0x0);
}
if (pipe->set_OVC_CH_CSCP0) {
pipe->set_OVC_CH_CSCP0(edc_base, 0x0, 0x0);
}
if (pipe->set_OVC_CH_CSCP1) {
pipe->set_OVC_CH_CSCP1(edc_base, 0x0, 0x0);
}
if (pipe->set_OVC_CH_CSCP2) {
pipe->set_OVC_CH_CSCP2(edc_base, 0x0, 0x0);
}
if (pipe->set_OVC_CH_CSCP3) {
pipe->set_OVC_CH_CSCP3(edc_base, 0x0, 0x0);
}
if (pipe->set_OVC_CH_CSCP4) {
pipe->set_OVC_CH_CSCP4(edc_base, 0x0);
}
}
void edc_overlay_compose_pre_unset(struct fb_info *info, int ndx)
{
struct edc_overlay_pipe *pipe = NULL;
BUG_ON(info == NULL);
pipe = edc_overlay_ndx2pipe(info, ndx);
if (pipe == NULL) {
k3fb_loge("id=%d not able to get pipe!\n", ndx);
return;
}
//unset it in cfg ok
if (pipe->req_info.is_overlay_compose) {
/* pipe->req_info.is_overlay_compose = 0; */
memset(&pipe->req_info, 0, sizeof(struct overlay_info));
pipe->req_info.need_unset = 1;
}
}
static int edc_overlay_compose_pipe_unset(struct fb_info *info)
{
struct edc_overlay_pipe *pipe = NULL;
u32 edc_base = 0;
int ch_id;
BUG_ON(info == NULL || info->par == NULL);
for (ch_id = 0; ch_id < OVERLAY_PIPE_MAX; ch_id++) {
pipe = edc_overlay_ndx2pipe(info, ch_id);
if (pipe == NULL) {
k3fb_loge("id=%d not able to get pipe!", ch_id);
return -ENODEV;
}
edc_base = pipe->edc_base;
if (pipe->req_info.need_unset) {
pipe->req_info.need_unset = 0;
/* memset(&pipe->req_info, 0, sizeof(struct overlay_info)); */
edc_overlay_ch_unset(pipe, edc_base);
/* clear overlay surface reg, don't clear pipe->req_info.overlay_num,
* because, if clear overlay_num, compose_play will get error overlay_num
*/
edc_overlay_surface_unset(edc_base, pipe->req_info.overlay_num);
}
}
return 0;
}
int edc_overlay_compose_ch_unset(struct fb_info *info, int ndx)
{
struct edc_overlay_pipe *pipe = NULL;
u32 edc_base = 0;
BUG_ON(info == NULL || info->par == NULL);
pipe = edc_overlay_ndx2pipe(info, ndx);
if (pipe == NULL) {
k3fb_loge("id=%d not able to get pipe!", ndx);
return -ENODEV;
}
edc_base = pipe->edc_base;
if (pipe->req_info.need_unset) {
pipe->req_info.need_unset = 0;
edc_overlay_ch_unset(pipe, edc_base);
edc_overlay_surface_unset(edc_base, pipe->req_info.overlay_num);
}
return 0;
}
static int edc_overlay_compose_g2d_unset(struct fb_info *info)
{
struct k3_fb_data_type *k3fd = NULL;
struct edc_overlay_pipe *pipe = NULL;
u32 edc_base = 0;
int ch_id;
BUG_ON(info == NULL || info->par == NULL);
k3fd = (struct k3_fb_data_type *)info->par;
/* reset ovc state */
for (ch_id = 0; ch_id < OVERLAY_PIPE_MAX; ch_id++) {
pipe = edc_overlay_ndx2pipe(info, ch_id);
if (pipe == NULL) {
k3fb_loge("id=%d not able to get ovc pipe!", ch_id);
return -ENODEV;
}
edc_base = pipe->edc_base;
if (pipe->req_info.need_unset) {
pipe->req_info.need_unset = 0;
}
if ((OVERLAY_PIPE_EDC0_CURSOR == ch_id) || (k3fd->graphic_ch == ch_id)) {
edc_base = pipe->edc_base;
/*begin support edc pixels algin modified by weiyi 00175802*/
#if defined(CONFIG_OVERLAY_PIXEL_ALIGN_SUPPORT)
pipe->set_EDC_CH_CLIP_bottom(edc_base,0x0);
pipe->set_EDC_CH_CLIP_right(edc_base,0x0);
pipe->set_EDC_CH_CLIP_left(edc_base,0x0);
pipe->set_EDC_CH_CLIP_top(edc_base,0x0);
#endif
/*end support edc pixels algin modified by weiyi 00175802*/
pipe->set_EDC_CHL_ADDR(edc_base, HISI_FRAME_BUFFER_BASE);
pipe->set_EDC_CHR_ADDR(edc_base, HISI_FRAME_BUFFER_BASE);
pipe->set_EDC_CH_XY(edc_base, 0x0, 0x0);
pipe->set_EDC_CH_SIZE(edc_base, 0x0, 0x0);
pipe->set_EDC_CH_STRIDE(edc_base, 0x0);
pipe->set_EDC_CH_CTL_pix_fmt(edc_base, 0x0);
pipe->set_EDC_CH_CTL_bgr(edc_base, 0x0);
pipe->set_EDC_CH_CTL_colork_en(edc_base, 0x0);
pipe->set_EDC_CH_CTL_ch_en(edc_base, 0x0);
}
}
return 0;
}
int edc_overlay_compose_pipe_unset_previous(struct fb_info *info, u32 previous_type, u32 previous_count)
{
struct k3_fb_data_type *k3fd = NULL;
BUG_ON(info == NULL || info->par == NULL);
k3fd = (struct k3_fb_data_type *)info->par;
switch (previous_type) {
case OVC_FULL:
edc_overlay_compose_pipe_unset(info);
break;
case OVC_PARTIAL:
edc_overlay_compose_pipe_unset(info);
edc_overlay_compose_g2d_unset(info);
break;
case OVC_NONE:
edc_overlay_compose_g2d_unset(info);
break;
default:
k3fb_loge("previous_type default!!!");
break;
}
//edc_overlay_compose_pipe_unset(info);
return 0;
}
#if defined(EDC_CH_CHG_SUPPORT)
static int overlay_compose_get_edc1_hw(struct clk **edc_clk, struct regulator **edc_vcc)
{
*edc_clk = clk_get(NULL, CLK_EDC1_NAME);
if (IS_ERR(*edc_clk)) {
k3fb_loge("failed to get edc1_clk!\n");
return -EINVAL;
}
*edc_vcc = regulator_get(NULL, VCC_EDC1_NAME);
if (IS_ERR(*edc_vcc)) {
k3fb_loge("failed to get edc1-vcc regulator\n");
return -EINVAL;
}
return 0;
}
static void overlay_compose_edc1_power_on(struct k3_fb_data_type *k3fd)
{
struct clk *edc1_clk;
struct regulator *edc1_vcc;
if (overlay_compose_get_edc1_hw(&edc1_clk, &edc1_vcc) < 0) {
k3fb_loge("failed to get edc1 para.\n");
}
/* edc1 vcc */
if (regulator_enable(edc1_vcc) != 0) {
k3fb_loge("failed to enable edc-vcc regulator.\n");
}
/* edc clock enable */
if (clk_enable(edc1_clk) != 0) {
k3fb_loge("failed to enable edc1 clock.\n");
}
/* Note: call clk_set_rate after clk_set_rate, set edc clock rate to normal value */
//edc1 clk uses edc0's rate !
if (clk_set_rate(edc1_clk, EDC_CORE_CLK_RATE) != 0) {
k3fb_loge("failed to set edc1 clk rate(%d).\n", EDC_CORE_CLK_RATE);
}
}
void overlay_compose_edc1_power_off(void)
{
struct clk *edc1_clk;
struct regulator *edc1_vcc;
if (overlay_compose_get_edc1_hw(&edc1_clk, &edc1_vcc) < 0) {
k3fb_loge("failed to get edc1 para.\n");
}
/* edc clock gating */
clk_disable(edc1_clk);
/* edc1 vcc */
if (regulator_disable(edc1_vcc) != 0) {
k3fb_loge("failed to disable edc-vcc regulator.\n");
}
}
int edc_overlay_compose_ch_chg_disable(struct k3_fb_data_type *k3fd, struct fb_info *info)
{
//edc0
struct edc_overlay_pipe *edc0_pipe = NULL;
u32 edc0_base = 0;
//edc1
struct fb_info* info1 = k3_fb1_get_info();
struct edc_overlay_pipe *edc1_pipe = NULL;
u32 edc1_base = 0;
//edc0
BUG_ON(info == NULL || info->par == NULL);
if (!k3fd->ch_chg_flag) {
return 0;
}
k3fd->ch_chg_flag = false;
k3fd->ch_chg_power_off = true;
edc0_pipe = edc_overlay_ndx2pipe(info, OVERLAY_PIPE_EDC0_CH2);
if (edc0_pipe == NULL) {
k3fb_loge("OVERLAY_PIPE_EDC0_CH2 not able to get pipe!");
return -ENODEV;
}
edc0_base = edc0_pipe->edc_base;
//edc1
BUG_ON(info1 == NULL || info1->par == NULL);
edc1_pipe = edc_overlay_ndx2pipe(info1, OVERLAY_PIPE_EDC1_CH1);
if (edc1_pipe == NULL) {
k3fb_loge("OVERLAY_PIPE_EDC1_CH1 not able to get pipe!");
return -ENODEV;
}
edc1_base = edc1_pipe->edc_base;
edc1_pipe->set_EDC_CH_CTL_ch_en(edc1_base, K3_DISABLE);
set_EDC_DISP_CTL_ch_chg(edc0_base, CH_CHG_DISABLE);
set_EDC_DISP_CTL_cfg_ok_sel(edc0_base, CFG_SEL_EDC1);
return 0;
}
static int edc_overlay_compose_ch_chg_enable(struct k3_fb_data_type *k3fd)
{
if (k3fd->ch_chg_flag) {
return 0;
}
k3fd->ch_chg_flag = true;
overlay_compose_edc1_power_on(k3fd);
return 0;
}
#endif //EDC_CH_CHG_SUPPORT
int edc_overlay_compose_play(struct fb_info *info, struct overlay_data *req)
{
struct edc_overlay_pipe *pipe = NULL;
struct k3_fb_data_type *k3fd = NULL;
struct overlay_info *ov_info = NULL;
struct st_overlay_surf_reg_func *pst_overlay_func = NULL;
struct k3fb_rect src;
/*struct k3fb_rect logic_rect;*/
struct k3fb_rect dst; /* physic */
u32 edc0_base = 0;
struct edc_overlay_pipe *edc0_pipe = NULL;
u32 edc_base = 0;
int i = 0;
int j = 0;
s16 stSCLHorzCoef[8][8] = {{0},};
s16 stSCLVertCoef[16][4] = {{0},};
u32 scl_ratio_w = 0;
u32 scl_ratio_h = 0;
u32 addr = 0;
#define MAX_EDC_W (1920)
#define MAX_EDC_H (1200)
u32 max_w;
u32 max_h;
bool is_rotate = false;
u32 cfg_disable;
#if defined(EDC_CH_CHG_SUPPORT)
//edc1
struct k3_fb_data_type *k3fd1 = NULL;
struct fb_info* info1 = k3_fb1_get_info();
struct edc_overlay_pipe *edc1_pipe = NULL;
u32 edc1_base = 0;
bool ch_chg = false;
#endif //EDC_CH_CHG_SUPPORT
#if defined(CONFIG_OVERLAY_PIXEL_ALIGN_SUPPORT)
//addr align begin
uint32_t left_clip = 0;
uint32_t right_clip = 0;
uint32_t top_clip = 0;
uint32_t bottom_clip = 0;
struct k3fb_rect src_temp;
//end
#endif
BUG_ON(info == NULL || info->par == NULL || req == NULL);
#ifdef DEBUG_ON
printk(
"\nDUMP overlay play:\n"
"type=%d\n"
"phy_addr=%x\n"
"actual_width=%d\n"
"actual_height=%d\n"
"format=%d\n"
"s3d_format=%d\n"
"stride=%d\n"
"width=%d\n"
"height=%d\n"
"id=%d\n"
"is_graphic=%d\n",
req->src.type,
req->src.phy_addr,
req->src.actual_width,
req->src.actual_height,
req->src.format,
req->src.s3d_format,
req->src.stride,
req->src.width,
req->src.height,
req->id,
req->is_graphic);
#endif
k3fd = (struct k3_fb_data_type *)info->par;
edc0_pipe = edc_overlay_ndx2pipe(info, req->id);
if (edc0_pipe == NULL) {
k3fb_loge("id=%d not able to get pipe!", req->id);
return -ENODEV;
}
//set to edc0
pipe = edc0_pipe;
/* stride 64byte odd align */
if (!is64BytesOddAlign(FB_64BYTES_ODD_ALIGN_NONE, req->src.stride)) {
k3fb_logw("stride NOT 64 bytes odd aligned, %x\n", req->src.stride);
return -EINVAL;
}
if (pipe->req_info.dst_rect.w == 0 ||
pipe->req_info.dst_rect.h == 0 ||
pipe->req_info.src_rect.w == 0 ||
pipe->req_info.src_rect.h == 0) {
k3fb_logw("invalid width or height! dst(%d,%d), src(%d,%d)",
pipe->req_info.dst_rect.w, pipe->req_info.dst_rect.h,
pipe->req_info.src_rect.w, pipe->req_info.src_rect.h);
return -EINVAL;
}
edc0_base = pipe->edc_base;
//set to edc0
edc_base = edc0_base;
ov_info = &pipe->req_info;
cfg_disable = pipe->req_info.cfg_disable;
#ifdef DEBUG_ON
printk("cfg_disable=%d\n",cfg_disable);
#endif
if (((req->id)!= OVERLAY_PIPE_EDC0_CH1) && ((req->id)!= OVERLAY_PIPE_EDC1_CH1)) {
ov_info->rotation = EDC_ROT_NOP;
}
is_rotate = ((ov_info->rotation == EDC_ROT_90) || (ov_info->rotation == EDC_ROT_270));
if (k3fd->panel_info.orientation == LCD_LANDSCAPE) {
max_w = is_rotate ? MAX_EDC_H : MAX_EDC_W;
max_h = is_rotate ? MAX_EDC_W : MAX_EDC_H;
}
else {
max_w = is_rotate ? MAX_EDC_W : MAX_EDC_H;
max_h = is_rotate ? MAX_EDC_H : MAX_EDC_W;
}
src.x = ov_info->src_rect.x;
src.y = ov_info->src_rect.y;
if ((ov_info->src_rect.w * ov_info->src_rect.h) <= (max_w * max_h)) {
src.w = ov_info->src_rect.w;
src.h = ov_info->src_rect.h;
}
else {
src.w = ov_info->src_rect.w = max_w;
src.h = ov_info->src_rect.h = max_h;
}
dst = ov_info->dst_rect;
#ifdef DEBUG_ON
printk("scr(%d,%d,%d,%d) ==> dst(%d,%d,%d,%d), clip_right=%d, clip_bottom = %d\n",src.x,src.y,src.w,src.h, dst.x,dst.y,dst.w,dst.h, ov_info->clip_right, ov_info->clip_bottom);
#endif
#if defined(CONFIG_OVERLAY_PIXEL_ALIGN_SUPPORT)
computeAlignSrc(&(req->src), ov_info, &src, &src_temp);
left_clip = src.x - src_temp.x;
right_clip = ov_info->clip_right;
top_clip = src.y - src_temp.y;
bottom_clip = ov_info->clip_bottom;
//printk("clip(%d,%d,%d,%d)\n", left_clip, top_clip, right_clip, bottom_clip);
src.x = src_temp.x;
src.y = src_temp.y;
src.w = ov_info->src_rect.w = src_temp.w;
src.h = ov_info->src_rect.h = src_temp.h;
//printk("scr(%d,%d,%d,%d) ==> dst(%d,%d,%d,%d), clip_right=%d, clip_bottom = %d, left_clip\n",src.x,src.y,src.w,src.h, dst.x,dst.y,dst.w,dst.h, ov_info->clip_right, ov_info->clip_bottom, left_clip);
#endif
/*computeDisplayRegion(&(req->src), k3fd->panel_info.orientation,
&(ov_info->dst_rect), &logic_rect);
logic2physicCoordinate(ov_info->rotation, &logic_rect, &dst);*/
addr = computeDisplayAddr(&(req->src), ov_info->rotation, &src);
//128bit(16byte) align
if (addr & 0x0f) {
k3fb_logw("addr NOT 64 bytes aligned, %x\n", addr);
return -EINVAL;
}
if (!ov_info->is_pipe_used) {
return 0;
}
if (!k3fd->panel_power_on) {
return 0;
}
/* check edc_afifo_underflow_int interrupt */
if ((inp32(edc_base + LDI_ORG_INT_OFFSET) & 0x4) == 0x4) {
set_reg(edc_base + LDI_INT_CLR_OFFSET, 0x1, 1, 2);
pr_notice("k3fb, %s: edc_afifo_underflow_int !!!\n", __func__);
}
#if defined(EDC_CH_CHG_SUPPORT)
//channel change flow
if (ov_info->rotation) {
if (!cfg_disable) {
if (req->id == OVERLAY_PIPE_EDC0_CH2) {
//replace edc1ch2
ch_chg = true;
edc_overlay_compose_ch_chg_enable(k3fd);
} else {
edc_overlay_compose_ch_chg_disable(k3fd, info);
}
}
} else {
edc_overlay_compose_ch_chg_disable(k3fd, info);
}
if (ch_chg) {
pipe->set_EDC_CH_CTL_ch_en(edc_base, K3_DISABLE);
set_EDC_DISP_CTL_ch_chg(edc_base, CH_CHG_ENABLE);
set_EDC_DISP_CTL_cfg_ok_sel(edc_base, CFG_SEL_EDC0);
BUG_ON(info1 == NULL || info1->par == NULL);
k3fd1 = (struct k3_fb_data_type *)info1->par;
BUG_ON(k3fd1 == NULL);
edc1_pipe = edc_overlay_ndx2pipe(info1, OVERLAY_PIPE_EDC1_CH1);
if (edc1_pipe == NULL) {
k3fb_loge("OVERLAY_PIPE_EDC1_CH1 not able to get pipe!");
return -ENODEV;
}
edc1_base = edc1_pipe->edc_base;
//set to edc1
pipe = edc1_pipe;
edc_base = edc1_base;
pipe->set_EDC_CH_CTL_ch_en(edc_base, K3_ENABLE);
}
#endif //EDC_CH_CHG_SUPPORT
/* set cross switch for this channel --start */
pst_overlay_func = &(g_overlay_surf_func[pipe->req_info.overlay_num]);
if (pst_overlay_func->set_overlay_cross_switch_sel) {
if (edc_overlay_compose_set_cross(pipe->req_info.overlay_num, pipe->req_info.id) < 0) {
/* clear the record map to invalid value */
memset(&g_ovly2ch_map, OVERLAY_TO_CHANELL_MAP_INVALID, sizeof(g_ovly2ch_map));
k3fb_loge("edc_overlay_compose_set_cross is error! \n");
return -EINVAL;
}
}
/* set cross switch for this channel --end */
if (req->src.type != EDC_LEFT_ADDR) {
if (pipe->set_EDC_CHR_ADDR) {
pipe->set_EDC_CHR_ADDR(edc_base, addr);
} else {
k3fb_logw("ch don't support right buffer addr!!!\n");
}
}
if (req->src.type != EDC_RIGHT_ADDR) {
pipe->set_EDC_CHL_ADDR(edc_base, addr);
}
/*begin support edc pixels algin modified by weiyi 00175802*/
#if defined(CONFIG_OVERLAY_PIXEL_ALIGN_SUPPORT)
// k3fb_loge("++++++++++++++++++++(%d)!\n", ov_info->rotation);
switch (ov_info->rotation) {
case EDC_ROT_NOP:
pipe->set_EDC_CH_CLIP_left(edc_base, left_clip);
pipe->set_EDC_CH_CLIP_top(edc_base, top_clip);
pipe->set_EDC_CH_CLIP_bottom(edc_base,ov_info->clip_bottom);
pipe->set_EDC_CH_CLIP_right(edc_base,ov_info->clip_right);
break;
case EDC_ROT_90:
pipe->set_EDC_CH_CLIP_bottom(edc_base, left_clip);
pipe->set_EDC_CH_CLIP_left(edc_base, top_clip);
pipe->set_EDC_CH_CLIP_top(edc_base,ov_info->clip_right);
pipe->set_EDC_CH_CLIP_right(edc_base,ov_info->clip_bottom);
break;
case EDC_ROT_180:
pipe->set_EDC_CH_CLIP_right(edc_base, left_clip);
pipe->set_EDC_CH_CLIP_bottom(edc_base, top_clip);
pipe->set_EDC_CH_CLIP_top(edc_base,ov_info->clip_bottom);
pipe->set_EDC_CH_CLIP_left(edc_base,ov_info->clip_right);
break;
case EDC_ROT_270:
pipe->set_EDC_CH_CLIP_top(edc_base, left_clip);
pipe->set_EDC_CH_CLIP_right(edc_base, top_clip);
pipe->set_EDC_CH_CLIP_left(edc_base,ov_info->clip_bottom);
pipe->set_EDC_CH_CLIP_bottom(edc_base,ov_info->clip_right);
break;
default:
k3fb_loge("Unsupported rotation(%d)!\n", ov_info->rotation);
break;
}
#endif
/*end support edc pixels algin modified by weiyi 00175802*/
pipe->set_EDC_CH_XY(edc_base, dst.x, dst.y);
pipe->set_EDC_CH_SIZE(edc_base, ov_info->src_rect.w, ov_info->src_rect.h);
pipe->set_EDC_CH_STRIDE(edc_base, req->src.stride);
pipe->set_EDC_CH_CTL_pix_fmt(edc_base, req->src.format);
pipe->set_EDC_CH_CTL_bgr(edc_base, req->src.bgr_fmt);
pipe->set_EDC_CH_CTL_ch_en(edc_base, K3_ENABLE);
if (pipe->set_EDC_CH_CTL_colork_en) {
pipe->set_EDC_CH_CTL_colork_en(edc_base, pipe->edc_ch_info.cap.ckey_enable);
}
if (pipe->edc_ch_info.cap.ckey_enable) {
pipe->set_EDC_CH_COLORK_MIN(edc_base, pipe->edc_ch_info.ckeymin);
pipe->set_EDC_CH_COLORK_MAX(edc_base, pipe->edc_ch_info.ckeymax);
}
if (pipe->pipe_type == OVERLAY_TYPE_CHCAP_ALL) {
set_EDC_CH1_CTL_rot(edc_base, ov_info->rotation);
#if defined(CONFIG_OVERLAY_PIXEL_ALIGN_SUPPORT)
/*JXT_ADD Fixed scale bug*/
resetSizeByClip(&src.w, &src.h , ov_info->rotation, (left_clip + right_clip), (top_clip + bottom_clip), -1);
/*Fiexed scale bug end*/
#endif
if (src.w == dst.w && src.h == dst.h) {
set_EDC_CH1_SCL_HSP_hsc_en(edc_base, K3_DISABLE);
set_EDC_CH1_SCL_VSP_vsc_en(edc_base, K3_DISABLE);
} else {
set_EDC_CH1_SCL_HSP_hsc_en(edc_base, K3_ENABLE);
set_EDC_CH1_SCL_VSP_vsc_en(edc_base, K3_ENABLE);
set_EDC_CH1_SCL_IRES(edc_base, src.w, src.h);
set_EDC_CH1_SCL_ORES(edc_base, dst.w, dst.h);
scl_ratio_w = (src.w << 12) / dst.w;
scl_ratio_h = (src.h << 12) / dst.h;
/*
if ((scl_ratio_w > ((10<<12)/7)) && (scl_ratio_h < (1<<12))) {
scl_ratio_w = ((10<<12)/7);
} else if ((scl_ratio_h > ((10<<12)/7)) && (scl_ratio_w < (1<<12))) {
scl_ratio_h = ((10<<12)/7);
}
*/
set_EDC_CH1_SCL_HSP_hratio(edc_base, scl_ratio_w);
set_EDC_CH1_SCL_HSP_hafir_en(edc_base, pipe->edc_ch_info.cap.filter_enable);
set_EDC_CH1_SCL_HSP_hfir_en(edc_base, pipe->edc_ch_info.cap.filter_enable);
if (pipe->edc_ch_info.cap.filter_enable) {
if (dst.w / src.w >= 1) {
memcpy(stSCLHorzCoef, gfxcoefficient8_cubic, sizeof(gfxcoefficient8_cubic));
} else if ((dst.w / src.w == 0) && (((dst.w % src.w) << 12) / src.w) >= 0x800) {
memcpy(stSCLHorzCoef, gfxcoefficient8_lanczos2_8tap, sizeof(gfxcoefficient8_lanczos2_8tap));
}else {
pr_err("k3fb, %s: scale down ratio can'nt be less than 0.5! ratio = 0x%x\n", __func__, (((dst.w % src.w) << 12) / src.w));
return -EINVAL;
}
for (i = 0; i < 8; i++) {
for (j = 0; j < 4; j++) {
set_EDC_CH1_SCL_HPC(edc_base, i, j, (stSCLHorzCoef[i][j*2+1] << 16) | (stSCLHorzCoef[i][j*2] & 0xFFFF));
}
}
}
set_EDC_CH1_SCL_VSR_vratio(edc_base, scl_ratio_h);
set_EDC_CH1_SCL_VSP_vafir_en(edc_base, pipe->edc_ch_info.cap.filter_enable);
set_EDC_CH1_SCL_VSP_vfir_en(edc_base, pipe->edc_ch_info.cap.filter_enable);
if (pipe->edc_ch_info.cap.filter_enable) {
if (dst.h / src.h >= 1) {
memcpy(stSCLVertCoef, gfxcoefficient4_cubic, sizeof(gfxcoefficient4_cubic));
} else if ((dst.h / src.h == 0) && (((dst.h % src.h) << 12) / src.h >= 0xC00)) {
memcpy(stSCLVertCoef, gfxcoefficient4_lanczos2_6M_a15, sizeof(gfxcoefficient4_lanczos2_6M_a15));
} else if ((dst.h / src.h == 0) && (((dst.h % src.h) << 12) / src.h >= 0x800) &&
(((dst.h % src.h) << 12) / src.h <= 0xC00)) {
memcpy(stSCLVertCoef, gfxcoefficient4_lanczos2_5M_a15, sizeof(gfxcoefficient4_lanczos2_5M_a15));
}else {
pr_err("k3fb, %s: scale down ratio can'nt be less than 0.5! ratio = 0x%x\n", __func__, (((dst.w % src.w) << 12) / src.w));
return -EINVAL;
}
for (i = 0; i < 16; i++) {
for (j = 0; j < 2; j++) {
set_EDC_CH1_SCL_VPC(edc_base, i, j, (stSCLVertCoef[i][j*2+1] << 16) |
(stSCLVertCoef[i][j*2] & 0xFFFF));
}
}
}
}
#if defined(CONFIG_OVERLAY_PIXEL_ALIGN_SUPPORT)
/*JXT_ADD Fixed scale bug*/
resetSizeByClip(&src.w, &src.h , ov_info->rotation, (left_clip + right_clip), (top_clip + bottom_clip), 1);
/*Fiexed scale bug end*/
#endif
}
#if defined(EDC_CH_CHG_SUPPORT)
if (ch_chg) {
//set to edc0
pipe = edc0_pipe;
edc_base = edc0_base;
/*begin support edc pixels algin modified by weiyi 00175802*/
#if defined(CONFIG_OVERLAY_PIXEL_ALIGN_SUPPORT)
pipe->set_EDC_CH_CLIP_bottom(edc_base,ov_info->clip_bottom);
pipe->set_EDC_CH_CLIP_right(edc_base,ov_info->clip_right);
#endif
/*end support edc pixels algin modified by weiyi 00175802*/
pipe->set_EDC_CH_XY(edc_base, dst.x, dst.y);
pipe->set_EDC_CH_SIZE(edc_base, src.w, src.h); //edc0
pipe->set_EDC_CH_CTL_pix_fmt(edc_base, req->src.format); //edc0
}
#endif //EDC_CH_CHG_SUPPORT
if (!req->is_graphic) {
if (pipe->set_EDC_CH_CSCIDC_csc_en) {
pipe->set_EDC_CH_CSCIDC_csc_en(edc_base, pipe->edc_ch_info.cap.csc_enable);
}
if (pipe->edc_ch_info.cap.csc_enable) {
#if 0
/* 709 for HD */
pipe->set_OVC_CH_CSCIDC(edc_base, 0x1f0, 0x180, 0x180);
pipe->set_OVC_CH_CSCODC(edc_base, 0x0, 0x0, 0x0);
pipe->set_OVC_CH_CSCP0(edc_base, 0x0, 0x129);
pipe->set_OVC_CH_CSCP1(edc_base, 0x129, 0x1cb);
pipe->set_OVC_CH_CSCP2(edc_base, 0x1f78, 0x1fca);
pipe->set_OVC_CH_CSCP3(edc_base, 0x21c, 0x129);
pipe->set_OVC_CH_CSCP4(edc_base, 0x0);
#else
/* 601 for SD */
pipe->set_OVC_CH_CSCIDC(edc_base, 0x1f0, 0x180, 0x180);
pipe->set_OVC_CH_CSCODC(edc_base, 0x0, 0x0, 0x0);
pipe->set_OVC_CH_CSCP0(edc_base, 0x0, 0x129);
pipe->set_OVC_CH_CSCP1(edc_base, 0x129, 0x198);
pipe->set_OVC_CH_CSCP2(edc_base, 0x1f30, 0x1f9c);
pipe->set_OVC_CH_CSCP3(edc_base, 0x204, 0x129);
pipe->set_OVC_CH_CSCP4(edc_base, 0x0);
#endif
}
}else {
edc_overlay_compose_ch_csc_unset(pipe, edc_base);
}
edc_overlay_compose_graphic_alpha_set(req, edc_base, pst_overlay_func);
k3_fb_gralloc_overlay_save_display_addr(k3fd, req->id, addr);
if (!cfg_disable) {
edc_overlay_compose_check_cross_ctl(edc_base);
#ifdef CONFIG_FOLLOWABILITY
if (G_FOLLOW_FLAG_START == g_follow_flag)
{
long fb_currTime = k3fb_getCurrTime();
pr_info("k3fb, TAG_Followability, %s: edc compose play current time is %ld ms!\n", __func__,fb_currTime);
k3fb_listInsert(fb_currTime);
}
#endif
/* clear the record map to invalid value */
memset(&g_ovly2ch_map, OVERLAY_TO_CHANELL_MAP_INVALID, sizeof(g_ovly2ch_map));
set_EDC_DISP_CTL_cfg_ok(edc_base, EDC_CFG_OK_YES);
}
return 0;
}
/* partial compose never use to pan_display */
#if 0
int edc_overlay_compose_pan_display(struct fb_var_screeninfo *var, struct fb_info *info, int ch_num)
{
struct edc_overlay_pipe *pipe = NULL;
struct edc_overlay_pipe *pan_pipe = NULL;
struct k3_fb_data_type *k3fd = NULL;
u32 edc_base = 0;
u32 display_addr = 0;
int pipe_id;
u32 pan_x;
u32 pan_y;
u32 pan_w;
u32 pan_h;
int pan_pipe_id;
BUG_ON(var == NULL || info == NULL || info->par == NULL);
k3fd = (struct k3_fb_data_type *)info->par;
/*
* pan_pipe_id: it is the channel numuber of stored the info of pan display,
* is the channel that its overlay_num = 0.
*
* pan_pipe: it is the pipe that its pipe overlay_info struct contain the info that pan_display needed.
*/
pan_pipe_id = ch_num;
pan_pipe = edc_overlay_ndx2pipe(info, pan_pipe_id);
if (pan_pipe == NULL) {
k3fb_loge("id=%d not able to get pipe!\n", pan_pipe_id);
return -ENODEV;
}
pan_x = pan_pipe->req_info.partial_dst_rect.x;
pan_y = pan_pipe->req_info.partial_dst_rect.y;
pan_w = pan_pipe->req_info.partial_dst_rect.w;
pan_h = pan_pipe->req_info.partial_dst_rect.h;
/*
* pipe_id: it is the real channel for EDC Display, and the channel info is stored by pan_pipe.
* pipe: it is th real channel pipe for display, must use it for config the edc channel register.
*/
pipe_id = pan_pipe->req_info.partial_ch_num;
pipe = edc_overlay_ndx2pipe(info, pipe_id);
edc_base = pipe->edc_base;
display_addr = info->fix.smem_start + info->fix.line_length * var->yoffset
+ var->xoffset * (var->bits_per_pixel >> 3);
/* stride 64byte odd align */
if (!is64BytesOddAlign(FB_64BYTES_ODD_ALIGN_NONE, info->fix.line_length)) {
k3fb_logw("stride NOT 64 bytes odd aligned, %x!\n", info->fix.line_length);
return -EINVAL;
}
if (!k3fd->panel_power_on) {
return 0;
}
display_addr += pan_y * info->fix.line_length + pan_x * (var->bits_per_pixel >> 3);
if (display_addr & 0x0F) {
k3fb_logw("buf addr NOT 16 bytes aligned, %x!\n", display_addr);
return -EINVAL;
}
/* set ovly_surf for pan display */
if (edc_overlay_compose_pan_display_ovly_surf_set(&(pan_pipe->req_info), edc_base) < 0) {
k3fb_loge("edc_overlay_compose_pan_display_ovly_surf_set is error,channel is %s\n", pan_pipe->req_info.id);
return -EINVAL;
}
if (k3fd->panel_info.s3d_frm != EDC_FRM_FMT_2D) {
if (pipe->set_EDC_CHR_ADDR) {
pipe->set_EDC_CHR_ADDR(edc_base, display_addr);
}
}
pipe->set_EDC_CHL_ADDR(edc_base, display_addr);
pipe->set_EDC_CH_STRIDE(edc_base, k3_fb_line_length(info->var.xres_virtual, info->var.bits_per_pixel >> 3));
pipe->set_EDC_CH_XY(edc_base, pan_x, pan_y);
pipe->set_EDC_CH_SIZE(edc_base, pan_w, pan_h);
pipe->set_EDC_CH_CTL_pix_fmt(edc_base, k3fd->fb_imgType);
/*begin support edc pixels algin modified by weiyi 00175802*/
#if defined(CONFIG_OVERLAY_PIXEL_ALIGN_SUPPORT)
pipe->set_EDC_CH_CLIP_bottom(edc_base,pan_pipe->req_info.clip_bottom_partial);
pipe->set_EDC_CH_CLIP_right(edc_base, pan_pipe->req_info.clip_right_partial);
#endif
/*begin support edc pixels algin modified by weiyi 00175802*/
if (pipe->set_EDC_CH_CTL_colork_en) {
pipe->set_EDC_CH_CTL_colork_en(edc_base, pipe->edc_ch_info.cap.ckey_enable);
}
if (pipe->edc_ch_info.cap.ckey_enable) {
pipe->set_EDC_CH_COLORK_MIN(edc_base, pipe->edc_ch_info.ckeymin);
pipe->set_EDC_CH_COLORK_MAX(edc_base, pipe->edc_ch_info.ckeymax);
}
pipe->set_EDC_CH_CTL_bgr(edc_base, k3fd->panel_info.bgr_fmt);
pipe->set_EDC_CH_CTL_bgr(edc_base, k3fd->fb_bgrFmt);
pipe->set_EDC_CH_CTL_ch_en(edc_base, K3_ENABLE);
edc_overlay_compose_partial_graphic_alpha_set(&(pan_pipe->req_info), edc_base);
/* clear the record map to invalid value */
memset(&g_ovly2ch_map, OVERLAY_TO_CHANELL_MAP_INVALID, sizeof(g_ovly2ch_map));
set_EDC_DISP_CTL_cfg_ok(edc_base, EDC_CFG_OK_YES);
/* Add for B120 traceDot begin */
#ifndef PC_UT_TEST_ON
trace_dot(SF, "8", 0);
#endif
/* Add for B120 traceDot end */
return 0;
}
#endif
#endif //CONFIG_OVERLAY_COMPOSE
int edc_overlay_play(struct fb_info *info, struct overlay_data *req)
{
struct edc_overlay_pipe *pipe = NULL;
struct k3_fb_data_type *k3fd = NULL;
struct overlay_info *ov_info = NULL;
struct k3fb_rect src;
struct k3fb_rect dst;
u32 edc_base = 0;
int i = 0;
int j = 0;
s16 stSCLHorzCoef[8][8] = {{0},};
s16 stSCLVertCoef[16][4] = {{0},};
u32 scl_ratio_w = 0;
u32 scl_ratio_h = 0;
u32 addr = 0;
BUG_ON(info == NULL || info->par == NULL || req == NULL);
k3fd = (struct k3_fb_data_type *)info->par;
pipe = edc_overlay_ndx2pipe(info, req->id);
if (pipe == NULL) {
k3fb_loge("id=%d not able to get pipe!\n", req->id);
return -ENODEV;
}
/* stride 64byte odd align */
if (!is64BytesOddAlign(FB_64BYTES_ODD_ALIGN_NONE, req->src.stride)) {
k3fb_logw("stride NOT 64 bytes odd aligned, %x.\n", req->src.stride);
return -EINVAL;
}
if (req->src.actual_width == 0 ||
req->src.actual_height == 0 ||
pipe->req_info.dst_rect.w == 0 ||
pipe->req_info.dst_rect.h == 0) {
k3fb_logw("invalid width or height!img_actual(%d,%d), dst(%d,%d).\n",
req->src.actual_width, req->src.actual_height,
pipe->req_info.dst_rect.w, pipe->req_info.dst_rect.h);
return -EINVAL;
}
edc_base = pipe->edc_base;
ov_info = &pipe->req_info;
src.x = 0;
src.y = 0;
src.w = req->src.actual_width;
src.h = req->src.actual_height;
dst = ov_info->dst_rect;
if (((req->id)!= OVERLAY_PIPE_EDC0_CH1) && ((req->id)!= OVERLAY_PIPE_EDC1_CH1)) {
ov_info->rotation = EDC_ROT_NOP;
}
addr = computeDisplayAddr(&(req->src), ov_info->rotation, &src);
/* 16 byte align */
if (addr & 0x0F) {
k3fb_logw("buf NOT 16 bytes aligned, %x.\n", req->src.phy_addr);
return -EINVAL;
}
if (!ov_info->is_pipe_used)
return 0;
down(&k3fd->sem);
if (!k3fd->panel_power_on) {
up(&k3fd->sem);
return 0;
}
/* Modified for EDC1 offset, begin */
if (k3fd_reg_base_edc0 == edc_base) {
/* check edc_afifo_underflow_int interrupt */
if ((inp32(edc_base + LDI_ORG_INT_OFFSET) & 0x4) == 0x4) {
set_reg(edc_base + LDI_INT_CLR_OFFSET, 0x1, 1, 2);
k3fb_logw("edc_afifo_underflow_int !!!\n");
}
} else {
/* check edc_afifo_underflow_int interrupt */
if ((inp32(edc_base + LDI_ORG_INT_OFFSET + LDI1_OFFSET) & 0x4) == 0x4) {
set_reg(edc_base + LDI_INT_CLR_OFFSET + LDI1_OFFSET, 0x1, 1, 2);
k3fb_logw("edc_afifo_underflow_int !!!\n");
}
}
/* Modified for EDC1 offset, end */
if(req->src.type != EDC_LEFT_ADDR) {
if (pipe->set_EDC_CHR_ADDR) {
pipe->set_EDC_CHR_ADDR(edc_base, addr);
} else {
k3fb_logw("ch don't support right buffer addr!!!\n");
}
}
if(req->src.type != EDC_RIGHT_ADDR) {
pipe->set_EDC_CHL_ADDR(edc_base, addr);
}
pipe->set_EDC_CH_XY(edc_base, dst.x, dst.y);
pipe->set_EDC_CH_SIZE(edc_base, req->src.actual_width, req->src.actual_height);
pipe->set_EDC_CH_STRIDE(edc_base, req->src.stride);
pipe->set_EDC_CH_CTL_pix_fmt(edc_base, req->src.format);
pipe->set_EDC_CH_CTL_bgr(edc_base, k3fd->panel_info.bgr_fmt);
pipe->set_EDC_CH_CTL_ch_en(edc_base, K3_ENABLE);
if(pipe->set_EDC_CH_CTL_colork_en) {
pipe->set_EDC_CH_CTL_colork_en(edc_base, pipe->edc_ch_info.cap.ckey_enable);
}
if (pipe->edc_ch_info.cap.ckey_enable) {
pipe->set_EDC_CH_COLORK_MIN(edc_base, pipe->edc_ch_info.ckeymin);
pipe->set_EDC_CH_COLORK_MAX(edc_base, pipe->edc_ch_info.ckeymax);
}
/* set EDC0 Cross switch to default value */
if(edc_base == k3fd_reg_base_edc0) {
set_EDC_CROSS_CTRL_default_val(edc_base);
}
if (pipe->pipe_type == OVERLAY_TYPE_CHCAP_ALL) {
set_EDC_CH1_CTL_rot(edc_base, ov_info->rotation);
if (src.w == dst.w && src.h == dst.h) {
set_EDC_CH1_SCL_HSP_hsc_en(edc_base, K3_DISABLE);
set_EDC_CH1_SCL_VSP_vsc_en(edc_base, K3_DISABLE);
} else {
set_EDC_CH1_SCL_HSP_hsc_en(edc_base, K3_ENABLE);
set_EDC_CH1_SCL_VSP_vsc_en(edc_base, K3_ENABLE);
set_EDC_CH1_SCL_IRES(edc_base, src.w, src.h);
set_EDC_CH1_SCL_ORES(edc_base, dst.w, dst.h);
scl_ratio_w = (src.w << 12) / dst.w;
scl_ratio_h = (src.h << 12) / dst.h;
/*
if ((scl_ratio_w > ((10<<12)/7)) && (scl_ratio_h < (1<<12))) {
scl_ratio_w = ((10<<12)/7);
} else if ((scl_ratio_h > ((10<<12)/7)) && (scl_ratio_w < (1<<12))) {
scl_ratio_h = ((10<<12)/7);
}
*/
set_EDC_CH1_SCL_HSP_hratio(edc_base, scl_ratio_w);
set_EDC_CH1_SCL_HSP_hafir_en(edc_base, pipe->edc_ch_info.cap.filter_enable);
set_EDC_CH1_SCL_HSP_hfir_en(edc_base, pipe->edc_ch_info.cap.filter_enable);
if (pipe->edc_ch_info.cap.filter_enable) {
if (dst.w / src.w >= 1) {
memcpy(stSCLHorzCoef, gfxcoefficient8_cubic, sizeof(gfxcoefficient8_cubic));
} else if ((dst.w / src.w == 0) && (((dst.w % src.w) << 12) / src.w) >= 0x800) {
memcpy(stSCLHorzCoef, gfxcoefficient8_lanczos2_8tap, sizeof(gfxcoefficient8_lanczos2_8tap));
}else {
pr_err("k3fb, %s: scale down ratio can'nt be less than 0.5! ratio = 0x%x\n", __func__, (((dst.w % src.w) << 12) / src.w));
up(&k3fd->sem);
return -EINVAL;
}
for (i = 0; i < 8; i++) {
for (j = 0; j < 4; j++) {
set_EDC_CH1_SCL_HPC(edc_base, i, j, (stSCLHorzCoef[i][j*2+1] << 16) |
(stSCLHorzCoef[i][j*2] & 0xFFFF));
}
}
}
set_EDC_CH1_SCL_VSR_vratio(edc_base, scl_ratio_h);
set_EDC_CH1_SCL_VSP_vafir_en(edc_base, pipe->edc_ch_info.cap.filter_enable);
set_EDC_CH1_SCL_VSP_vfir_en(edc_base, pipe->edc_ch_info.cap.filter_enable);
if (pipe->edc_ch_info.cap.filter_enable) {
if (dst.h / src.h >= 1) {
memcpy(stSCLVertCoef, gfxcoefficient4_cubic, sizeof(gfxcoefficient4_cubic));
} else if ((dst.h / src.h == 0) && (((dst.h % src.h) << 12) / src.h >= 0xC00)) {
memcpy(stSCLVertCoef, gfxcoefficient4_lanczos2_6M_a15, sizeof(gfxcoefficient4_lanczos2_6M_a15));
} else if ((dst.h / src.h == 0) && (((dst.h % src.h) << 12) / src.h >= 0x800) &&
(((dst.h % src.h) << 12) / src.h <= 0xC00)) {
memcpy(stSCLVertCoef, gfxcoefficient4_lanczos2_5M_a15, sizeof(gfxcoefficient4_lanczos2_5M_a15));
}else {
pr_err("k3fb, %s: scale down ratio can'nt be less than 0.5! ratio = 0x%x\n", __func__, (((dst.w % src.w) << 12) / src.w));
up(&k3fd->sem);
return -EINVAL;
}
for (i = 0; i < 16; i++) {
for (j = 0; j < 2; j++) {
set_EDC_CH1_SCL_VPC(edc_base, i, j, (stSCLVertCoef[i][j*2+1] << 16) |
(stSCLVertCoef[i][j*2] & 0xFFFF));
}
}
}
}
}
if (!req->is_graphic) {
pipe->set_EDC_CH_CSCIDC_csc_en(edc_base, pipe->edc_ch_info.cap.csc_enable);
if (pipe->edc_ch_info.cap.csc_enable) {
#if 0
/* 709 for HD */
pipe->set_EDC_CH_CSCIDC(edc_base, 0x0fc30180);
pipe->set_EDC_CH_CSCODC(edc_base, 0x00000000);
pipe->set_EDC_CH_CSCP0(edc_base, 0x00000100);
pipe->set_EDC_CH_CSCP1(edc_base, 0x0100018a);
pipe->set_EDC_CH_CSCP2(edc_base, 0x1f8b1fd2);
pipe->set_EDC_CH_CSCP3(edc_base, 0x01d00100);
pipe->set_EDC_CH_CSCP4(edc_base, 0x00000000);
#else
/* 601 for SD */
pipe->set_EDC_CH_CSCIDC(edc_base, 0x0fc30180);
pipe->set_EDC_CH_CSCODC(edc_base, 0x00000000);
pipe->set_EDC_CH_CSCP0(edc_base, 0x00000100);
pipe->set_EDC_CH_CSCP1(edc_base, 0x0100015e);
pipe->set_EDC_CH_CSCP2(edc_base, 0x1faa1f4e);
pipe->set_EDC_CH_CSCP3(edc_base, 0x01bb0100);
pipe->set_EDC_CH_CSCP4(edc_base, 0x00000000);
#endif
}
if (isAlphaRGBType(k3fd->fb_imgType)) {
set_EDC_CH12_OVLY_alp_blend_en(edc_base, pipe->edc_ch_info.cap.alpha_enable);
if (pipe->edc_ch_info.cap.alpha_enable) {
set_EDC_CH12_OVLY_alp_src(edc_base, pipe->edc_ch_info.alp_src);
if (pipe->edc_ch_info.alp_src == EDC_ALP_GLOBAL) {
set_EDC_CH12_GLB_ALP_VAL(edc_base, pipe->edc_ch_info.alpha0, pipe->edc_ch_info.alpha1);
} else {
if (k3fd->graphic_ch == OVERLAY_PIPE_EDC0_CH2 ||
k3fd->graphic_ch == OVERLAY_PIPE_EDC1_CH2) {
set_EDC_CH12_OVLY_pix_alp_src(edc_base, EDC_PIX_ALP_SRC_CH2);
set_EDC_CH12_OVLY_ch1_alp_sel(edc_base, EDC_ALP_MUL_COEFF_1);
set_EDC_CH12_OVLY_ch2_alp_sel(edc_base, EDC_ALP_MUL_COEFF_0);
} else {
set_EDC_CH12_OVLY_pix_alp_src(edc_base, EDC_PIX_ALP_SRC_CH1);
set_EDC_CH12_OVLY_ch1_alp_sel(edc_base, EDC_ALP_MUL_COEFF_0);
set_EDC_CH12_OVLY_ch2_alp_sel(edc_base, EDC_ALP_MUL_COEFF_1);
}
}
}
} else {
set_EDC_CH12_OVLY_alp_blend_en(edc_base, pipe->edc_ch_info.cap.alpha_enable);
if (pipe->edc_ch_info.cap.alpha_enable) {
set_EDC_CH12_OVLY_alp_src(edc_base, EDC_ALP_GLOBAL);
set_EDC_CH12_GLB_ALP_VAL(edc_base, pipe->edc_ch_info.alpha0, pipe->edc_ch_info.alpha1);
}
}
}
/* clear the record map to invalid value */
memset(&g_ovly2ch_map, OVERLAY_TO_CHANELL_MAP_INVALID, sizeof(g_ovly2ch_map));
set_EDC_DISP_CTL_cfg_ok(edc_base, EDC_CFG_OK_YES);
up(&k3fd->sem);
return 0;
}
int fb_pan_display_camera_debug(struct fb_var_screeninfo *var, struct fb_info *info, int id)
{
struct edc_overlay_pipe *pipe = NULL;
struct k3_fb_data_type *k3fd = NULL;
struct k3fb_rect src;
struct k3fb_rect dst;
#if defined(CONFIG_OVERLAY_COMPOSE)
u32 pre_type;
u32 pre_count;
#endif
u32 edc_base = 0;
u32 display_addr = 0;
int i = 0;
int j = 0;
s16 stSCLHorzCoef[8][8] = {{0},};
s16 stSCLVertCoef[16][4] = {{0},};
u32 scl_ratio_w = 0;
u32 scl_ratio_h = 0;
BUG_ON(var == NULL || info == NULL || info->par == NULL);
k3fd = (struct k3_fb_data_type *)info->par;
src.x = 0;
src.y = 0;
src.w = CAMERA_XRES_TEST;//320;
src.h = CAMERA_YRES_TEST;//480;
dst.w = k3fd->panel_info.xres;//720;
dst.h = k3fd->panel_info.yres;//1280;
#if defined(CONFIG_OVERLAY_COMPOSE)
pre_type = k3fd->ovc_type;
k3fd->ovc_type = OVC_NONE;
pre_count = k3fd->ovc_ch_count;
k3fd->ovc_ch_count = 1;
#endif
pipe = edc_overlay_ndx2pipe(info, 0);
if (pipe == NULL) {
k3fb_loge("id=%d not able to get pipe!\n", id);
return -ENODEV;
}
edc_base = pipe->edc_base;
display_addr = info->fix.smem_start + info->fix.line_length * var->yoffset
+ var->xoffset * (var->bits_per_pixel >> 3);
if (display_addr & 0x0F) {
k3fb_logw("buf addr NOT 16 bytes aligned, %x!\n", display_addr);
return -EINVAL;
}
/* stride 64byte odd align */
if (!is64BytesOddAlign(FB_64BYTES_ODD_ALIGN_NONE, info->fix.line_length)) {
k3fb_logw("stride NOT 64 bytes odd aligned, %x!\n", info->fix.line_length);
return -EINVAL;
}
#ifdef DEBUG_ON
pr_info("k3fb, %s:k3fd->panel_power_on: %d\n",__func__,k3fd->panel_power_on);
pr_info("k3fb, %s:info->fix.line_length: %d\n",__func__,info->fix.line_length);
pr_info("k3fb, %s:var->yoffset: %d\n",__func__,var->yoffset);
pr_info("k3fb, %s:var->xoffset: %d\n",__func__,var->xoffset);
pr_info("k3fb, %s:var->bits_per_pixel: %d\n",__func__,var->bits_per_pixel);
pr_info("k3fb, %s:k3fd->fb_imgType: %d\n",__func__,k3fd->fb_imgType);
#endif
down(&k3fd->sem);
if (!k3fd->panel_power_on) {
up(&k3fd->sem);
return 0;
}
#if defined(CONFIG_OVERLAY_COMPOSE)
edc_overlay_compose_pipe_unset_previous(info, pre_type, pre_count);
#if defined(EDC_CH_CHG_SUPPORT)
edc_overlay_compose_ch_chg_disable(k3fd, info);
#endif //EDC_CH_CHG_SUPPORT
pipe->set_EDC_CH_CTL_bgr(edc_base, k3fd->panel_info.bgr_fmt);
set_EDC_CH12_OVLY_ch2_top(edc_base, EDC_CH2_TOP);
#endif //CONFIG_OVERLAY_COMPOSE
if (k3fd->panel_info.s3d_frm != EDC_FRM_FMT_2D) {
if (pipe->set_EDC_CHR_ADDR) {
pipe->set_EDC_CHR_ADDR(edc_base, display_addr);
}
}
pipe->set_EDC_CHL_ADDR(edc_base, display_addr);
pipe->set_EDC_CH_STRIDE(edc_base, info->fix.line_length);
pipe->set_EDC_CH_XY(edc_base, 0, 0);
pipe->set_EDC_CH_SIZE(edc_base, src.w, src.h );
pipe->set_EDC_CH_CTL_pix_fmt(edc_base, k3fd->fb_imgType);
pipe->set_EDC_CH_CTL_bgr(edc_base, k3fd->fb_bgrFmt);
pipe->set_EDC_CH_CTL_colork_en(edc_base, pipe->edc_ch_info.cap.ckey_enable);
pipe->set_EDC_CH_CTL_bgr(edc_base, k3fd->fb_bgrFmt);
if (pipe->edc_ch_info.cap.ckey_enable) {
pipe->set_EDC_CH_COLORK_MIN(edc_base, pipe->edc_ch_info.ckeymin);
pipe->set_EDC_CH_COLORK_MAX(edc_base, pipe->edc_ch_info.ckeymax);
}
pipe->set_EDC_CH_CTL_ch_en(edc_base, K3_ENABLE);
if (pipe->pipe_type == OVERLAY_TYPE_CHCAP_ALL){
if (src.w == dst.w && src.h == dst.h) {
set_EDC_CH1_SCL_HSP_hsc_en(edc_base, K3_DISABLE);
set_EDC_CH1_SCL_VSP_vsc_en(edc_base, K3_DISABLE);
} else {
set_EDC_CH1_SCL_HSP_hsc_en(edc_base, K3_ENABLE);
set_EDC_CH1_SCL_VSP_vsc_en(edc_base, K3_ENABLE);
set_EDC_CH1_SCL_IRES(edc_base, src.w, src.h);
set_EDC_CH1_SCL_ORES(edc_base, dst.w, dst.h);
scl_ratio_w = (src.w << 12) / dst.w;
scl_ratio_h = (src.h << 12) / dst.h;
set_EDC_CH1_SCL_HSP_hratio(edc_base, scl_ratio_w);
set_EDC_CH1_SCL_HSP_hafir_en(edc_base, pipe->edc_ch_info.cap.filter_enable);
set_EDC_CH1_SCL_HSP_hfir_en(edc_base, pipe->edc_ch_info.cap.filter_enable);
if (pipe->edc_ch_info.cap.filter_enable) {
if (dst.w / src.w >= 1) {
memcpy(stSCLHorzCoef, gfxcoefficient8_cubic, sizeof(gfxcoefficient8_cubic));
} else if ((dst.w / src.w == 0) && (((dst.w % src.w) << 12) / src.w) >= 0x800) {
memcpy(stSCLHorzCoef, gfxcoefficient8_lanczos2_8tap, sizeof(gfxcoefficient8_lanczos2_8tap));
}else {
pr_err("k3fb, %s: scale down ratio can'nt be less than 0.5! ratio = 0x%x\n", __func__, (((dst.w % src.w) << 12) / src.w));
up(&k3fd->sem);
return -EINVAL;
}
for (i = 0; i < 8; i++) {
for (j = 0; j < 4; j++) {
set_EDC_CH1_SCL_HPC(edc_base, i, j, (stSCLHorzCoef[i][j*2+1] << 16) |
(stSCLHorzCoef[i][j*2] & 0xFFFF));
}
}
}
set_EDC_CH1_SCL_VSR_vratio(edc_base, scl_ratio_h);
set_EDC_CH1_SCL_VSP_vafir_en(edc_base, pipe->edc_ch_info.cap.filter_enable);
set_EDC_CH1_SCL_VSP_vfir_en(edc_base, pipe->edc_ch_info.cap.filter_enable);
if (pipe->edc_ch_info.cap.filter_enable) {
if (dst.h / src.h >= 1) {
memcpy(stSCLVertCoef, gfxcoefficient4_cubic, sizeof(gfxcoefficient4_cubic));
} else if ((dst.h / src.h == 0) && (((dst.h % src.h) << 12) / src.h >= 0xC00)) {
memcpy(stSCLVertCoef, gfxcoefficient4_lanczos2_6M_a15, sizeof(gfxcoefficient4_lanczos2_6M_a15));
} else if ((dst.h / src.h == 0) && (((dst.h % src.h) << 12) / src.h >= 0x800) &&
(((dst.h % src.h) << 12) / src.h <= 0xC00)) {
memcpy(stSCLVertCoef, gfxcoefficient4_lanczos2_5M_a15, sizeof(gfxcoefficient4_lanczos2_5M_a15));
}else {
pr_err("k3fb, %s: scale down ratio can'nt be less than 0.5! ratio = 0x%x\n", __func__, (((dst.w % src.w) << 12) / src.w));
up(&k3fd->sem);
return -EINVAL;
}
for (i = 0; i < 16; i++) {
for (j = 0; j < 2; j++) {
set_EDC_CH1_SCL_VPC(edc_base, i, j, (stSCLVertCoef[i][j*2+1] << 16) |
(stSCLVertCoef[i][j*2] & 0xFFFF));
}
}
}
}
}
set_EDC_DISP_CTL_cfg_ok(edc_base, EDC_CFG_OK_YES);
up(&k3fd->sem);
return 0;
}
int edc_fb_pan_display(struct fb_var_screeninfo *var, struct fb_info *info, int id)
{
struct edc_overlay_pipe *pipe = NULL;
struct k3_fb_data_type *k3fd = NULL;
u32 edc_base = 0;
u32 display_addr = 0;
#if defined(CONFIG_OVERLAY_COMPOSE)
u32 pre_type;
u32 pre_count;
#endif
BUG_ON(var == NULL || info == NULL || info->par == NULL);
k3fd = (struct k3_fb_data_type *)info->par;
#if defined(CONFIG_OVERLAY_COMPOSE)
pre_type = k3fd->ovc_type;
k3fd->ovc_type = OVC_NONE;
pre_count = k3fd->ovc_ch_count;
k3fd->ovc_ch_count = 1;
#endif /* CONFIG_OVERLAY_COMPOSE */
if (g_debug_camerause == 1) {
return fb_pan_display_camera_debug( var, info, 0 );
}
pipe = edc_overlay_ndx2pipe(info, id);
if (pipe == NULL) {
k3fb_loge("id=%d not able to get pipe!\n", id);
return -ENODEV;
}
edc_base = pipe->edc_base;
display_addr = info->fix.smem_start + info->fix.line_length * var->yoffset
+ var->xoffset * (var->bits_per_pixel >> 3);
if (display_addr & 0x0F) {
k3fb_logw("buf addr NOT 16 bytes aligned, %x!\n", display_addr);
return -EINVAL;
}
/* stride 64byte odd align */
if (!is64BytesOddAlign(FB_64BYTES_ODD_ALIGN_NONE, info->fix.line_length)) {
k3fb_logw("stride NOT 64 bytes odd aligned, %x!\n", info->fix.line_length);
return -EINVAL;
}
#ifdef DEBUG_ON
pr_info("k3fb, %s:k3fd->panel_power_on: %d\n",__func__,k3fd->panel_power_on);
pr_info("k3fb, %s:info->fix.line_length: %d\n",__func__,info->fix.line_length);
pr_info("k3fb, %s:var->yoffset: %d\n",__func__,var->yoffset);
pr_info("k3fb, %s:var->xoffset: %d\n",__func__,var->xoffset);
pr_info("k3fb, %s:var->bits_per_pixel: %d\n",__func__,var->bits_per_pixel);
pr_info("k3fb, %s:k3fd->fb_imgType: %d\n",__func__,k3fd->fb_imgType);
#endif
down(&k3fd->sem);
if (!k3fd->panel_power_on) {
up(&k3fd->sem);
return 0;
}
#if defined(CONFIG_OVERLAY_COMPOSE)
if (pre_type != k3fd->ovc_type) edc_overlay_compose_pipe_unset_previous(info, pre_type, pre_count);
#if defined(EDC_CH_CHG_SUPPORT)
edc_overlay_compose_ch_chg_disable(k3fd, info);
#endif //EDC_CH_CHG_SUPPORT
pipe->set_EDC_CH_CTL_bgr(edc_base, k3fd->panel_info.bgr_fmt);
set_EDC_CH12_OVLY_ch2_top(edc_base, EDC_CH2_TOP);
#endif //CONFIG_OVERLAY_COMPOSE
if (k3fd->panel_info.s3d_frm != EDC_FRM_FMT_2D) {
if (pipe->set_EDC_CHR_ADDR) {
pipe->set_EDC_CHR_ADDR(edc_base, display_addr);
}
}
if (pipe->set_EDC_CH_CSCIDC_csc_en) {
pipe->set_EDC_CH_CSCIDC_csc_en(edc_base, 0x0);
}
pipe->set_EDC_CHL_ADDR(edc_base, display_addr);
pipe->set_EDC_CH_STRIDE(edc_base, info->fix.line_length);
pipe->set_EDC_CH_XY(edc_base, 0, 0);
pipe->set_EDC_CH_SIZE(edc_base, k3fd->panel_info.xres, k3fd->panel_info.yres);
pipe->set_EDC_CH_CTL_pix_fmt(edc_base, k3fd->fb_imgType);
pipe->set_EDC_CH_CTL_bgr(edc_base, k3fd->fb_bgrFmt);
if (pipe->set_EDC_CH_CTL_colork_en) {
pipe->set_EDC_CH_CTL_colork_en(edc_base, pipe->edc_ch_info.cap.ckey_enable);
}
if (pipe->edc_ch_info.cap.ckey_enable) {
pipe->set_EDC_CH_COLORK_MIN(edc_base, pipe->edc_ch_info.ckeymin);
pipe->set_EDC_CH_COLORK_MAX(edc_base, pipe->edc_ch_info.ckeymax);
}
pipe->set_EDC_CH_CTL_ch_en(edc_base, K3_ENABLE);
if (0 == k3fd->index) {
set_EDC_CROSS_CTRL_default_val(edc_base);
}
/* clear the record map to invalid value */
memset(&g_ovly2ch_map, OVERLAY_TO_CHANELL_MAP_INVALID, sizeof(g_ovly2ch_map));
set_EDC_DISP_CTL_cfg_ok(edc_base, EDC_CFG_OK_YES);
#if CONFIG_WFD_FBINFO
/* wifi display begin */
wfd_fbi.physical = display_addr;
wfd_fbi.format = k3fd->fb_imgType;
//save the fb index and the fb shatus
wfd_fbi.fbslot = var->yoffset/var->yres;
wfd_fbi.fbstatus |= 1 << wfd_fbi.fbslot;
if ((EDC_ARGB_1555 == k3fd->fb_imgType) || (EDC_RGB_565 == k3fd->fb_imgType) ){
wfd_fbi.bpp = 2;
}
else if ((EDC_XRGB_8888 == k3fd->fb_imgType) || (EDC_ARGB_8888 == k3fd->fb_imgType)){
wfd_fbi.bpp = 4;
}
/* wifi display end */
#endif
/* Add for B120 traceDot begin */
#ifndef PC_UT_TEST_ON
trace_dot(SF, "8", 0);
#endif
/* Add for B120 traceDot end */
up(&k3fd->sem);
return 0;
}
int edc_fb_suspend(struct fb_info *info)
{
struct edc_overlay_pipe *pipe = NULL;
struct k3_fb_data_type *k3fd = NULL;
u32 edc_base = 0;
unsigned long dw_jiffies = 0;
u32 tmp = 0;
BUG_ON(info == NULL || info->par == NULL);
pr_info("k3fb, %s: enter!\n", __func__);
k3fd = (struct k3_fb_data_type *)info->par;
pipe = edc_overlay_ndx2pipe(info, k3fd->graphic_ch);
if (pipe == NULL) {
k3fb_loge("id=%d not able to get pipe!\n", k3fd->graphic_ch);
return -ENODEV;
}
#ifdef CONFIG_DEBUG_FS
if ((g_fb_lowpower_debug_flag & DEBUG_EDC_LOWPOWER_DISABLE) == DEBUG_EDC_LOWPOWER_DISABLE) {
k3fb_logi(" edc suspend was disable");
return 0;
}
#endif
edc_base = pipe->edc_base;
down(&k3fd->sem);
/* mask edc int and clear int state */
set_EDC_INTE(edc_base, 0xFFFFFFFF);
set_EDC_INTS(edc_base, 0x0);
set_EDC_CH1_CTL_ch1_en(edc_base, K3_DISABLE);
set_EDC_CH2_CTL_ch2_en(edc_base, K3_DISABLE);
#if defined(CONFIG_OVERLAY_COMPOSE)
if (0 == k3fd->index) {
set_EDC_GNEW1_CTL_ch_en(edc_base, K3_DISABLE);
set_EDC_GNEW2_CTL_ch_en(edc_base, K3_DISABLE);
set_EDC_CRS_CTL_en(edc_base, K3_DISABLE);
}
#endif
/* disable edc */
set_EDC_DISP_CTL_edc_en(edc_base, K3_DISABLE);
if (k3fd->panel_info.sbl_enable) {
/* disable sbl */
set_EDC_DISP_DPD_sbl_en(edc_base, K3_DISABLE);
}
/* edc cfg ok */
set_EDC_DISP_CTL_cfg_ok(edc_base, EDC_CFG_OK_YES);
/* Modified for EDC1 offset, begin */
if (k3fd_reg_base_edc0 == edc_base) {
/* check outstanding */
dw_jiffies = jiffies + HZ / 2;
do {
tmp = inp32(edc_base + EDC_STS_OFFSET);
if ((tmp & 0x80000000) == 0x80000000) {
break;
}
} while (time_after(dw_jiffies, jiffies));
} else {
/* check outstanding */
dw_jiffies = jiffies + HZ / 2;
do {
tmp = inp32(edc_base + EDC_STS_OFFSET + EDC1_OFFSET);
if ((tmp & 0x80000000) == 0x80000000) {
break;
}
} while (time_after(dw_jiffies, jiffies));
}
/* Modified for EDC1 offset, end */
/* edc clock gating */
clk_disable(k3fd->edc_clk);
clk_disable(k3fd->edc_axi_clk);
/* edc0 vcc */
if (k3fd->index == 0) {
clk_disable(k3fd->edc_cfg_clk);
edc0_pwr_down_clk_dis();
edc0_pwr_down_iso_en();
edc0_pwr_down_clk_reset();
edc_mtcos_disable(0);
}
/* edc1 mtcos disable in MHL */
#if defined(CONFIG_OVERLAY_COMPOSE)
k3_fb_overlay_compose_data_clear(k3fd);
#endif
up(&k3fd->sem);
pr_info("k3fb, %s: exit!\n", __func__);
return 0;
}
int edc_fb_resume(struct fb_info *info)
{
struct edc_overlay_pipe *pipe = NULL;
struct k3_fb_data_type *k3fd = NULL;
u32 edc_base = 0;
u32 edc_clk = 0;
BUG_ON(info == NULL || info->par == NULL);
pr_info("%s enter! \n",__func__);
k3fd = (struct k3_fb_data_type *)info->par;
pipe = edc_overlay_ndx2pipe(info, k3fd->graphic_ch);
if (pipe == NULL) {
k3fb_loge("id=%d not able to get pipe!\n", k3fd->graphic_ch);
return -ENODEV;
}
edc_base = k3fd->edc_base;
down(&k3fd->sem);
if (k3fd->index == 0) {
#ifndef PC_UT_TEST_ON
k3fd->ddr_min_freq = DDR_FREQ_POWER_ON;
pm_qos_update_request(&k3fd->ovc_ddrminprofile, k3fd->ddr_min_freq);
k3fd->ddr_min_freq_saved = k3fd->ddr_min_freq;
#endif
}
if (k3fd->index == 0) {
edc_clk = EDC_CORE_CLK_RATE;
} else {
edc_clk = EDC_CORE_CLK_RATE;//(k3fd->panel_info.yres < 720) ? EDC_CORE_CLK_RATE : ( k3fd->panel_info.clk_rate * 12 / 10);
}
/* 1: set clk division, and choose pll source */
if (clk_set_rate(k3fd->edc_clk, edc_clk) != 0) {
k3fb_loge("failed to set edc clk rate(%d).\n", edc_clk);
}
/* set ldi clock rate */
if (k3_fb_set_clock_rate(k3fd, k3fd->ldi_clk, k3fd->panel_info.clk_rate) != 0) {
k3fb_loge("failed to set ldi clk rate(%d).\n", k3fd->panel_info.clk_rate);
}
/* 2: enable edc clk */
if (clk_enable(k3fd->edc_clk) != 0) {
k3fb_loge("failed to enable edc clock.\n");
}
/* 3: enable edc brother clk, pixel clk enable at ldi_on()
* dsi_cfg_clk, dphy_cfg_clk, dphy_ref_clk enable at mipi_dsi_on()
*/
if (clk_enable(k3fd->edc_axi_clk) != 0) {
k3fb_loge("failed to enable edc axi clock.\n");
}
if (k3fd->index == 0) {
if (clk_enable(k3fd->edc_cfg_clk) != 0) {
k3fb_loge("failed to enable edc cfg clock.\n");
}
/* 4: edc disreset */
edc0_core_clk_disreset();
edc0_pixel_clk_disreset();
edc0_axi_clk_disreset();
edc0_cfg_clk_disreset();
/* 5: vcc enable */
if (edc_mtcos_enable(0) != 0) {
pr_err("k3fb, %s: failed to enable edc0_mtcos .\n", __func__);
}
/* 6: power domain clk disreset */
edc0_pwr_down_clk_disreset();
/* 7: power domain iso dis */
edc0_pwr_down_iso_dis();
/* 8: power domain clk enable */
edc0_pwr_down_clk_en();
}
/* edc init */
if (pipe->set_EDC_CH_CTL_secu_line) {
pipe->set_EDC_CH_CTL_secu_line(edc_base, EDC_CH_SECU_LINE);
}
pipe->set_EDC_CH_CTL_bgr(edc_base, k3fd->panel_info.bgr_fmt);
if (k3fd->panel_info.type == PANEL_MIPI_CMD) {
set_EDC_INTE(k3fd->edc_base, 0xFFFFFFFF);
} else {
set_EDC_INTE(k3fd->edc_base, 0xFFFFFF3F);
}
set_EDC_INTS(edc_base, 0x0);
set_EDC_DISP_DPD_disp_dpd(edc_base, 0x0);
set_EDC_DISP_SIZE(edc_base, k3fd->panel_info.xres, k3fd->panel_info.yres);
set_EDC_DISP_CTL_pix_fmt(edc_base, k3fd->panel_info.bpp);
set_EDC_DISP_CTL_frm_fmt(edc_base, k3fd->panel_info.s3d_frm);
set_EDC_DISP_CTL_endian(edc_base, EDC_ENDIAN_LITTLE);
set_EDC_CH12_OVLY_ch2_top(edc_base, 1);
#if defined(CONFIG_OVERLAY_COMPOSE)
if (0 == k3fd->index) {
if ((OVERLAY_PIPE_EDC0_GNEW1 == pipe->pipe_num) || (OVERLAY_PIPE_EDC0_GNEW2 == pipe->pipe_num)) {
if (k3fd->panel_info.s3d_frm > EDC_FRM_FMT_3D_CBC) {
k3fb_loge("edc ch %d don't support this 3d format %d.\n", pipe->pipe_num,k3fd->panel_info.s3d_frm);
}
}
/* set Cross switch to default value */
set_EDC_CROSS_CTRL_default_val(edc_base);
}
#endif
/* clear the record map to invalid value */
memset(&g_ovly2ch_map, OVERLAY_TO_CHANELL_MAP_INVALID, sizeof(g_ovly2ch_map));
if (isNeedDither(k3fd)) {
set_EDC_DISP_CTL_dither_en(edc_base, 1);
} else {
set_EDC_DISP_CTL_dither_en(edc_base, 0);
}
set_EDC_DISP_CTL_nrot_burst(edc_base, EDC_BURST8);
set_EDC_DISP_CTL_crg_gt_en(edc_base, K3_ENABLE);
#if defined(CONFIG_OVERLAY_COMPOSE)
set_EDC_DISP_CTL_outstding_dep(edc_base, 15);
#else
set_EDC_DISP_CTL_outstding_dep(edc_base, 8);
#endif
/*Set unflow_lev = 3072 for edc0 and unflow_lev = 640 for edc1*/
if (k3fd->index == 0) {
set_EDC_DISP_CTL_unflow_lev(edc_base, 0xC00);
} else {
set_EDC_DISP_CTL_unflow_lev(edc_base, 0x280);
}
set_EDC_DISP_CTL_edc_en(edc_base, K3_ENABLE);
set_EDC_DISP_CTL_cfg_ok(edc_base, EDC_CFG_OK_YES);
up(&k3fd->sem);
/* This spinlock will be UNLOCK in mipi_dsi_on */
if (k3fd->index == 0) {
if (k3fd->panel_info.frc_enable) {
k3fd->panel_info.frame_rate = 60;
k3fd->frc_threshold_count = 0;
k3fd->frc_state = K3_FB_FRC_NONE_PLAYING;
k3fd->frc_timestamp = jiffies;
}
if (k3fd->panel_info.esd_enable) {
k3fd->esd_timestamp = jiffies;
k3fd->esd_frame_count = 0;
}
}
pr_info("%s exit! \n", __func__);
return 0;
}
int sbl_bkl_set(struct k3_fb_data_type *k3fd, u32 value)
{
u32 tmp = 0;
BUG_ON(k3fd == NULL);
if (!k3fd->panel_power_on)
return 0;
/* Modified for EDC1 offset, begin */
if (k3fd_reg_base_edc0 == k3fd->edc_base) {
tmp = inp32(k3fd->edc_base + EDC_DISP_DPD_OFFSET);
} else {
tmp = inp32(k3fd->edc_base + EDC_DISP_DPD_OFFSET + EDC1_OFFSET);
}
/* Modified for EDC1 offset, end */
if ((tmp & REG_SBL_EN) == REG_SBL_EN) {
k3fd->bl_level = SBL_REDUCE_VALUE(value);
set_SBL_BKL_LEVEL_L_bkl_level_l(k3fd->edc_base, k3fd->bl_level);
}
return 0;
}
int sbl_ctrl_set(struct k3_fb_data_type *k3fd)
{
u32 tmp = 0;
u32 edc_base = 0;
u32 bkl_value = 0;
struct k3_fb_panel_data *pdata = NULL;
BUG_ON(k3fd == NULL);
edc_base = k3fd->edc_base;
pdata = (struct k3_fb_panel_data *)k3fd->pdev->dev.platform_data;
/* Modified for EDC1 offset, begin */
if (k3fd_reg_base_edc0 == edc_base) {
tmp = inp32(edc_base + EDC_DISP_DPD_OFFSET);
} else {
tmp = inp32(edc_base + EDC_DISP_DPD_OFFSET + EDC1_OFFSET);
}
/* Modified for EDC1 offset, end */
if (K3_DISABLE == k3fd->sbl_enable) {
if ((tmp & REG_SBL_EN) == REG_SBL_EN) {
set_EDC_DISP_DPD_sbl_en(edc_base, K3_DISABLE);
set_EDC_DISP_CTL_cfg_ok(edc_base, EDC_CFG_OK_YES);
if (pdata && pdata->set_cabc) {
pdata->set_cabc(k3fd->pdev, K3_ENABLE);
}
k3_fb_set_backlight(k3fd, k3fd->bl_level_sbl);
}
} else {
if ((tmp & REG_SBL_EN) != REG_SBL_EN) {
bkl_value = SBL_REDUCE_VALUE(k3fd->bl_level_sbl);
set_SBL_BKL_LEVEL_L_bkl_level_l(edc_base, bkl_value);
if (((k3fd->panel_info.type != PANEL_MIPI_CMD) || (k3fd->cmd_bl_can_set)) && (0 != k3fd->bl_level_sbl))
k3_fb_set_backlight(k3fd, bkl_value);
set_EDC_DISP_DPD_sbl_en(edc_base, K3_ENABLE);
set_EDC_DISP_CTL_cfg_ok(edc_base, EDC_CFG_OK_YES);
if (pdata && pdata->set_cabc) {
pdata->set_cabc(k3fd->pdev, K3_DISABLE);
}
}
}
return 0;
}
static unsigned short apical_reg_table[] = {
0x20, 0xff, 0x0f,
0x1f, 0xb3, 0x0f,
0x1e, 0x64, 0x0f,
0x1d, 0x13, 0x0f,
0x1c, 0xc0, 0x0e,
0x1b, 0x6b, 0x0e,
0x1a, 0x13, 0x0e,
0x19, 0xb9, 0x0d,
0x18, 0x5c, 0x0d,
0x17, 0xfd, 0x0c,
0x16, 0x9b, 0x0c,
0x15, 0x36, 0x0c,
0x14, 0xce, 0x0b,
0x13, 0x63, 0x0b,
0x12, 0xf4, 0x0a,
0x11, 0x82, 0x0a,
0x10, 0x0c, 0x0a,
0x0f, 0x93, 0x09,
0x0e, 0x15, 0x09,
0x0d, 0x93, 0x08,
0x0c, 0x0d, 0x08,
0x0b, 0x82, 0x07,
0x0a, 0xf3, 0x06,
0x09, 0x5e, 0x06,
0x08, 0xc3, 0x05,
0x07, 0x23, 0x05,
0x06, 0x7c, 0x04,
0x05, 0xcf, 0x03,
0x04, 0x1c, 0x03,
0x03, 0x61, 0x02,
0x02, 0x9e, 0x01,
0x01, 0xd3, 0x00,
0x00, 0x00, 0x00,
};
extern int apical_flags;
int sbl_ctrl_resume(struct k3_fb_data_type *k3fd)
{
u32 tmp = 0;
u32 edc_base = 0;
u32 frame_width_l = 0;
u32 frame_width_h = 0;
u32 frame_height_l = 0;
u32 frame_height_h = 0;
unsigned int count = 0;
unsigned int table_size;
struct k3_fb_panel_data *pdata = NULL;
pdata = (struct k3_fb_panel_data *)k3fd->pdev->dev.platform_data;
BUG_ON(k3fd == NULL);
edc_base = k3fd->edc_base;
frame_width_l = (k3fd->panel_info.xres) & 0xff;
frame_width_h = (k3fd->panel_info.xres >> 8) & 0xff;
frame_height_l = (k3fd->panel_info.yres) & 0xff;
frame_height_h = (k3fd->panel_info.yres >> 8) & 0xff;
set_SBL_FRAME_WIDTH_L_frame_width_l(edc_base, frame_width_l);
set_SBL_FRAME_WIDTH_H_frame_width_h(edc_base, frame_width_h);
set_SBL_FRAME_HEIGHT_L_frame_height_l(edc_base, frame_height_l);
set_SBL_FRAME_HEIGHT_H_frame_height_h(edc_base, frame_height_h);
set_reg(edc_base + SBL_CTRL_REG0_OFFSET, 0x0b, 8, 0);
set_reg(edc_base + SBL_CTRL_REG1_OFFSET, 0x22, 8, 0);
set_reg(edc_base + SBL_HS_POS_LOFFSET, 0x0, 8, 0);
set_reg(edc_base + SBL_HS_POS_HOFFSET, 0x0, 8, 0);
set_reg(edc_base + SBL_VS_POS_LOFFSET, 0x0, 8, 0);
set_reg(edc_base + SBL_VS_POS_HOFFSET, 0x0, 8, 0);
set_reg(edc_base + SBL_IRIDIX_CTRL0_OFFSET, 0x07, 8, 0);
set_reg(edc_base + SBL_IRIDIX_CTRL1_OFFSET, 0x46, 8, 0);
set_reg(edc_base + SBL_VARIANCE_OFFSET, 0x41, 8, 0);
set_reg(edc_base + SBL_SLOPE_MAX_OFFSET, 0x3c, 8, 0);
set_reg(edc_base + SBL_SLOPE_MIN_OFFSET, 0x80, 8, 0);
set_reg(edc_base + SBL_BLACK_LEVEL_LOFFSET, 0x0, 8, 0);
set_reg(edc_base + SBL_BLACK_LEVEL_HOFFSET, 0x0, 8, 0);
set_reg(edc_base + SBL_WHITE_LEVEL_LOFFSET, 0xff, 8, 0);
set_reg(edc_base + SBL_WHITE_LEVEL_HOFFSET, 0x03, 8, 0);
set_reg(edc_base + SBL_LIMIT_AMP_OFFSET, 0x0, 8, 0);
set_reg(edc_base + SBL_DITHER_OFFSET, 0x0, 8, 0);
set_reg(edc_base + SBL_LOGO_LEFT_OFFSET, 0x0, 8, 0);
set_reg(edc_base + SBL_LOGO_RIGHT_OFFSET, 0x0, 8, 0);
set_reg(edc_base + SBL_DITHER_CTRL_OFFSET, 0x03, 8, 0);
set_reg(edc_base + SBL_STRENGTH_SEL_OFFSET, 0x01, 8, 0);
set_reg(edc_base + SBL_STRENGTH_LIMIT_OFFSET, k3fd->panel_info.sbl.str_limit, 8, 0);
if(apical_flags == 0x80)
set_reg(edc_base + SBL_STRENGTH_MANUAL_OFFSET, 0x80, 8, 0);
else if(apical_flags == 0x20)
set_reg(edc_base + SBL_STRENGTH_MANUAL_OFFSET, 0x20, 8, 0);
else if(apical_flags == 0x0)
set_reg(edc_base + SBL_STRENGTH_MANUAL_OFFSET, 0x0, 8, 0);
set_reg(edc_base + SBL_OPTION_SEL_OFFSET, 0x02, 8, 0);
set_reg(edc_base + SBL_BKL_MAX_LOFFSET, k3fd->panel_info.sbl.bl_max, 8, 0);
set_reg(edc_base + SBL_BKL_MAX_HOFFSET, 0x0, 8, 0);
set_reg(edc_base + SBL_CALIBRATION_A_OFFSET, k3fd->panel_info.sbl.cal_a, 8, 0);
set_reg(edc_base + SBL_CALIBRATION_B_OFFSET, k3fd->panel_info.sbl.cal_b, 8, 0);
set_reg(edc_base + SBL_DRC_IN_LOFFSET, 0x87, 8, 0);
set_reg(edc_base + SBL_DRC_IN_HOFFSET, 0xba, 8, 0);
set_reg(edc_base + SBL_T_FILT_CTRL_OFFSET, 0x0, 8, 0);
set_reg(edc_base + SBL_BKL_LEVEL_HOFFSET, 0x0, 8, 0);
set_reg(edc_base + SBL_AMBIENT_LIGHT_LOFFSET, 0x0, 8, 0);
set_reg(edc_base + SBL_AMBIENT_LIGHT_HOFFSET, 0x2, 8, 0);
set_reg(edc_base + SBL_START_CALC_OFFSET, 0x01, 8, 0);
table_size = sizeof(apical_reg_table)/sizeof(unsigned short);
while (count < table_size) {
set_reg(edc_base + SBL_OFFSET + 0x480, apical_reg_table[count], 8, 0);
set_reg(edc_base + SBL_OFFSET + 0x484, apical_reg_table[count+1], 8, 0);
set_reg(edc_base + SBL_OFFSET + 0x488, apical_reg_table[count+2], 8, 0);
count += 3;
}
/* Modified for EDC1 offset, begin */
if (k3fd_reg_base_edc0 == edc_base) {
tmp = inp32(edc_base + EDC_DISP_DPD_OFFSET);
} else {
tmp = inp32(edc_base + EDC_DISP_DPD_OFFSET + EDC1_OFFSET);
}
/* Modified for EDC1 offset, end */
if ((K3_ENABLE == k3fd->sbl_enable) && ((tmp & REG_SBL_EN) != REG_SBL_EN)) {
k3fd->bl_level = SBL_REDUCE_VALUE(k3fd->bl_level_sbl);
set_SBL_BKL_LEVEL_L_bkl_level_l(edc_base, k3fd->bl_level);
set_EDC_DISP_DPD_sbl_en(edc_base, K3_ENABLE);
set_EDC_DISP_CTL_cfg_ok(edc_base, EDC_CFG_OK_YES);
if (pdata && pdata->set_cabc) {
pdata->set_cabc(k3fd->pdev, K3_DISABLE);
}
}
else {
if (pdata && pdata->set_cabc) {
pdata->set_cabc(k3fd->pdev, K3_ENABLE);
}
}
return 0;
}
int edc_fb_disable(struct fb_info *info)
{
struct edc_overlay_pipe *pipe = NULL;
struct k3_fb_data_type *k3fd = NULL;
u32 edc_base = 0;
BUG_ON(info == NULL || info->par == NULL);
k3fd = (struct k3_fb_data_type *)info->par;
pipe = edc_overlay_ndx2pipe(info, k3fd->graphic_ch);
if (pipe == NULL) {
k3fb_loge("id=%d not able to get pipe!\n", k3fd->graphic_ch);
return -ENODEV;
}
edc_base = pipe->edc_base;
down(&k3fd->sem);
pipe->set_EDC_CH_CTL_ch_en(edc_base, K3_DISABLE);
/* disable edc */
set_EDC_DISP_CTL_edc_en(edc_base, K3_DISABLE);
/* edc cfg ok */
set_EDC_DISP_CTL_cfg_ok(edc_base, EDC_CFG_OK_YES);
up(&k3fd->sem);
return 0;
}
int edc_fb_enable(struct fb_info *info)
{
struct edc_overlay_pipe *pipe = NULL;
struct k3_fb_data_type *k3fd = NULL;
u32 edc_base = 0;
BUG_ON(info == NULL || info->par == NULL);
pr_info("k3fb, %s: enter!\n", __func__);
k3fd = (struct k3_fb_data_type *)info->par;
pipe = edc_overlay_ndx2pipe(info, k3fd->graphic_ch);
if (pipe == NULL) {
k3fb_loge("id=%d not able to get pipe!\n", k3fd->graphic_ch);
return -ENODEV;
}
edc_base = pipe->edc_base;
down(&k3fd->sem);
pipe->set_EDC_CH_CTL_ch_en(edc_base, K3_DISABLE);
/* disable edc */
set_EDC_DISP_CTL_edc_en(edc_base, K3_ENABLE);
/* edc cfg ok */
set_EDC_DISP_CTL_cfg_ok(edc_base, EDC_CFG_OK_YES);
up(&k3fd->sem);
pr_info("k3fb, %s: exit!\n", __func__);
return 0;
}
| 32.777907 | 204 | 0.65569 | [
"3d"
] |
33c79daddfdebc1814dfd87728804d059c9b07c5 | 2,213 | h | C | gui/accessibility/LinkAccessibleWidget.h | mail-ru-im/im-desktop | d6bb606650ad84b31046fe39b81db1fec4e6050b | [
"Apache-2.0"
] | 81 | 2019-09-18T13:53:17.000Z | 2022-03-19T00:44:20.000Z | gui/accessibility/LinkAccessibleWidget.h | mail-ru-im/im-desktop | d6bb606650ad84b31046fe39b81db1fec4e6050b | [
"Apache-2.0"
] | 4 | 2019-10-03T15:17:00.000Z | 2019-11-03T01:05:41.000Z | gui/accessibility/LinkAccessibleWidget.h | mail-ru-im/im-desktop | d6bb606650ad84b31046fe39b81db1fec4e6050b | [
"Apache-2.0"
] | 25 | 2019-09-27T16:56:02.000Z | 2022-03-14T07:11:14.000Z | #pragma once
#include "controls/TextUnit.h"
namespace Ui
{
namespace Accessibility
{
class AccessibleLinkWidget;
}
class LinkAccessibleWidget : public QWidget
{
Q_OBJECT
public:
LinkAccessibleWidget(QWidget* _parent) : QWidget(_parent) {}
virtual const TextRendering::TextUnitPtr& getTextUnit() const = 0;
private:
friend class Ui::Accessibility::AccessibleLinkWidget;
};
namespace Accessibility
{
class LinkAccessibilityObject : public QObject
{
Q_OBJECT
public:
LinkAccessibilityObject(QObject* _parent, QRect _rect, int _idx)
: QObject(_parent)
, rect_(_rect)
, idx_(_idx)
{
}
QRect rect_;
int idx_ = -1;
};
class AccessibleTextLink : public QAccessibleObject
{
public:
AccessibleTextLink(LinkAccessibilityObject* _object) : QAccessibleObject(_object) {}
QAccessibleInterface* parent() const override;
bool isValid() const override { return true; }
int childCount() const override { return 0; }
QAccessibleInterface* child(int index) const override { return nullptr; }
int indexOfChild(const QAccessibleInterface* child) const override { return -1; }
QRect rect() const override;
QString text(QAccessible::Text t) const override;
QAccessible::Role role() const override { return QAccessible::Role::Link; }
QAccessible::State state() const override { return {}; }
};
class AccessibleLinkWidget : public QAccessibleWidget
{
public:
AccessibleLinkWidget(LinkAccessibleWidget* _widget);
int childCount() const override;
QAccessibleInterface* child(int index) const override;
int indexOfChild(const QAccessibleInterface* child) const override;
QString text(QAccessible::Text t) const override;
private:
LinkAccessibleWidget* getWidget() const;
std::vector<QRect> getLinkRects() const;
};
}
} | 30.736111 | 96 | 0.603254 | [
"vector"
] |
33d0b23f654e2e47e201a0a25a3264c79e1c3094 | 13,502 | c | C | build/gui/gridvcb.c | Unidata/Garp | 85a4a3fd68009f22be61d456bd7cb754ea5ace3d | [
"MIT"
] | 2 | 2018-03-06T03:28:17.000Z | 2021-06-16T20:31:03.000Z | build/gui/gridvcb.c | Unidata/Garp | 85a4a3fd68009f22be61d456bd7cb754ea5ace3d | [
"MIT"
] | 1 | 2021-07-23T17:44:41.000Z | 2021-07-23T17:44:41.000Z | build/gui/gridvcb.c | Unidata/Garp | 85a4a3fd68009f22be61d456bd7cb754ea5ace3d | [
"MIT"
] | null | null | null | /***********************************************************************
*
* Copyright 1996, University Corporation for Atmospheric Research.
*
* gridvcb.c
*
* Vertical profile callbacks for dynamically initialized widgets.
*
* History:
*
* 12/96 COMET Original copy
* 2/97 COMET Replaced "free" with Free macro to insure memory
* sanity.
* 3/97 COMET Desensitize FDF's when plotting SkewT or Stuve.
* 7/97 COMET Added model defined subdirectories.
* 10/97 COMET Added macro functionality.
* 11/97 COMET Save the button label for a model.
* 12/97 COMET Fix leaks related to builddirpath()
* 2/98 COMET Added code to allow for model dependent macros.
* 8/99 COMET Redefined FDF model directory.
*
***********************************************************************/
#include "geminc.h"
#include "gemprm.h"
#include "utils.h"
#include "ctbcmn.h"
#include "guimacros.h"
#include "vprofobj.h"
#include "model.h"
#include "fdfobj.h"
#include "genglobs.h"
#include "winobj.h"
#include "menucb.h"
#include "_proto.h"
char * GetStringArrayLabel ( int, char *, char **, char ** );
void
SetVPModelGridTypeCB ( Widget w, XtPointer clientData, XtPointer call_data )
/*
* This function sets the plot type to SCALAROBJECT or VECTOROBJECT when
* an FDF is chosen for model grids. It also activates the appropriate
* radio button. This routine is used both as a callback and as a general
* use routine so the widget id may not be that of either the scalar or
* vector radio buttons.
*/
{
Widget scalar_b, vector_b;
GuiVertProfileObjectType *vpt;
int type;
type = (int) clientData;
vpt = GetGuiVertProfileDialog();
/*
* Set grid type to SCALAROBJECT or VECTOROBJECT.
*/
SetVPGridType ( vpt, type );
/*
* Set radio button to either Scalar or Vector.
*/
scalar_b = GetModelScalarButtonVPW ( vpt );
vector_b = GetModelVectorButtonVPW ( vpt );
if ( type == SCALARGRIDOBJECT ) {
if ( ! XmToggleButtonGetState ( scalar_b ) )
XmToggleButtonSetState ( scalar_b, TRUE, FALSE );
if ( XmToggleButtonGetState ( vector_b ) )
XmToggleButtonSetState ( vector_b, FALSE, FALSE );
}
else if ( type == VECTORGRIDOBJECT ) {
if ( ! XmToggleButtonGetState ( vector_b ) )
XmToggleButtonSetState ( vector_b, TRUE, FALSE );
if ( XmToggleButtonGetState ( scalar_b ) )
XmToggleButtonSetState ( scalar_b, FALSE, FALSE );
}
}
void
VPModelButtonCB (Widget w,
XtPointer clientData,
XtPointer xt_call_data )
/*
* Called when a model option button is picked. Set the new model
* and update date/time scrolled list.
*/
{
Widget forecast_list;
GuiVertProfileObjectType *vpt;
WindowObjectType *wo;
KeyListType *fdf;
char *file, *model, *label;
char **models, **labels;
char *chapter, *directory;
int len, plot_type, numkeys;
int iret, err, verbose;
ButtonObject *bo = (ButtonObject *) clientData;
XmPushButtonCallbackStruct *cbs =
(XmPushButtonCallbackStruct *) xt_call_data;
verbose = GetVerboseLevel();
if( verbose > VERBOSE_0 )
printf ( "VPModelButtonCB\n" );
vpt = GetGuiVertProfileDialog();
wo = GetActiveWindowObject();
fdf = GetVPGuiFdfInfo();
SetupAbortProcess( wo );
/*
* Model.
*/
model = strdup ( bo->string );
FreeModelTypeVP ( vpt );
SetModelTypeVP ( vpt, model );
/*
* Get model key and label list from configuration file.
*/
iret = GetKeyList ( "modelkeys", "modellabels", ",",
&numkeys, &models, &labels );
label = GetStringArrayLabel ( numkeys, model,
models, labels );
FreeModelLabelTypeVP ( vpt );
SetModelLabelTypeVP ( vpt, label );
/*
* Dynamically build dialog scrolled lists.
*/
VPBuildScrolledLists ( model );
/*
* Update FDF.
*/
plot_type = GetVPGridType ( vpt );
file = strdup ( GetModelFdfVP ( vpt ) );
switch ( plot_type ) {
case SCALARGRIDOBJECT:
chapter = strdup ( GetModelVPScalarDir ( vpt ) );
directory = GetConfigValue( "vpscalarfdf" );
break;
case VECTORGRIDOBJECT:
chapter = strdup ( GetModelVPVectorDir ( vpt ) );
directory = GetConfigValue( "vpvectorfdf" );
break;
default:
CancelAbortProcess( wo, False );
return;
}
/*
* Reload FDF.
*/
GetVPModelField ( file, chapter, directory );
/*
* Free.
*/
Free ( model );
Free ( label );
Free ( file );
Free ( directory );
Free ( chapter );
StringListFree ( numkeys, models );
StringListFree ( numkeys, labels );
CancelAbortProcess( wo, False );
return;
}
void
VPVcoordButtonCB (Widget w,
XtPointer clientData,
XtPointer xt_call_data )
/*
* Called when a new vertical coordinate is chosen.
*/
{
GuiVertProfileObjectType *vpt;
WindowObjectType *wo;
char *vcoord;
int verbose;
ButtonObject *bo = (ButtonObject *) clientData;
XmPushButtonCallbackStruct *cbs =
(XmPushButtonCallbackStruct *) xt_call_data;
verbose = GetVerboseLevel();
if( verbose > VERBOSE_0 )
printf ( "VPVcoordButtonCB\n" );
vpt = GetGuiVertProfileDialog();
wo = GetActiveWindowObject();
SetupAbortProcess( wo );
/*
* Vertical coordinate.
*/
vcoord = strdup ( bo->string );
XmTextSetString ( GetModelVCoordVPW ( vpt ), vcoord );
Free ( vcoord );
CancelAbortProcess( wo, False );
return;
}
void
VPScalarFdfDirCB (Widget w,
XtPointer clientData,
XtPointer xt_call_data )
/*
* Called when a new FDF chapter is chosen.
*/
{
GuiVertProfileObjectType *vpt;
Widget scalar_list;
char *model, *chapter, *directory;
int verbose;
ButtonObject *bo = (ButtonObject *) clientData;
XmPushButtonCallbackStruct *cbs =
(XmPushButtonCallbackStruct *) xt_call_data;
verbose = GetVerboseLevel();
if( verbose > VERBOSE_0 )
printf ( "VPScalarFdfDirCB\n" );
vpt = GetGuiVertProfileDialog();
chapter = strdup ( bo->string );
/*
* Save FDF chapter.
*/
FreeModelVPScalarDir ( vpt );
SetModelVPScalarDir ( vpt, chapter );
/*
* Refill the scrolled list.
*/
scalar_list = GetScalarListVPW( vpt );
XtUnmanageChild ( scalar_list );
RemoveProductsFromList ( scalar_list );
model = strdup ( GetModelTypeVP ( vpt ) );
directory = GetConfigValue( "vpscalarfdf" );
BuildFieldList ( scalar_list, directory, chapter, model,
&(vpt->scalar_list) );
XtManageChild ( scalar_list );
Free ( model );
Free ( chapter );
Free ( directory );
return;
}
void
VPVectorFdfDirCB (Widget w,
XtPointer clientData,
XtPointer xt_call_data )
/*
* Called when a new FDF chapter is chosen.
*/
{
GuiVertProfileObjectType *vpt;
Widget vector_list;
char *model, *chapter, *directory;
int verbose;
ButtonObject *bo = (ButtonObject *) clientData;
XmPushButtonCallbackStruct *cbs =
(XmPushButtonCallbackStruct *) xt_call_data;
verbose = GetVerboseLevel();
if( verbose > VERBOSE_0 )
printf ( "VPVectorFdfDirCB\n" );
vpt = GetGuiVertProfileDialog();
chapter = strdup ( bo->string );
/*
* Save FDF chapter.
*/
FreeModelVPVectorDir ( vpt );
SetModelVPVectorDir ( vpt, chapter );
/*
* Refill the scrolled list.
*/
vector_list = GetVectorListVPW( vpt );
XtUnmanageChild ( vector_list );
RemoveProductsFromList ( vector_list );
model = strdup ( GetModelTypeVP ( vpt ) );
directory = GetConfigValue( "vpvectorfdf" );
BuildFieldList ( vector_list, directory, chapter, model,
&(vpt->vector_list) );
XtManageChild ( vector_list );
Free ( model );
Free ( chapter );
Free ( directory );
return;
}
void
VPWindSymbolCB ( Widget w,
XtPointer clientData,
XtPointer call_data )
/*
* Called when a model wind symbol button is picked.
*/
{
GuiVertProfileObjectType *vpt;
char *symbol;
int verbose;
ButtonObject *bo = (ButtonObject *) clientData;
XmPushButtonCallbackStruct *cbs =
(XmPushButtonCallbackStruct *) call_data;
verbose = GetVerboseLevel();
if( verbose > VERBOSE_0 )
printf ( "VPWindSymbolCB\n" );
vpt = GetGuiVertProfileDialog();
symbol = strdup ( bo->string );
FreeVectorSymbolVP ( vpt );
SetVectorSymbolVP ( vpt, symbol );
Free ( symbol );
return;
}
void
VPLineTypeCB ( Widget w,
XtPointer clientData,
XtPointer call_data )
/*
* Called when a model line type button is picked.
*/
{
GuiVertProfileObjectType *vpt;
char *linetype;
int verbose;
ButtonObject *bo = (ButtonObject *) clientData;
XmPushButtonCallbackStruct *cbs =
(XmPushButtonCallbackStruct *) call_data;
verbose = GetVerboseLevel();
if( verbose > VERBOSE_0 )
printf ( "VPLineTypeCB\n" );
vpt = GetGuiVertProfileDialog();
linetype = strdup ( bo->string );
FreeLineTypeVP ( vpt );
SetLineTypeVP ( vpt, linetype );
Free ( linetype );
return;
}
void
CheckYaxisTypeVP ( GuiVertProfileObjectType *vpt, char *axis_type )
{
/*
* Desensitize FDF lists for thermodynamic diagrams.
*/
if ( axis_type == NULL ) return;
if ( strcasecmp ( axis_type, "skewt" ) == 0 ||
strcasecmp ( axis_type, "stuve" ) == 0 ) {
XtSetSensitive ( GetScalarListVPW ( vpt ), FALSE );
XtSetSensitive ( GetVectorListVPW ( vpt ), FALSE );
XtSetSensitive ( GetFunctionVPW ( vpt ), FALSE );
XtSetSensitive ( GetModelFdfVPW ( vpt ), FALSE );
}
else {
XtSetSensitive ( GetScalarListVPW ( vpt ), TRUE );
XtSetSensitive ( GetVectorListVPW ( vpt ), TRUE );
XtSetSensitive ( GetFunctionVPW ( vpt ), TRUE );
XtSetSensitive ( GetModelFdfVPW ( vpt ), TRUE );
}
}
void
VPVerticalAxisCB ( Widget w,
XtPointer clientData,
XtPointer call_data )
/*
* Called when a new vertical axis is chosen.
*/
{
GuiVertProfileObjectType *vpt;
char *axis_type;
int verbose;
ButtonObject *bo = (ButtonObject *) clientData;
XmPushButtonCallbackStruct *cbs =
(XmPushButtonCallbackStruct *) call_data;
verbose = GetVerboseLevel();
if( verbose > VERBOSE_0 )
printf ( "VPVerticalAxisCB\n" );
vpt = GetGuiVertProfileDialog();
axis_type = strdup ( bo->string );
FreeAxisTypeVP ( vpt );
SetAxisTypeVP ( vpt, axis_type );
/*
* Desensitize FDF lists for thermodynamic diagrams.
*/
CheckYaxisTypeVP ( vpt, axis_type );
Free ( axis_type );
return;
}
void
SetVPMacro ( KeyListType *fdf, char *file )
{
/*
* The current FDF is a macro so change GUI to reflect a different mode.
*/
GuiVertProfileObjectType *vpt;
XmString xmstr;
char *buf="MACRO";
vpt = GetGuiVertProfileDialog();
/*
* Set function textfield widget.
*/
FreeFunctionVP ( vpt );
SetFunctionVP ( vpt, buf );
XmTextSetString ( GetFunctionVPW ( vpt ), GetFunctionVP ( vpt ) );
/*
* Set label.
*/
FreeModelFdfVP ( vpt );
SetModelFdfVP ( vpt, file );
xmstr = XmStringLtoRCreate ( buf, XmSTRING_DEFAULT_CHARSET );
XtVaSetValues ( GetModelFdfVPW ( vpt ),
XmNlabelString, xmstr,
NULL);
XmStringFree ( xmstr );
}
void
RunVPMacro ( char *directory )
{
GuiVertProfileObjectType *vpt;
KeyListType *fdf, *macro=NULL;
char *subdir, *model;
char *current_directory;
char *plot_type_key;
char chapter[81];
char keyName[1024], value[1024];
int i, err, plot_type;
vpt = GetGuiVertProfileDialog();
fdf = GetVPGuiFdfInfo();
/*
* Save default directory in case the directory is redefined in a
* macro.
*/
current_directory = strdup ( directory );
/*
* Read macro into a key list which allows for duplicate
* entries.
*/
if ( GetVPGridType ( vpt ) == SCALARGRIDOBJECT )
subdir = strdup ( GetModelVPScalarDir ( vpt ) );
else
subdir = strdup ( GetModelVPVectorDir ( vpt ) );
model = strdup ( GetModelTypeVP ( vpt ) );
if ( err = GetMacro ( fdf->fileName, fdf->path,
subdir, model, ¯o ) ) return;
/*
* Put key/value pairs into FDF and then display it.
*/
for ( i=0; i<macro->numKeys; i++ ) {
strcpy ( keyName, macro->keys[i].keyName );
strcpy ( value, macro->keys[i].value );
ToUpper ( keyName );
ToUpper ( value );
/*
* Update GUI and build metObjects.
*/
if ( strcmp ( keyName, "OPERATION" ) == 0 &&
strcmp ( value, "RUN" ) == 0 ) {
SetVPFdfFallbackValues ( fdf );
SetVPGridWidgets ( fdf, fdf->fileName );
BuildVPGrid();
}
/*
* Save the directory holding the current FDF.
*/
else if ( strcmp ( keyName, "DIRECTORY" ) == 0 ) {
Free ( current_directory );
current_directory = GetConfigValue ( macro->keys[i].value );
}
/*
* Save the chapter holding the current FDF.
*/
else if ( strcmp ( keyName, "CHAPTER" ) == 0 ) {
strcpy ( chapter, macro->keys[i].value );
}
/*
* Read in FDF. Save plot type.
*/
else if ( strcmp ( keyName, "FDF" ) == 0 ) {
GetVPModelField ( macro->keys[i].value, chapter,
current_directory );
fdf = GetVPGuiFdfInfo();
/*
* Save plot type.
*/
plot_type_key = GetFdfKeyValue ( fdf, "type" );
ToUpper ( plot_type_key );
plot_type = SCALARGRIDOBJECT;
if ( strcmp ( plot_type_key, "VECTOR" ) == 0 )
plot_type = VECTORGRIDOBJECT;
SetVPGridType ( vpt, plot_type );
Free ( plot_type_key );
}
/*
* Put modifications into FDF.
*/
else
PutInFDF ( macro->keys[i].keyName,
macro->keys[i].value, fdf, OVERWRITE );
}
/*
* Restore current macro settings.
*/
CopyFdf ( macro, fdf );
if ( macro != NULL ) DestroyFDF ( macro );
/*
* Free.
*/
Free ( model );
Free ( subdir );
Free ( current_directory );
}
| 21.812601 | 76 | 0.649682 | [
"vector",
"model"
] |
33d31039e2a147c9f655c4eedbb29867b92f9b8b | 1,945 | h | C | src/document.h | firodj/ascigram | 83bf7cab0a3cd27f5e8d8843b3df62f857db437d | [
"MIT"
] | null | null | null | src/document.h | firodj/ascigram | 83bf7cab0a3cd27f5e8d8843b3df62f857db437d | [
"MIT"
] | null | null | null | src/document.h | firodj/ascigram | 83bf7cab0a3cd27f5e8d8843b3df62f857db437d | [
"MIT"
] | null | null | null | /* document.h - generic markdown parser */
#ifndef _ASCIGRAM_DOCUMENT_H_
#define _ASCIGRAM_DOCUMENT_H_
#include "buffer.h"
#include "stack.h"
#ifdef __cplusplus
extern "C" {
#endif
/*************
* CONSTANTS *
*************/
/*********
* TYPES *
*********/
struct ascigram_attr {
uint16_t x, y;
uint32_t meta;
};
typedef struct ascigram_attr ascigram_attr;
struct ascigram_cell {
uint8_t ch;
ascigram_attr attr;
ascigram_stack pattern_refs;
};
typedef struct ascigram_cell ascigram_cell;
struct ascigram_row {
uint16_t y;
uint16_t width;
ascigram_stack cells;
};
typedef struct ascigram_row ascigram_row;
struct ascigram_renderer_data {
void *opaque;
};
typedef struct ascigram_renderer_data ascigram_renderer_data;
/* ascigram_renderer - functions for rendering parsed data */
struct ascigram_renderer {
/* state object */
void *opaque;
/* block level callbacks - NULL skips the block */
};
typedef struct ascigram_renderer ascigram_renderer;
struct ascigram_document {
ascigram_renderer renderer;
ascigram_renderer_data data;
ascigram_stack rows;
ascigram_stack pattern_refs;
uint16_t height;
uint16_t width;
};
typedef struct ascigram_document ascigram_document;
/*************
* FUNCTIONS *
*************/
/* ascigram_document_new: allocate a new document processor instance */
ascigram_document *ascigram_document_new(
const ascigram_renderer *renderer
) __attribute__ ((malloc));
/* ascigram_document_render: render regular Markdown using the document processor */
void ascigram_document_render(ascigram_document *doc, ascigram_buffer *ob, const uint8_t *data, size_t size);
/* ascigram_document_free: deallocate a document processor instance */
void ascigram_document_free(ascigram_document *doc);
void export_document_patrefs(ascigram_document *doc, ascigram_buffer *ob);
void dump_document_cells(ascigram_document *doc);
#ifdef __cplusplus
}
#endif
#endif /** _ASCIGRAM_DOCUMENT_H_ **/
| 21.373626 | 109 | 0.757841 | [
"render",
"object"
] |
33dff2f0b7e549e6fdf55d803021cdf2877935af | 2,735 | h | C | third_party/soomla/store/src/soomla/domain/CCVirtualCategory.h | enrevol/ee-x | 60a66ad3dc6e14802a7c5d8d585a8499be13f5b8 | [
"MIT"
] | null | null | null | third_party/soomla/store/src/soomla/domain/CCVirtualCategory.h | enrevol/ee-x | 60a66ad3dc6e14802a7c5d8d585a8499be13f5b8 | [
"MIT"
] | null | null | null | third_party/soomla/store/src/soomla/domain/CCVirtualCategory.h | enrevol/ee-x | 60a66ad3dc6e14802a7c5d8d585a8499be13f5b8 | [
"MIT"
] | null | null | null | /*
Copyright (C) 2012-2014 Soomla Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef __CCVirtualCategory_H_
#define __CCVirtualCategory_H_
#ifdef __cplusplus
#include <cocos2d.h>
#include <soomla/CCSoomlaMacros.h>
#include "soomla/CCStoreConsts.h"
#include <soomla/domain/CCDomain.h>
namespace soomla {
/**
@class CCVirtualCategory
@brief A category for virtual items.
This class is a definition of a category. A single category can be
associated with many virtual goods. Virtual categories help in organizing
your economy's virtual goods.
*/
class CCVirtualCategory : public CCDomain {
public:
CCVirtualCategory()
: mName(nullptr) {};
/**
Creates a virtual category.
@param name The name of the category.
@param goodItemIds An array containing the item ids of all the items
in this category.
@return The virtual category.
*/
static CCVirtualCategory*
create(const std::string& name,
const std::vector<std::string>& goodItemIds);
/**
Creates a virtual category.
@param dict A dictionary containing keys to each of the parameters
required by the create function.
@return The virtual category.
*/
SL_CREATE_WITH_VALUE_MAP(CCVirtualCategory);
virtual bool init(const std::string& name,
const std::vector<std::string>& goodItemIds);
virtual bool initWithValueMap(const cocos2d::ValueMap& map) override;
/**
Converts this `~CCVirtualCategory` to a `CCDictionary`.
@return `CCDictionary` representation of this `~CCVirtualCategory`.
*/
virtual cocos2d::ValueMap toValueMap() override;
virtual ~CCVirtualCategory() = default;
CC_SYNTHESIZE_PASS_BY_REF(std::string, mName, Name);
CC_SYNTHESIZE_PASS_BY_REF(std::vector<std::string>, mGoodItemIds,
GoodItemIds);
protected:
void fillNameFromValueMap(const cocos2d::ValueMap& map);
void putNameToValueMap(cocos2d::ValueMap& map);
void fillGoodItemIdsFromValueMap(const cocos2d::ValueMap& map);
void putGoodItemIdsToValueMap(cocos2d::ValueMap& map);
};
}; // namespace soomla
#endif // __cplusplus
#endif //__CCVirtualCategory_H_
| 30.730337 | 74 | 0.710786 | [
"vector"
] |
33e000e2b10cb897bfeace1b6bb2c6496513b688 | 11,354 | c | C | diylang/codegen.c | apetcho/diylang | 0e9a4d63b9f3b8a42dccc5b0f00b21e80321e7df | [
"MIT"
] | null | null | null | diylang/codegen.c | apetcho/diylang | 0e9a4d63b9f3b8a42dccc5b0f00b21e80321e7df | [
"MIT"
] | null | null | null | diylang/codegen.c | apetcho/diylang | 0e9a4d63b9f3b8a42dccc5b0f00b21e80321e7df | [
"MIT"
] | null | null | null | #include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<stdarg.h>
#include<stdint.h>
#include<ctype.h>
typedef unsigned char uchar;
// ---
typedef enum {
NodeIDENT, NodeSTR, NodeINT, NodeSEQ, NodeIF, NodePRTC, NodePRTS,
NodePRTI, NodeWHILE, NodeASSIGN, NodeNEG, NodeNOT, NodeMUL, NodeDIV,
NodeMOD, NodeADD, NodeSUB, NodeLT, NodeLE, NodeGT, NodeGE, NodeEQ,
NodeNE, NodeAND, NodeOR
} NodeEnum_t;
// ---
typedef enum{
FETCH, STORE, PUSH, ADD, SUB, MUL, DIV, MOD, LT, GT, LE, GE,
EQ, NE, AND, OR, NEG, NOT, JMP, JZ, PRTC, PRTS, PRTI, HALT
}CodeEnum_t;
typedef uchar Code_t;
// ---
typedef struct Tree{
NodeEnum_t node;
struct Tree *left;
struct Tree *right;
char *value;
}Tree;
// ***
#define diyl_dim(name, type) \
type *name = NULL; \
int _qy_ ## name ## _p = 0; \
int _qy_ ## name ## _max = 0
#define diyl_rewind(name) _qy_ ## name ## _p = 0
#define diyl_redim(name) \
do{ \
if(_qy_ ## name ## _p >= _qy_ ## name ## _max){ \
name = realloc(name, (_qy_##name##_max += 32)*sizeof(name[0])); \
} \
}while(0)
#define diyl_append(name, x) \
do{ \
diyl_redim(name); \
name[_qy_ ## name ## _p++] = x; \
}while(0)
#define diyl_len(name) _qy_ ## name ## _p
#define diyl_add(name) \
do{ \
diyl_redim(name); \
_qy_ ## name ## _p++; \
}while(0)
// ---
FILE *srcfile;
FILE *dstfile;
static int here;
diyl_dim(object, Code_t);
diyl_dim(globals, const char*);
diyl_dim(string_pool, const char*);
// ---
struct {
char *enumtxt;
NodeEnum_t node;
CodeEnum_t opcode;
} attr[] = {
{"IDENTIFIER", NodeIDENT, -1},
{"STRING", NodeSTR, -1},
{"INTEGER", NodeINT, -1},
{"SEQUENCE", NodeSEQ, -1},
{"IF", NodeIF, -1},
{"PRTC", NodePRTC, -1},
{"PRTS", NodePRTS, -1},
{"PRTI", NodePRTI, -1},
{"WHILE", NodeWHILE, -1},
{"ASSIGN", NodeASSIGN, -1},
{"NEGATE", NodeNEG, NEG},
{"NOT", NodeNOT, NOT},
{"MULTIPLY", NodeMUL, MUL},
{"MOD", NodeMOD, MOD},
{"ADD", NodeADD, ADD},
{"SUBSTRACT", NodeSUB, SUB},
{"LESSTHAN", NodeLT, LT},
{"LESSEQUAL", NodeLE, LE},
{"GREATERTHAN", NodeGT, GT},
{"GREATEREQUAL", NodeGE, GE},
{"EQUAL", NodeEQ, EQ},
{"NOTEQUAL", NodeNE, NE},
{"AND", NodeAND, AND},
{"OR", NodeOR, OR},
};
// ***
void error(const char *fmt, ...){
va_list ap;
char buf[1000];
//
va_start(ap, fmt);
vsprintf(buf, fmt, ap);
va_end(ap);
printf("Error: %s\n", buf);
exit(1);
}
// ***
CodeEnum_t type_to_opcode(NodeEnum_t type){
return attr[type].opcode;
}
// ***
Tree *make_node(NodeEnum_t ntype, Tree *left, Tree *right){
Tree *tree = calloc(sizeof(*tree), 1);
tree->node = ntype;
tree->left = left;
tree->right = right;
return tree;
}
// ***
Tree *make_leaf(NodeEnum_t ntype, char *value){
Tree *tree = calloc(sizeof(*tree), 1);
tree->node = ntype;
tree->value = value;
return tree;
}
// ***
// ----- Code Generator -----
void emit_byte(int c){
diyl_append(object, (uchar)c);
++here;
}
// ***
void emit_int(int32_t n){
union{
int32_t n;
unsigned char c[sizeof(int32_t)];
}x;
x.n = n;
for(size_t i=0; i < sizeof(x.n); ++i){emit_byte(x.c[i]);}
}
// ***
int hole(){
int t = here;
emit_int(0);
return t;
}
// ***
void fix(int src, int dst){
*(int32_t*)(object + src) = dst - src;
}
// ***
int fetch_var_offset(const char *id){
for(int i=0; i < diyl_len(globals); ++i){
if(strcmp(id, globals[i]) == 0){ return i;}
}
diyl_add(globals);
int n = n = diyl_len(globals) - 1;
globals[n] = strdup(id);
return n;
}
// ***
int fetch_string_offset(const char *st){
for(int i=0; i < diyl_len(string_pool); i++){
if(strcmp(st, string_pool[i]) == 0){ return i; }
}
diyl_add(string_pool);
int n = diyl_len(string_pool) - 1;
string_pool[n] = strdup(st);
return n;
}
// ***
void code_gen(Tree *tree){
int p1, p2, n;
if(tree == NULL){ return;}
switch(tree->node){
case NodeIDENT:
emit_byte(FETCH);
n = fetch_var_offset(tree->value);
emit_int(n);
break;
case NodeINT:
emit_byte(PUSH);
emit_int(atoi(tree->value));
break;
case NodeSTR:
emit_byte((PUSH));
n = fetch_string_offset(tree->value);
emit_int(n);
break;
case NodeASSIGN:
n = fetch_var_offset(tree->left->value);
code_gen(tree->right);
emit_byte(STORE);
emit_int(n);
break;
case NodeIF:
code_gen(tree->left);
emit_byte(JZ);
p1 = hole();
code_gen(tree->right->left);
if(tree->right->right != NULL){
emit_byte(JMP);
p2 = hole();
}
fix(p1, here);
if(tree->right->right != NULL){
code_gen(tree->right->right);
fix(p2, here);
}
break;
case NodeWHILE:
p1 = here;
code_gen(tree->left);
emit_byte(JZ);
p2 = hole();
code_gen(tree->right);
emit_byte(JMP);
fix(hole(), p1);
fix(p2, here);
break;
case NodeSEQ:
code_gen(tree->left);
code_gen(tree->right);
break;
case NodePRTC:
code_gen(tree->left);
emit_byte(PRTC);
break;
case NodePRTI:
code_gen(tree->left);
emit_byte(PRTI);
break;
case NodePRTS:
code_gen(tree->left);
emit_byte(PRTS);
break;
case NodeLT: case NodeGT: case NodeLE: case NodeEQ: case NodeNE:
case NodeAND: case NodeOR: case NodeSUB: case NodeADD: case NodeDIV:
case NodeMUL: case NodeMOD:
code_gen(tree->left);
code_gen(tree->right);
emit_byte(type_to_opcode(tree->node));
break;
case NodeNEG: case NodeNOT:
code_gen(tree->left);
emit_byte(type_to_opcode(tree->node));
break;
default:
error("Error in code generator - found %d, expecting operator",
tree->node);
}
}
// ***
void code_finish(){
emit_byte(HALT);
}
// ***
void list_code(){
fprintf(
dstfile,
"Datasize: %d strings: %d\n",
diyl_len(globals), diyl_len(string_pool)
);
for(int i=0; i < diyl_len(string_pool); ++i){
fprintf(dstfile, "%s\n", string_pool[i]);
}
Code_t *pc = object;
// --
again:
fprintf(dstfile, "%5d ", (int)(pc - object));
switch(*pc++){
case FETCH:
fprintf(dstfile, "fetch [%d]\n", *(int32_t*)pc);
pc += sizeof(int32_t);
goto again;
case STORE:
fprintf(dstfile, "store [%d]\n", *(int32_t*)pc);
pc += sizeof(int32_t);
goto again;
case PUSH:
fprintf(dstfile, "push %d\n", *(int32_t*)pc);
pc += sizeof(int32_t);
goto again;
case ADD:
fprintf(dstfile, "add\n");
goto again;
case SUB:
fprintf(dstfile, "sub\n");
goto again;
case MUL:
fprintf(dstfile, "mul\n");
goto again;
case DIV:
fprintf(dstfile, "div\n");
goto again;
case MOD:
fprintf(dstfile, "mod\n");
goto again;
case LT:
fprintf(dstfile, "lt\n");
goto again;
case GT:
fprintf(dstfile, "gt\n");
goto again;
case LE:
fprintf(dstfile, "le\n");
goto again;
case GE:
fprintf(dstfile, "ge\n");
goto again;
case EQ:
fprintf(dstfile, "eq\n");
goto again;
case AND:
fprintf(dstfile, "and\n");
goto again;
case OR:
fprintf(dstfile, "or\n");
goto again;
case NOT:
fprintf(dstfile, "not\n");
goto again;
case NEG:
fprintf(dstfile, "neg\n");
goto again;
case JMP:
fprintf(dstfile, "jmp (%d) %d\n",
*(int32_t*)pc, (int32_t)(pc + (*(int32_t*)pc) - object)
);
pc += sizeof(int32_t);
goto again;
case JZ:
fprintf(dstfile, "jz (%d) %d\n",
*(int32_t*)pc, (int32_t)(pc + (*(int32_t*)pc) - object)
);
pc += sizeof(int32_t);
goto again;
case PRTC:
fprintf(dstfile, "prtc\n");
goto again;
case PRTI:
fprintf(dstfile, "prti\n");
goto again;
case PRTS:
fprintf(dstfile, "prts\n");
goto again;
case HALT:
fprintf(dstfile, "halt\n");
break;
default:
error("listcode: Unknow opcode %d\n", *(pc - 1));
}//switch
}
// ***
// init_io() => initialize()
void initialize(FILE **fp, FILE *std, const char mode[], const char filename[]){
if(filename[0] == '\0'){ *fp = std; }
else if((*fp = fopen(filename, mode)) == NULL){
error(0, 0, "Can't open %s\n", filename);
}
}
// ***
NodeEnum_t get_enum_value(const char name[]){
for(size_t i=0; i < sizeof(attr)/sizeof(attr[0]); i++){
if(strcmp(attr[i].enumtxt, name) == 0){
return attr[i].node;
}
}
error("Unknown token %s\n", name);
return -1;
}
// ***
char* read_line(int *len){
static char *text = NULL;
static int textmax = 0;
for(*len = 0; ; (*len)++){
int ch = fgetc(srcfile);
if(ch == EOF || ch == '\n'){
if(*len == 0){return NULL; }
break;
}
if(*len+1 >= textmax){
textmax = (textmax == 0? 128 : textmax * 2);
text = realloc(text, textmax);
}
text[*len] = ch;
}
text[*len] = '\0';
return text;
}
// ***
char *rtrim(char *text, int *len){
for(; *len >= 0 && isspace(text[*len-1]); --(*len)){}
text[*len] = '\0';
return text;
}
// ***
Tree* load_ast(){
int len;
char **yytext = read_line(&len);
// --
char *token = strtok(yytext, " ");
if(token[0] = ';'){ return NULL; }
NodeEnum_t node = get_enum_value(token);
// --
char *p = token + strlen(token);
if(p != &yytext[len]){
for(++p; isspace(*p); ++p){}
return make_leaf(node, p);
}
//
Tree *left = load_ast();
Tree *right = load_ast();
return make_node(node, left, right);
}
// --------------------------------------------------------------------------
// M A I N D R I V E R
// --------------------------------------------------------------------------
int main(int argc, char **argv){
initialize(&srcfile, stdin, "r", argc > 1 ? argv[1] : "");
initialize(&dstfile, stdout, "wb", argc > 2 ? argv[2] : "");
code_gen(load_ast());
code_finish();
list_code();
return EXIT_SUCCESS;
}
| 24.575758 | 80 | 0.486084 | [
"object"
] |
33e22bc54f9e18cc68f6e14706cb942da4f1ae9f | 1,231 | h | C | headers/bboxes.h | Euler-Maskerony/PokerData | 4fbca303fdf17d74cd074be2d6a089bb0243da3b | [
"MIT"
] | null | null | null | headers/bboxes.h | Euler-Maskerony/PokerData | 4fbca303fdf17d74cd074be2d6a089bb0243da3b | [
"MIT"
] | null | null | null | headers/bboxes.h | Euler-Maskerony/PokerData | 4fbca303fdf17d74cd074be2d6a089bb0243da3b | [
"MIT"
] | null | null | null | #ifndef BBOXES_PD
#define BBOXES_PD
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/dnn.hpp>
#include <opencv2/highgui.hpp>
#include <vector>
#include <iostream>
#include <utility>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <map>
#include "vars.h"
#define CONF_THRES 0.7
#define NMS_TRES 0.4
#define INTER_SCORE 0.5
#define PATH_TO_CFG "../res/yolo/yolov3-voc.cfg"
#define PATH_TO_WEIGHTS "../res/yolo/model.weights"
#define PATH_TO_NAMES "../res/yolo/voc.names"
namespace pd
{
class Models
{
private:
inline static std::map<int,cv::dnn::Net> models;
inline static int def{-1};
public:
// Adds model to the container
static int addModel(cv::dnn::Net model);
// Returns bounding boxes of objects and their ids
static std::vector<pd::Obj> getBboxes(cv::Mat,int key=-1);
// Sets default model
static void setDefault(int key);
};
// Returns names array from voc.names
void getNames(std::vector<std::string>&);
// Returns true if common area of two rects is bigger than INTER_SCORE
bool isIntersects(cv::Rect,cv::Rect);
}
#endif | 26.191489 | 74 | 0.683184 | [
"vector",
"model"
] |
33e6d37d20cd6f696f5175fe057b9d35b7ca558f | 13,987 | h | C | Library/Sources/Stroika/Foundation/Time/TimeOfDay.h | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 28 | 2015-09-22T21:43:32.000Z | 2022-02-28T01:35:01.000Z | Library/Sources/Stroika/Foundation/Time/TimeOfDay.h | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 98 | 2015-01-22T03:21:27.000Z | 2022-03-02T01:47:00.000Z | Library/Sources/Stroika/Foundation/Time/TimeOfDay.h | SophistSolutions/Stroika | f4e5d84767903a054fba0a6b9c7c4bd1aaefd105 | [
"MIT"
] | 4 | 2019-02-21T16:45:25.000Z | 2022-02-18T13:40:04.000Z | /*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
#ifndef _Stroika_Foundation_Time_TimeOfDay_h_
#define _Stroika_Foundation_Time_TimeOfDay_h_ 1
#include "../StroikaPreComp.h"
#if defined(__cpp_impl_three_way_comparison)
#include <compare>
#endif
#include <climits>
#include <locale>
#include <string>
#include "../Characters/String.h"
#include "../Configuration/Common.h"
#include "../Configuration/Enumeration.h"
#include "../Execution/Exceptions.h"
#include "../Traversal/Iterable.h"
/**
* \file
*
* \version <a href="Code-Status.md">Alpha-Late</a>
*
* TODO:
* @todo Need DefaultNames<> for enums in TimeOfDay module
*
* @todo Consider having some way to support double as TimeOfDay (or maybe float). Don't want the
* complexity of the chrono code, but some of the power ;-). Not sure how to compromise.
*
* @todo I'm not sure eCurrentLocale_WithZerosStripped is a good idea. Not sure if better
* to use separate format print arg or???
*
* @todo Should we PIN or throw OVERFLOW exception on values/requests which are out of range?
*
* @todo (medium) Consider using strftime and strptime with %FT%T%z.
* Same format
* That doesn't use std::locale()
* En.cppreference.com/w/cpp/io/manip/get_time
* istringstream xxx ('2011-feb')
* ss.imbue(std::locale() ('de-DE'));
* ss >> std::get_time(&t, '%FT%T%z')
*/
namespace Stroika::Foundation::Time {
using Characters::String;
/**
* Description:
* A time value - which is assumed to be within a given day - e.g 2:30 pm.
*
* \note this implies NO NOTION of timezone. Its a time relative to midnight of a given day.
*
* \note \em Thread-Safety <a href="Thread-Safety.md#C++-Standard-Thread-Safety">C++-Standard-Thread-Safety</a>
*
* \note <a href="Coding Conventions.md#Comparisons">Comparisons</a>:
* o Standard Stroika Comparison support (operator<=>,operator==, etc);
*/
class TimeOfDay {
public:
/**
* NB: The maximum value in a TimeOfDay struct is one less than kMaxSecondsPerDay
*/
static constexpr uint32_t kMaxSecondsPerDay = 60 * 60 * 24u; // nb: 86400: wont fit in uint16_t
public:
/**
* If value out of range - pinned to kMax.
* We normalize to be within a given day (seconds since midnight)
*
* For the TimeOfDay, we allow out of range values and pin/accumulate. But you can still never have a time of day >= kMaxSecondsPerDay.
* And the first hour (1pm) is hour 0, so TimeOfDay (2, 0, 0) is 3am.
*
* \req argument time-of-day (in seconds or hours/minutes/seconds) is in valid range for one day
* \req t < kMaxSecondsPerDay
* \req hour < 24
* \req minute < 60
* \req seconds < 60
*/
constexpr TimeOfDay (const TimeOfDay&) = default;
constexpr TimeOfDay (TimeOfDay&& src) = default;
constexpr explicit TimeOfDay (uint32_t t);
explicit constexpr TimeOfDay (unsigned int hour, unsigned int minute, unsigned int seconds);
public:
/**
*/
nonvirtual TimeOfDay& operator= (const TimeOfDay&) = default;
public:
/**
* \note https://en.cppreference.com/w/cpp/locale/time_get/get and https://en.cppreference.com/w/cpp/locale/time_put/put
* equivalent to "%H:%M:%S"
*
* \note leading zeros in hours, minutes, seconds, required, not optional
* \note this is locale-independent
*/
static constexpr wstring_view kISO8601Format = L"%T"sv;
public:
/**
* \note https://en.cppreference.com/w/cpp/locale/time_get/get and https://en.cppreference.com/w/cpp/locale/time_put/put
*/
static constexpr wstring_view kLocaleStandardFormat = L"%X"sv;
public:
/**
* \note https://en.cppreference.com/w/cpp/locale/time_get/get and https://en.cppreference.com/w/cpp/locale/time_put/put
*/
static constexpr wstring_view kLocaleStandardAlternateFormat = L"%EX"sv;
public:
/**
* Default formats used by TimeOfDay::Parse () to parse time strings. The first of these - %X, is
* the locale-specific time format.
*
* \note https://en.cppreference.com/w/cpp/locale/time_get/get and https://en.cppreference.com/w/cpp/locale/time_put/put
*/
static const Traversal::Iterable<String> kDefaultParseFormats;
public:
/**
* Always produces a valid legal TimeOfDay, or throws an exception.
*
* \note an empty string produces FormatException exception (whereas before 2.1d11 it produced an empty TimeOfDay object (TimeOfDay {}).
*
* \note the 2 argument locale overload uses each of kDefaultParseFormats formats to try to
* parse the time string, but the default is locale specific standard time format.
*
* \note overloads with the locale missing, default to locale{} - the default locale.
*
* \note format strings defined by https://en.cppreference.com/w/cpp/locale/time_get/get and https://en.cppreference.com/w/cpp/locale/time_put/put
*
* \see https://en.cppreference.com/w/cpp/locale/time_get/get for allowed formatPatterns
*
* The overload which takes a locale but no explicit format strings, defaults to trying
* each of kDefaultParseFormats strings in order, and returns the first match.
*
* The overload taking an iterable of formats, tries each, and returns the timeofday for the first that succeeds, or throws
* FormatException if none succeed.
*/
static TimeOfDay Parse (const String& rep, const locale& l = locale{});
static TimeOfDay Parse (const String& rep, const String& formatPattern);
static TimeOfDay Parse (const String& rep, const locale& l, const String& formatPattern);
static TimeOfDay Parse (const String& rep, const locale& l, const Traversal::Iterable<String>& formatPatterns);
public:
/**
* \brief like Parse(), but returns nullopt on parse error, not throwing exception.
* if locale is missing, and formatPattern is not locale independent, the current locale (locale{}) is used.
* if rep is empty, this will return nullopt
*/
static optional<TimeOfDay> ParseQuietly (const String& rep, const String& formatPattern);
static optional<TimeOfDay> ParseQuietly (const String& rep, const locale& l, const String& formatPattern);
private:
// this rquires rep!= ""
static optional<TimeOfDay> ParseQuietly_ (const wstring& rep, const String& formatPattern);
static optional<TimeOfDay> ParseQuietly_ (const wstring& rep, const time_get<wchar_t>& tmget, const String& formatPattern);
public:
/**
* kMin is the first date this TimeOfDay class supports representing.
*/
static const TimeOfDay kMin; // defined constexpr
public:
/**
* kMax is the last date this TimeOfDay class supports representing. This is a legal TimeOfDay, and
* not like 'end' - one past the last legal value.
*/
static const TimeOfDay kMax; // defined constexpr
public:
[[deprecated ("Since Stroika 2.1b4 use kMin")]] static constexpr TimeOfDay min ();
[[deprecated ("Since Stroika 2.1b4 use kMax")]] static constexpr TimeOfDay max ();
public:
class FormatException;
public:
/**
* \ensure {return} < kMaxSecondsPerDay
*/
nonvirtual constexpr uint32_t GetAsSecondsCount () const; // seconds since StartOfDay (midnight)
public:
/**
*/
nonvirtual void ClearSecondsField ();
public:
/**
* returns 0..23
*/
nonvirtual constexpr uint8_t GetHours () const;
public:
/**
* returns 0..59
*/
nonvirtual constexpr uint8_t GetMinutes () const;
public:
/**
* returns 0..59
*/
nonvirtual constexpr uint8_t GetSeconds () const;
public:
/**
* \brief PrintFormat is a representation which a TimeOfDay can be transformed into
*
* eCurrentLocale_WithZerosStripped
* eCurrentLocale_WithZerosStripped is eCurrentLocale, but with many cases of trailing zero's,
* and sometimes leading zeros, stripped, so for example, 01:03:05 PM will become 1:03:05 PM,
* and 04:06:00 PM will become 4:06 PM.
*/
DISABLE_COMPILER_CLANG_WARNING_START ("clang diagnostic ignored \"-Wdeprecated-declarations\"")
DISABLE_COMPILER_GCC_WARNING_START ("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
DISABLE_COMPILER_MSC_WARNING_START (4996) // class deprecated but still need to implement it
enum class PrintFormat : uint8_t {
eCurrentLocale [[deprecated ("Since Stroika 2.1b10 - use locale{}")]],
eISO8601 [[deprecated ("Since Stroika 2.1b10 - use kISO8601Format")]],
eCurrentLocale_WithZerosStripped,
eDEFAULT = eCurrentLocale_WithZerosStripped,
Stroika_Define_Enum_Bounds (eCurrentLocale, eCurrentLocale_WithZerosStripped)
};
DISABLE_COMPILER_CLANG_WARNING_END ("clang diagnostic ignored \"-Wdeprecated-declarations\"")
DISABLE_COMPILER_GCC_WARNING_END ("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
DISABLE_COMPILER_MSC_WARNING_END (4996) // class deprecated but still need to implement it
public:
/**
* For formatPattern, see http://en.cppreference.com/w/cpp/locale/time_put/put
* If only formatPattern specified, and no locale, use default (global) locale.
*
* \note if locale is missing (not specified as argument) the default locale (locale{}) is used.
*/
nonvirtual String Format (PrintFormat pf = PrintFormat::eDEFAULT) const;
nonvirtual String Format (const locale& l) const;
nonvirtual String Format (const locale& l, const String& formatPattern) const;
nonvirtual String Format (const String& formatPattern) const;
#if __cpp_impl_three_way_comparison >= 201907
public:
/**
*/
constexpr strong_ordering operator<=> (const TimeOfDay& rhs) const = default;
#endif
public:
/**
* @see Characters::ToString ()
*/
nonvirtual String ToString () const;
public:
DISABLE_COMPILER_CLANG_WARNING_START ("clang diagnostic ignored \"-Wdeprecated-declarations\"")
DISABLE_COMPILER_GCC_WARNING_START ("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
DISABLE_COMPILER_MSC_WARNING_START (4996) // class deprecated but still need to implement it
enum class [[deprecated ("Since Stroika 2.1b10 ")]] ParseFormat : uint8_t{
eCurrentLocale,
eISO8601 [[deprecated ("Since Stroika 2.1b10 - use kISO8601Format")]],
Stroika_Define_Enum_Bounds (eCurrentLocale, eISO8601)};
[[deprecated ("Since Stroika 2.1b10 *use Parse/1")]] static TimeOfDay Parse (const String& rep, ParseFormat pf);
DISABLE_COMPILER_CLANG_WARNING_END ("clang diagnostic ignored \"-Wdeprecated-declarations\"")
DISABLE_COMPILER_GCC_WARNING_END ("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
DISABLE_COMPILER_MSC_WARNING_END (4996) // class deprecated but still need to implement it
private:
uint32_t fTime_;
};
class TimeOfDay::FormatException : public Execution::RuntimeErrorException<> {
public:
FormatException ();
public:
/**
*/
static const FormatException kThe;
};
#if !qCompiler_cpp17InlineStaticMemberOfClassDoubleDeleteAtExit_Buggy
inline const TimeOfDay::FormatException TimeOfDay::FormatException::kThe;
//%t Any white space.
//%T The time as %H : %M : %S. (iso8601 format)
//%r is the time as %I:%M:%S %p
//%M The minute [00,59]; leading zeros are permitted but not required.
//%p Either 'AM' or 'PM' according to the given time value, or the corresponding strings for the current locale. Noon is treated as 'pm' and midnight as 'am'.
//%P Like %p but in lowercase: 'am' or 'pm' or a corresponding string for the current locale. (GNU)
//%S The seconds [00,60]; leading zeros are permitted but not required.
inline const Traversal::Iterable<String> TimeOfDay::kDefaultParseFormats{
kLocaleStandardFormat,
kLocaleStandardAlternateFormat,
kISO8601Format,
L"%r"sv,
L"%H:%M"sv,
L"%I%p"sv,
L"%I%P"sv,
L"%I%t%p"sv,
L"%I%t%P"sv,
L"%I:%M%t%p"sv,
L"%I:%M%t%P"sv,
L"%I:%M:%S%t%p"sv,
L"%I:%M:%S%t%P"sv,
L"%I:%M:%S"sv,
L"%I:%M"sv,
};
#endif
#if __cpp_impl_three_way_comparison < 201907
constexpr bool operator< (TimeOfDay lhs, TimeOfDay rhs);
constexpr bool operator<= (TimeOfDay lhs, TimeOfDay rhs);
constexpr bool operator== (TimeOfDay lhs, TimeOfDay rhs);
constexpr bool operator!= (TimeOfDay lhs, TimeOfDay rhs);
constexpr bool operator>= (TimeOfDay lhs, TimeOfDay rhs);
constexpr bool operator> (TimeOfDay lhs, TimeOfDay rhs);
#endif
}
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include "TimeOfDay.inl"
#endif /*_Stroika_Foundation_Time_TimeOfDay_h_*/
| 41.259587 | 169 | 0.628727 | [
"object"
] |
33f121aa2c1574507c636604252bf079ea528d87 | 2,207 | h | C | examples/pxScene2d/external/libnode-v10.15.3/deps/v8/src/objects/microtask.h | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 5,964 | 2016-09-27T03:46:29.000Z | 2022-03-31T16:25:27.000Z | examples/pxScene2d/external/libnode-v10.15.3/deps/v8/src/objects/microtask.h | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 1,432 | 2017-06-21T04:08:48.000Z | 2020-08-25T16:21:15.000Z | examples/pxScene2d/external/libnode-v10.15.3/deps/v8/src/objects/microtask.h | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 1,006 | 2016-09-27T05:17:27.000Z | 2022-03-30T02:46:51.000Z | // Copyright 2018 the V8 project 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 V8_OBJECTS_MICROTASK_H_
#define V8_OBJECTS_MICROTASK_H_
#include "src/objects.h"
// Has to be the last include (doesn't have include guards):
#include "src/objects/object-macros.h"
namespace v8 {
namespace internal {
// Abstract base class for all microtasks that can be scheduled on the
// microtask queue. This class merely serves the purpose of a marker
// interface.
class Microtask : public Struct {
public:
// Dispatched behavior.
DECL_CAST(Microtask)
DECL_VERIFIER(Microtask)
private:
DISALLOW_IMPLICIT_CONSTRUCTORS(Microtask);
};
// A CallbackTask is a special Microtask that allows us to schedule
// C++ microtask callbacks on the microtask queue. This is heavily
// used by Blink for example.
class CallbackTask : public Microtask {
public:
DECL_ACCESSORS(callback, Foreign)
DECL_ACCESSORS(data, Foreign)
static const int kCallbackOffset = Microtask::kHeaderSize;
static const int kDataOffset = kCallbackOffset + kPointerSize;
static const int kSize = kDataOffset + kPointerSize;
// Dispatched behavior.
DECL_CAST(CallbackTask)
DECL_PRINTER(CallbackTask)
DECL_VERIFIER(CallbackTask)
private:
DISALLOW_IMPLICIT_CONSTRUCTORS(CallbackTask)
};
// A CallableTask is a special (internal) Microtask that allows us to
// schedule arbitrary callables on the microtask queue. We use this
// for various tests of the microtask queue.
class CallableTask : public Microtask {
public:
DECL_ACCESSORS(callable, JSReceiver)
DECL_ACCESSORS(context, Context)
static const int kCallableOffset = Microtask::kHeaderSize;
static const int kContextOffset = kCallableOffset + kPointerSize;
static const int kSize = kContextOffset + kPointerSize;
// Dispatched behavior.
DECL_CAST(CallableTask)
DECL_PRINTER(CallableTask)
DECL_VERIFIER(CallableTask)
void BriefPrintDetails(std::ostream& os);
private:
DISALLOW_IMPLICIT_CONSTRUCTORS(CallableTask);
};
} // namespace internal
} // namespace v8
#include "src/objects/object-macros-undef.h"
#endif // V8_OBJECTS_MICROTASK_H_
| 28.294872 | 73 | 0.773448 | [
"object"
] |
b8768289203fcc7db0b6e01309430893eff9eb5c | 1,275 | h | C | src/codegen/shared_library.h | viyadb/viyadb | 56d9b9836a57a36483bee98e6bc79f79e2f5c772 | [
"Apache-2.0"
] | 109 | 2017-10-03T06:52:30.000Z | 2022-03-22T18:38:48.000Z | src/codegen/shared_library.h | b-xiang/viyadb | b72f9cabacb4b24bd2192ed824d930ccb73d3609 | [
"Apache-2.0"
] | 26 | 2017-10-15T19:45:18.000Z | 2019-10-18T09:55:54.000Z | src/codegen/shared_library.h | viyadb/viyadb | 56d9b9836a57a36483bee98e6bc79f79e2f5c772 | [
"Apache-2.0"
] | 7 | 2017-10-03T09:37:36.000Z | 2020-12-15T01:04:45.000Z | /*
* Copyright (c) 2017-present ViyaDB Group
*
* 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 VIYA_CODEGEN_SHARED_LIBRARY_H_
#define VIYA_CODEGEN_SHARED_LIBRARY_H_
#include "util/macros.h"
#include <string>
#include <vector>
namespace viya {
namespace codegen {
class SharedLibrary {
public:
SharedLibrary(const std::string &path);
DISALLOW_COPY_AND_MOVE(SharedLibrary);
~SharedLibrary();
template <typename Func> Func GetFunction(const std::string &name) {
return reinterpret_cast<Func>(GetFunctionPtr(name));
}
private:
std::string path_;
std::vector<std::string> fn_names_;
void *handle_;
void *GetFunctionPtr(const std::string &name);
};
} // namespace codegen
} // namespace viya
#endif // VIYA_CODEGEN_SHARED_LIBRARY_H_
| 26.5625 | 75 | 0.746667 | [
"vector"
] |
b87778166eb66456e5ba9b9cf1f340fc8ef6ebc6 | 5,479 | c | C | lib/am335x_sdk/ti/drv/pruss/example/apps/icssg_pwm/firmware/src/main.c | brandonbraun653/Apollo | a1ece2cc3f1d3dae48fdf8fe94f0bbb59d405fce | [
"MIT"
] | 2 | 2021-12-27T10:19:01.000Z | 2022-03-15T07:09:06.000Z | lib/am335x_sdk/ti/drv/pruss/example/apps/icssg_pwm/firmware/src/main.c | brandonbraun653/Apollo | a1ece2cc3f1d3dae48fdf8fe94f0bbb59d405fce | [
"MIT"
] | null | null | null | lib/am335x_sdk/ti/drv/pruss/example/apps/icssg_pwm/firmware/src/main.c | brandonbraun653/Apollo | a1ece2cc3f1d3dae48fdf8fe94f0bbb59d405fce | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2019 Texas Instruments Incorporated - http://www.ti.com/
*
*
* 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 Texas Instruments Incorporated nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "iepPwmFwRegs.h"
#include "iepPwmHwRegs.h"
#include "iepPwm.h"
#include "icssg_iep_pwm.h"
#include "resource_table_empty.h"
void main(void)
{
Int32 status;
IepSm_Config iepSmConfig;
/* Reset PWM FW control object */
status = resetPwmCtrlObj(&gIcssgIepPwmCtrlObj);
if (status != IEP_STS_NERR)
{
/* Indicate Error to Host */
;
}
/* Reset IEP 0 PWM object */
status = resetIepPwmObj(&gIcssgIep0PwmObj, IEP_ID_0);
if (status != IEP_STS_NERR)
{
/* Indicate Error to Host */
;
}
/* Reset IEP 1 PWM object */
status = resetIepPwmObj(&gIcssgIep1PwmObj, IEP_ID_1);
if (status != IEP_STS_NERR)
{
/* Indicate Error to Host */
;
}
/* Wait for PWM enable flag from Host, indicates FW init can commence */
status = waitPwmEnFlag(&gIcssgIepPwmCtrlObj);
if (status != IEP_STS_NERR)
{
/* Indicate Error to Host */
;
}
/* Initialize PWM FW control */
status = initPwmCtrl(&gIcssgIepPwmCtrlObj);
if (status != IEP_STS_NERR)
{
/* Indicate Error to Host */
;
}
/* Initialize IEP0 PWM */
status = initIepPwm(&gIcssgIepPwmCtrlObj, &gIcssgIep0PwmObj);
if (status != IEP_STS_NERR)
{
/* Indicate Error to Host */
;
}
/* Initialize IEP1 PWM */
status = initIepPwm(&gIcssgIepPwmCtrlObj, &gIcssgIep1PwmObj);
if (status != IEP_STS_NERR)
{
/* Indicate Error to Host */
;
}
/* Set PWM FW init flag, indicate FW init complete to Host */
status = setPwmFwInitFlag(&gIcssgIepPwmCtrlObj);
if (status != IEP_STS_NERR)
{
/* Indicate Error to Host */
;
}
/* Get State Machine configuration */
iepSmConfig = getIepPwmSmConfig(&gIcssgIepPwmCtrlObj);
/* Execute State Machine(s) */
if (iepSmConfig == IEP_SM_CONFIG_IEP0)
{
/* IEP0 PWM enabled */
initIepPwmSm(&gIcssgIep0PwmObj);
while (1)
{
gIcssgIep0PwmObj.pIepHwRegs->CMP_STATUS_REG = IEP_CMP_STATUS_CMP1_12_MASK; /* clear all but CMP0 events */
status = execIepPwmSm(&gIcssgIep0PwmObj, TRUE);
if (status != IEP_STS_NERR)
{
/* Indicate Error to Host */
;
}
}
}
else if (iepSmConfig == IEP_SM_CONFIG_IEP1)
{
/* IEP1 PWM enabled */
initIepPwmSm(&gIcssgIep1PwmObj);
while (1)
{
gIcssgIep1PwmObj.pIepHwRegs->CMP_STATUS_REG = IEP_CMP_STATUS_CMP1_12_MASK; /* clear all but CMP0 events */
status = execIepPwmSm(&gIcssgIep1PwmObj, TRUE);
if (status != IEP_STS_NERR)
{
/* Indicate Error to Host */
;
}
}
}
else if (iepSmConfig == IEP_SM_CONFIG_IEP0_1)
{
/* IEP0 & IEP1 PWM enabled */
initIepPwmSm(&gIcssgIep0PwmObj);
initIepPwmSm(&gIcssgIep1PwmObj);
while (1)
{
gIcssgIep0PwmObj.pIepHwRegs->CMP_STATUS_REG = IEP_CMP_STATUS_CMP1_12_MASK; /* clear all but CMP0 events */
gIcssgIep1PwmObj.pIepHwRegs->CMP_STATUS_REG = IEP_CMP_STATUS_CMP1_12_MASK; /* clear all but CMP0 events */
status = execIepPwmSm(&gIcssgIep0PwmObj, TRUE);
if (status != IEP_STS_NERR)
{
/* Indicate Error to Host */
;
}
status = execIepPwmSm(&gIcssgIep1PwmObj, FALSE);
if (status != IEP_STS_NERR)
{
/* Indicate Error to Host */
;
}
}
}
else /* iepSmConfig == IEP_SM_CONFIG_NONE */
{
/* Nothing to do */
while (1)
;
}
}
| 31.308571 | 119 | 0.608505 | [
"object"
] |
b87cc5b145cf8731df4205cfb8ee6d42d7b8f278 | 8,619 | h | C | Source/Scene/selection_manager.h | neonkingfr/wildogcad | 6d9798daa672d3ab293579439f38bb279fa376c7 | [
"BSD-3-Clause"
] | null | null | null | Source/Scene/selection_manager.h | neonkingfr/wildogcad | 6d9798daa672d3ab293579439f38bb279fa376c7 | [
"BSD-3-Clause"
] | null | null | null | Source/Scene/selection_manager.h | neonkingfr/wildogcad | 6d9798daa672d3ab293579439f38bb279fa376c7 | [
"BSD-3-Clause"
] | null | null | null | /*******************************************************************************
* Copyright (c) 2007, 2008, CerroKai Development
* 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 CerroKai Development 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 CerroKai Development ``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 CerroKai Development 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 __SELECTION_MANAGER_H__
#define __SELECTION_MANAGER_H__
/*** Included Header Files ***/
#include <Scene/wscnl.h>
/*** Locally Defined Values ***/
//None
/*** Namespace Declaration ***/
namespace __WILDCAT_NAMESPACE__ {
/*** Class Predefines ***/
class WCVisualObject;
/***********************************************~***************************************************/
class WCSelectionType {
public:
WCSelectionType() { }
~WCSelectionType() { }
};
/***********************************************~***************************************************/
class WCSelectionObject : virtual public WCObject {
protected:
bool _isSelected; //!< Selection state
public:
//Constructors and Destructors
WCSelectionObject() : _isSelected(false) { } //!< Default constructor
virtual ~WCSelectionObject() { } //!< Default destructor
//Virtual Methods
virtual WCObject* Associate(void)=0;
virtual void OnSelection(const bool fromManager, std::list<WCVisualObject*> objects)=0; //!< Called on selection
virtual void OnDeselection(const bool fromManager)=0; //!< Called on deselection
virtual inline bool IsSelected(void) const { return this->_isSelected; } //!< Current selection state
};
/***********************************************~***************************************************/
class WCSelectionManager : public WCObject {
private:
WCPerformanceLevel _perfLevel; //!< Performance level indicator
WCScene *_scene; //!< Related scene
GLuint _tex, _depthRenderBuffer; //!< Selection texture and render buffer
GLuint _framebuffer; //!< Selection draw framebuffer
std::map<WCVisualObject*,WCSelectionObject*>_objects; //!< Map of objects to be considered
std::list<WCSelectionObject*> _selected; //!< List of selected items
std::list< std::pair<WCVisualObject*,WCSelectionObject*> > _selectedVisuals; //!< List of selected visual items
std::stack< std::map<WCVisualObject*,WCSelectionObject*> > _stack; //!< Push/pop stack
//Private Methods
void ReadyFramebuffer(void); //!< Prepare the framebuffer
WCColor EncodeColor(const WPInt index); //!< Encode the index value
WPInt DecodeColor(const GLubyte r, const GLubyte g, const GLubyte b); //!< Decode the color values
WPUInt ProcessSingleSelect(std::vector<std::pair<WCVisualObject*,WCSelectionObject*> > &sa, //!< Process a single selection
GLubyte *pixels, bool notify);
WPUInt ProcessRectangleSelect(std::vector<std::pair<WCVisualObject*,WCSelectionObject*> > &sa, //!< Process a rectangular selection
GLubyte *pixels,const WPUInt width, const WPUInt height, bool notify);
WPUInt ProcessSingleSelect(WCSelectionObject **selectionArray, GLubyte *pixels, bool notify); //!< Process a single selection
WPUInt ProcessRectangleSelect(WCSelectionObject **selectionArray, GLubyte *pixels, //!< Process a rectangular selection
const WPUInt width, const WPUInt height, bool notify);
//Deny Access
WCSelectionManager(); //!< Deny access to default constructor
WCSelectionManager(const WCSelectionManager &mgr); //!< Deny access to copy constructor
WCSelectionManager& operator=(const WCSelectionManager &mgr); //!< Deny access to equals operator
public:
//Constructors and Destructors
WCSelectionManager(WCScene *scene); //!< Primary constructor
~WCSelectionManager(); //!< Default destructor
//Inherited Methods
void ReceiveNotice(WCObjectMsg msg, WCObject *sender); //!< Receive notice
//Selection Methods
bool AddObject(WCVisualObject* object, WCSelectionObject *selector); //!< Add a selectable object
bool RemoveObject(WCVisualObject* object); //!< Remove a selectable object
WPUInt Select(const WPUInt &xMin, const WPUInt &xMax, const WPUInt &yMin, const WPUInt &yMax, //!< Query for selection
const bool ¬ify=true);
bool ForceSelection(WCSelectionObject *object, const bool ¬ify=false); //!< Make an object selected
bool ForceDeselection(WCSelectionObject *object, const bool ¬ify=false); //!< Make an object not selected
void PushObjects(void); //!< Push the list of selected items
void PopObjects(void); //!< Pop the list of selected items
void Clear(const bool ¬ify=true); //!< Clear the list of selected items
inline WPUInt Count(void) const { return (WPUInt)this->_selected.size(); } //!< Get number of selected items
inline WPUInt CountVisuals(void) const { return (WPUInt)this->_selectedVisuals.size(); } //!< Get number of selected visual items
std::list<WCSelectionObject*> Selected(void){ return this->_selected; } //!< Get the list of selected items
std::list< std::pair<WCVisualObject*,WCSelectionObject*> > SelectedVisuals(void) { //!< Get the list of selected visual items
return this->_selectedVisuals; }
WCSelectionObject* Top(void) { if (this->_selected.size() > 0) //!< Return the first selected item
return this->_selected.front();
else return NULL; }
WCVisualObject* TopVisual(void) { if (this->_selectedVisuals.size() > 0)
return this->_selectedVisuals.front().first;
else return NULL; }
template <class T>
std::list<T*> FilterSelected(const bool &useAssociate) { std::list<T*> filtered; T* ptr; //!< Filter selected list by certain type
std::list<WCSelectionObject*>::iterator iter = this->_selected.begin();
for (; iter!=this->_selected.end(); iter++) {
if (useAssociate) ptr = dynamic_cast<T*>( (*iter)->Associate() );
else ptr = dynamic_cast<T*>(*iter);
if (ptr != NULL) filtered.push_back(ptr); }
return filtered; }
template <class T>
std::list< std::pair<T*,WCSelectionObject*> > FilterSelectedVisuals(void) { //!< Filter selected visuals by type
std::list<std::pair<T*,WCSelectionObject*> > filtered; T* ptr;
std::list< std::pair<WCVisualObject*,WCSelectionObject*> >::iterator iter;
for (iter = this->_selectedVisuals.begin(); iter!=this->_selectedVisuals.end(); iter++) {
ptr = dynamic_cast<T*>((*iter).first);
if (ptr != NULL) filtered.push_back( std::make_pair(ptr, (*iter).second) ); }
return filtered; }
/*** Friend Functions ***/
friend std::ostream& operator<<(std::ostream& out, WCSelectionManager &sel); //!< Overloaded output operator
};
/***********************************************~***************************************************/
} // End Wildcat Namespace
#endif //__SELECTION_MANAGER_H__
| 51 | 132 | 0.637081 | [
"render",
"object",
"vector"
] |
b888bb8ac1c74c6a9f22c890f8052d69c297b5c3 | 47,437 | c | C | XilinxProcessorIPLib/drivers/dfeequ/src/xdfeequ.c | erique/embeddedsw | 4b5fd15c71405844e03f2c276daa38cfcbb6459b | [
"BSD-2-Clause",
"MIT"
] | 1 | 2021-12-17T18:07:58.000Z | 2021-12-17T18:07:58.000Z | XilinxProcessorIPLib/drivers/dfeequ/src/xdfeequ.c | erique/embeddedsw | 4b5fd15c71405844e03f2c276daa38cfcbb6459b | [
"BSD-2-Clause",
"MIT"
] | null | null | null | XilinxProcessorIPLib/drivers/dfeequ/src/xdfeequ.c | erique/embeddedsw | 4b5fd15c71405844e03f2c276daa38cfcbb6459b | [
"BSD-2-Clause",
"MIT"
] | null | null | null | /******************************************************************************
* Copyright (C) 2021 Xilinx, Inc. All rights reserved.
* SPDX-License-Identifier: MIT
******************************************************************************/
/*****************************************************************************/
/**
*
* @file xdfeequ.c
* @addtogroup xdfeequ_v1_1
* @{
*
* Contains the APIs for the DFE Equalizer Filter component.
*
* <pre>
* MODIFICATION HISTORY:
*
* Ver Who Date Changes
* ----- --- -------- -----------------------------------------------
* 1.0 dc 09/03/20 Initial version
* dc 02/02/21 Remove hard coded device node name
* dc 02/22/21 align driver to current specification
* dc 03/15/21 Add data latency api
* dc 04/06/21 Register with full node name
* dc 04/07/21 Fix bare metal initialisation
* dc 04/20/21 Doxygen documentation update
* dc 05/08/21 Update to common trigger
* 1.1 dc 05/26/21 Update CFG_SHIFT calculation
* dc 07/13/21 Update to common latency requirements
*
* </pre>
*
******************************************************************************/
#include "xdfeequ.h"
#include "xdfeequ_hw.h"
#include <math.h>
#include <metal/io.h>
#include <metal/device.h>
#include <string.h>
#ifdef __BAREMETAL__
#include "sleep.h"
#else
#include <unistd.h>
#endif
/**************************** Macros Definitions ****************************/
#define XDFEEQU_SEQUENCE_ENTRY_NULL 8U /* Null sequence entry flag */
#define XDFEEQU_NO_EMPTY_CCID_FLAG 0xFFFFU /* Not Empty CCID flag */
#define XDFEEQU_U32_NUM_BITS 32U
#define XDFEEQU_COEFF_LOAD_TIMEOUT \
1000U /* Units of us declared in XDFEEQU_WAIT */
#define XDFEEQU_WAIT 10U /* Units of us */
#define XDFEEQU_TAP_MAX 24U /* Maximum tap value */
#define XDFEEQU_DRIVER_VERSION_MINOR 1U
#define XDFEEQU_DRIVER_VERSION_MAJOR 1U
/************************** Function Prototypes *****************************/
/************************** Variable Definitions ****************************/
#ifdef __BAREMETAL__
extern struct metal_device CustomDevice[XDFEEQU_MAX_NUM_INSTANCES];
extern metal_phys_addr_t metal_phys[XDFEEQU_MAX_NUM_INSTANCES];
#endif
extern XDfeEqu XDfeEqu_Equalizer[XDFEEQU_MAX_NUM_INSTANCES];
static u32 XDfeEqu_DriverHasBeenRegisteredOnce = 0U;
/************************** Function Definitions ****************************/
extern s32 XDfeEqu_RegisterMetal(XDfeEqu *InstancePtr,
struct metal_device **DevicePtr,
const char *DeviceNodeName);
extern s32 XDfeEqu_LookupConfig(XDfeEqu *InstancePtr);
extern void XDfeEqu_CfgInitialize(XDfeEqu *InstancePtr);
/************************** Register Access Functions ***********************/
/****************************************************************************/
/**
*
* Writes value to register in an Equalizer instance.
*
* @param InstancePtr is a pointer to the XDfeEqu instance.
* @param AddrOffset is address offset relative to instance base address.
* @param Data is value to be written.
*
****************************************************************************/
void XDfeEqu_WriteReg(const XDfeEqu *InstancePtr, u32 AddrOffset, u32 Data)
{
Xil_AssertVoid(InstancePtr != NULL);
metal_io_write32(InstancePtr->Io, (unsigned long)AddrOffset, Data);
}
/****************************************************************************/
/**
*
* Reads a value from the register using an Equalizer instance.
*
* @param InstancePtr is a pointer to the XDfeEqu instance.
* @param AddrOffset is address offset relative to instance base address.
*
* @return Register value.
*
****************************************************************************/
u32 XDfeEqu_ReadReg(const XDfeEqu *InstancePtr, u32 AddrOffset)
{
Xil_AssertNonvoid(InstancePtr != NULL);
return metal_io_read32(InstancePtr->Io, (unsigned long)AddrOffset);
}
/****************************************************************************/
/**
*
* Writes a bit field value to register.
*
* @param InstancePtr is a pointer to the XDfeEqu instance.
* @param Offset is address offset relative to instance base address.
* @param FieldWidth is a bit field width.
* @param FieldOffset is a bit field offset.
* @param FieldData is a bit field data.
*
****************************************************************************/
void XDfeEqu_WrRegBitField(const XDfeEqu *InstancePtr, u32 Offset,
u32 FieldWidth, u32 FieldOffset, u32 FieldData)
{
u32 Data;
u32 Tmp;
u32 Val;
Xil_AssertVoid(InstancePtr != NULL);
Xil_AssertVoid((FieldOffset + FieldWidth) <= XDFEEQU_U32_NUM_BITS);
Data = XDfeEqu_ReadReg(InstancePtr, Offset);
Val = (FieldData & (((u32)1U << FieldWidth) - 1U)) << FieldOffset;
Tmp = ~((((u32)1U << FieldWidth) - 1U) << FieldOffset);
Data = (Data & Tmp) | Val;
XDfeEqu_WriteReg(InstancePtr, Offset, Data);
}
/****************************************************************************/
/**
*
* Reads a bit field value from the register.
*
* @param InstancePtr is a pointer to the XDfeEqu instance.
* @param Offset is address offset relative to instance base address.
* @param FieldWidth is a bit field width.
* @param FieldOffset is a bit field offset.
*
* @return Bit field data.
*
****************************************************************************/
u32 XDfeEqu_RdRegBitField(const XDfeEqu *InstancePtr, u32 Offset,
u32 FieldWidth, u32 FieldOffset)
{
u32 Data;
Xil_AssertNonvoid(InstancePtr != NULL);
Xil_AssertNonvoid((FieldOffset + FieldWidth) <= XDFEEQU_U32_NUM_BITS);
Data = XDfeEqu_ReadReg(InstancePtr, Offset);
return ((Data >> FieldOffset) & (((u32)1U << FieldWidth) - 1U));
}
/****************************************************************************/
/**
*
* Reads a bit field value from the u32 variable.
*
* @param FieldWidth is a bit field width.
* @param FieldOffset is a bit field offset in bits number.
* @param Data is a u32 data which bit field this function reads.
*
* @return Bit field value.
*
****************************************************************************/
u32 XDfeEqu_RdBitField(u32 FieldWidth, u32 FieldOffset, u32 Data)
{
Xil_AssertNonvoid((FieldOffset + FieldWidth) <= XDFEEQU_U32_NUM_BITS);
return (((Data >> FieldOffset) & (((u32)1U << FieldWidth) - 1U)));
}
/****************************************************************************/
/**
*
* Writes a bit field value to the u32 variable.
*
* @param FieldWidth is a bit field width.
* @param FieldOffset is a bit field offset in bits number.
* @param Data is a u32 data which bit field this function reads.
* @param Val is a u32 value to be written in the bit field.
*
* @return Data with a bit field written.
*
****************************************************************************/
u32 XDfeEqu_WrBitField(u32 FieldWidth, u32 FieldOffset, u32 Data, u32 Val)
{
u32 BitFieldSet;
u32 BitFieldClear;
Xil_AssertNonvoid((FieldOffset + FieldWidth) <= XDFEEQU_U32_NUM_BITS);
BitFieldSet = (Val & (((u32)1U << FieldWidth) - 1U)) << FieldOffset;
BitFieldClear =
Data & (~((((u32)1U << FieldWidth) - 1U) << FieldOffset));
return (BitFieldSet | BitFieldClear);
}
/************************ DFE Common functions ******************************/
/************************ Low Level Functions *******************************/
/****************************************************************************/
/**
*
* Sets Equalizer filter coefficients in Real mode.
*
* @param InstancePtr is a pointer to the Equalizer instance.
* @param ChannelField is a flag which bits indicate channel is enabled.
* @param EqCoeffs is an Equalizer coefficients container.
* @param NumValues is the number of taps.
* @param Shift is shift value.
*
****************************************************************************/
static void XDfeEqu_LoadRealCoefficients(const XDfeEqu *InstancePtr,
u32 ChannelField,
const XDfeEqu_Coefficients *EqCoeffs,
u32 NumValues, u32 Shift)
{
u32 Offset;
u32 Index;
Xil_AssertVoid(InstancePtr != NULL);
Xil_AssertVoid(InstancePtr->StateId == XDFEEQU_STATE_OPERATIONAL);
Xil_AssertVoid(ChannelField <
((u32)1U << XDFEEQU_CHANNEL_FIELD_FIELD_WIDTH));
Xil_AssertVoid(EqCoeffs != NULL);
Xil_AssertVoid(EqCoeffs->Set < (1U << XDFEEQU_SET_TO_WRITE_SET_WIDTH));
Xil_AssertVoid(EqCoeffs->NUnits <= XDFEEQU_MAX_NUMBER_OF_UNITS_REAL);
/* Write the co-efficient set buffer with the following information */
Offset = XDFEEQU_COEFFICIENT_SET;
for (Index = 0; Index < NumValues; Index++) {
XDfeEqu_WriteReg(InstancePtr, Offset,
(u32)(EqCoeffs->Coefficients[Index]));
Offset += (u32)sizeof(u32);
}
Offset = XDFEEQU_SET_TO_WRITE_OFFSET;
XDfeEqu_WriteReg(InstancePtr, Offset, EqCoeffs->Set);
Offset = XDFEEQU_NUMBER_OF_UNITS_OFFSET;
XDfeEqu_WriteReg(InstancePtr, Offset, EqCoeffs->NUnits);
Offset = XDFEEQU_SHIFT_VALUE_OFFSET;
XDfeEqu_WriteReg(InstancePtr, Offset, Shift);
/* Set the Channel_Field register (0x010C) with the value in
Channel_Field. This initiates the write of the co-efficients. */
Offset = XDFEEQU_CHANNEL_FIELD_OFFSET;
XDfeEqu_WriteReg(InstancePtr, Offset, ChannelField);
}
/****************************************************************************/
/**
*
* Sets Equalizer filter coefficients in Complex mode.
*
* @param InstancePtr is a pointer to the Equalizer instance.
* @param ChannelField is a flag in which bits indicate the channel is
* enabled.
* @param EqCoeffs is an Equalizer coefficients container.
* @param NumValues is the number of taps.
* @param Shift is shift value.
*
****************************************************************************/
static void
XDfeEqu_LoadComplexCoefficients(const XDfeEqu *InstancePtr, u32 ChannelField,
const XDfeEqu_Coefficients *EqCoeffs,
u32 NumValues, u32 Shift)
{
u32 Offset;
u32 LoadDone;
u32 Index;
Xil_AssertVoid(InstancePtr != NULL);
Xil_AssertVoid(InstancePtr->StateId == XDFEEQU_STATE_OPERATIONAL);
Xil_AssertVoid(ChannelField <
((u32)1U << XDFEEQU_CHANNEL_FIELD_FIELD_WIDTH));
Xil_AssertVoid(EqCoeffs != NULL);
Xil_AssertVoid(EqCoeffs->Set < (1U << XDFEEQU_SET_TO_WRITE_SET_WIDTH));
Xil_AssertVoid(EqCoeffs->NUnits <= XDFEEQU_MAX_NUMBER_OF_UNITS_COMPLEX);
/* Write the co-efficient set buffer with the following information */
Offset = XDFEEQU_COEFFICIENT_SET;
for (Index = 0; Index < NumValues; Index++) {
XDfeEqu_WriteReg(InstancePtr, Offset,
(u32)(EqCoeffs->Coefficients[Index]));
XDfeEqu_WriteReg(
InstancePtr,
Offset + (XDFEEQU_IM_COEFFICIENT_SET_OFFSET *
sizeof(u32)),
(u32)(EqCoeffs->Coefficients[Index + NumValues]));
Offset += (u32)sizeof(u32);
}
Offset = XDFEEQU_SET_TO_WRITE_OFFSET;
XDfeEqu_WriteReg(InstancePtr, Offset, EqCoeffs->Set);
Offset = XDFEEQU_NUMBER_OF_UNITS_OFFSET;
XDfeEqu_WriteReg(InstancePtr, Offset, EqCoeffs->NUnits);
Offset = XDFEEQU_SHIFT_VALUE_OFFSET;
XDfeEqu_WriteReg(InstancePtr, Offset, Shift);
/* Set the Channel_Field register (0x010C) with the value in
Channel_Field. This initiates the write of the co-efficients. */
Offset = XDFEEQU_CHANNEL_FIELD_OFFSET;
XDfeEqu_WriteReg(InstancePtr, Offset, ChannelField);
/* The software should wait for bit 8 in the Channel_Field register
to go low before returning. */
for (Index = 0; Index < XDFEEQU_COEFF_LOAD_TIMEOUT; Index++) {
LoadDone = XDfeEqu_RdRegBitField(
InstancePtr, Offset, XDFEEQU_CHANNEL_FIELD_DONE_WIDTH,
XDFEEQU_CHANNEL_FIELD_DONE_OFFSET);
if (XDFEEQU_CHANNEL_FIELD_DONE_LOADING_DONE == LoadDone) {
break;
}
usleep(XDFEEQU_WAIT);
if (Index == (XDFEEQU_COEFF_LOAD_TIMEOUT - 1U)) {
Xil_AssertVoidAlways();
}
}
/* Write the co-efficient set buffer with the following information */
Offset = XDFEEQU_COEFFICIENT_SET;
for (Index = 0; Index < NumValues; Index++) {
XDfeEqu_WriteReg(
InstancePtr, Offset,
(u32)(-EqCoeffs->Coefficients[Index + NumValues]));
XDfeEqu_WriteReg(InstancePtr,
Offset + (XDFEEQU_IM_COEFFICIENT_SET_OFFSET *
sizeof(u32)),
(u32)(EqCoeffs->Coefficients[Index]));
Offset += (u32)sizeof(u32);
}
Offset = XDFEEQU_SET_TO_WRITE_OFFSET;
XDfeEqu_WriteReg(InstancePtr, Offset, EqCoeffs->Set + 1U);
Offset = XDFEEQU_NUMBER_OF_UNITS_OFFSET;
XDfeEqu_WriteReg(InstancePtr, Offset, EqCoeffs->NUnits);
Offset = XDFEEQU_SHIFT_VALUE_OFFSET;
XDfeEqu_WriteReg(InstancePtr, Offset, Shift);
/* Set the Channel_Field register (0x010C) with the value in
Channel_Field. This initiates the write of the co-efficients. */
Offset = XDFEEQU_CHANNEL_FIELD_OFFSET;
XDfeEqu_WriteReg(InstancePtr, Offset, ChannelField);
}
/****************************************************************************/
/**
*
* Sets Equalizer filter coefficients in Matrix mode.
*
* @param InstancePtr is a pointer to the Equalizer instance.
* @param ChannelField is a flag in which bits indicate channel is enabled.
* @param EqCoeffs is an Equalizer coefficients container.
* @param NumValues is the number of taps.
* @param Shift is shift value.
*
****************************************************************************/
static void XDfeEqu_LoadMatrixCoefficients(const XDfeEqu *InstancePtr,
u32 ChannelField,
const XDfeEqu_Coefficients *EqCoeffs,
u32 NumValues, u32 Shift)
{
u32 Offset;
u32 Index;
Xil_AssertVoid(InstancePtr != NULL);
Xil_AssertVoid(InstancePtr->StateId == XDFEEQU_STATE_OPERATIONAL);
Xil_AssertVoid(ChannelField <
((u32)1U << XDFEEQU_CHANNEL_FIELD_FIELD_WIDTH));
Xil_AssertVoid(EqCoeffs != NULL);
Xil_AssertVoid(EqCoeffs->Set < (1U << XDFEEQU_SET_TO_WRITE_SET_WIDTH));
Xil_AssertVoid(EqCoeffs->NUnits <= XDFEEQU_MAX_NUMBER_OF_UNITS_COMPLEX);
/* Write the co-efficient set buffer with the following information */
Offset = XDFEEQU_COEFFICIENT_SET;
for (Index = 0; Index < NumValues; Index++) {
XDfeEqu_WriteReg(InstancePtr, Offset,
(u32)(EqCoeffs->Coefficients[Index]));
XDfeEqu_WriteReg(
InstancePtr,
Offset + (XDFEEQU_IM_COEFFICIENT_SET_OFFSET *
sizeof(u32)),
(u32)(EqCoeffs->Coefficients[Index + NumValues]));
Offset += (u32)sizeof(u32);
}
Offset = XDFEEQU_SET_TO_WRITE_OFFSET;
XDfeEqu_WriteReg(InstancePtr, Offset, EqCoeffs->Set);
Offset = XDFEEQU_NUMBER_OF_UNITS_OFFSET;
XDfeEqu_WriteReg(InstancePtr, Offset, EqCoeffs->NUnits);
Offset = XDFEEQU_SHIFT_VALUE_OFFSET;
XDfeEqu_WriteReg(InstancePtr, Offset, Shift);
/* Set the Channel_Field register (0x010C) with the value in
Channel_Field. This initiates the write of the co-efficients. */
Offset = XDFEEQU_CHANNEL_FIELD_OFFSET;
XDfeEqu_WriteReg(InstancePtr, Offset, ChannelField);
}
/****************************************************************************/
/**
*
* Reads the Triggers and sets enable bit of update trigger. If
* Mode = IMMEDIATE, then trigger will be applied immediately.
*
* @param InstancePtr is a pointer to the Equalizer instance.
*
****************************************************************************/
static void XDfeEqu_EnableUpdateTrigger(const XDfeEqu *InstancePtr)
{
u32 Data;
Xil_AssertVoid(InstancePtr != NULL);
Data = XDfeEqu_ReadReg(InstancePtr,
XDFEEQU_NEXT_CONTROL_TRIGGER_OFFSET);
Data = XDfeEqu_WrBitField(XDFEEQU_TRIGGERS_TRIGGER_ENABLE_WIDTH,
XDFEEQU_TRIGGERS_TRIGGER_ENABLE_OFFSET, Data,
XDFEEQU_TRIGGERS_TRIGGER_ENABLE_ENABLED);
XDfeEqu_WriteReg(InstancePtr, XDFEEQU_NEXT_CONTROL_TRIGGER_OFFSET,
Data);
}
/****************************************************************************/
/**
*
* Reads the Triggers and sets enable bit of LowPower trigger.
* If Mode = IMMEDIATE, then trigger will be applied immediately.
*
* @param InstancePtr is a pointer to the Equalizer instance.
*
****************************************************************************/
static void XDfeEqu_EnableLowPowerTrigger(const XDfeEqu *InstancePtr)
{
u32 Data;
Xil_AssertVoid(InstancePtr != NULL);
Data = XDfeEqu_ReadReg(InstancePtr,
XDFEEQU_DYNAMIC_POWER_DOWN_MODE_TRIGGER_OFFSET);
Data = XDfeEqu_WrBitField(XDFEEQU_TRIGGERS_TRIGGER_ENABLE_WIDTH,
XDFEEQU_TRIGGERS_TRIGGER_ENABLE_OFFSET, Data,
XDFEEQU_TRIGGERS_TRIGGER_ENABLE_ENABLED);
XDfeEqu_WriteReg(InstancePtr,
XDFEEQU_DYNAMIC_POWER_DOWN_MODE_TRIGGER_OFFSET, Data);
}
/****************************************************************************/
/**
*
* Reads the Triggers, set enable bit of Activate trigger. If
* Mode = IMMEDIATE, then trigger will be applied immediately.
*
* @param InstancePtr is a pointer to the Equalizer instance.
*
****************************************************************************/
static void XDfeEqu_EnableActivateTrigger(const XDfeEqu *InstancePtr)
{
u32 Data;
Xil_AssertVoid(InstancePtr != NULL);
Data = XDfeEqu_ReadReg(InstancePtr,
XDFEEQU_OPERATIONAL_MODE_TRIGGER_OFFSET);
Data = XDfeEqu_WrBitField(XDFEEQU_TRIGGERS_TRIGGER_ENABLE_WIDTH,
XDFEEQU_TRIGGERS_TRIGGER_ENABLE_OFFSET, Data,
XDFEEQU_TRIGGERS_TRIGGER_ENABLE_ENABLED);
Data = XDfeEqu_WrBitField(XDFEEQU_TRIGGERS_STATE_OUTPUT_WIDTH,
XDFEEQU_TRIGGERS_STATE_OUTPUT_OFFSET, Data,
XDFEEQU_TRIGGERS_STATE_OUTPUT_ENABLED);
XDfeEqu_WriteReg(InstancePtr, XDFEEQU_OPERATIONAL_MODE_TRIGGER_OFFSET,
Data);
}
/****************************************************************************/
/**
*
* Reads the Triggers, set disable bit of Activate trigger. If
* Mode = IMMEDIATE, then trigger will be applied immediately.
*
* @param InstancePtr is a pointer to the Equalizer instance.
*
****************************************************************************/
static void XDfeEqu_EnableDeactivateTrigger(const XDfeEqu *InstancePtr)
{
u32 Data;
Xil_AssertVoid(InstancePtr != NULL);
Data = XDfeEqu_ReadReg(InstancePtr,
XDFEEQU_OPERATIONAL_MODE_TRIGGER_OFFSET);
Data = XDfeEqu_WrBitField(XDFEEQU_TRIGGERS_TRIGGER_ENABLE_WIDTH,
XDFEEQU_TRIGGERS_TRIGGER_ENABLE_OFFSET, Data,
XDFEEQU_TRIGGERS_TRIGGER_ENABLE_ENABLED);
Data = XDfeEqu_WrBitField(XDFEEQU_TRIGGERS_STATE_OUTPUT_WIDTH,
XDFEEQU_TRIGGERS_STATE_OUTPUT_OFFSET, Data,
XDFEEQU_TRIGGERS_STATE_OUTPUT_DISABLED);
XDfeEqu_WriteReg(InstancePtr, XDFEEQU_OPERATIONAL_MODE_TRIGGER_OFFSET,
Data);
}
/****************************************************************************/
/**
*
* Reads the Triggers and resets enable a bit of LowPower trigger.
*
* @param InstancePtr is a pointer to the Equalizer instance.
*
****************************************************************************/
static void XDfeEqu_DisableLowPowerTrigger(const XDfeEqu *InstancePtr)
{
u32 Data;
Xil_AssertVoid(InstancePtr != NULL);
Data = XDfeEqu_ReadReg(InstancePtr,
XDFEEQU_DYNAMIC_POWER_DOWN_MODE_TRIGGER_OFFSET);
Data = XDfeEqu_WrBitField(XDFEEQU_TRIGGERS_TRIGGER_ENABLE_WIDTH,
XDFEEQU_TRIGGERS_TRIGGER_ENABLE_OFFSET, Data,
XDFEEQU_TRIGGERS_TRIGGER_ENABLE_DISABLED);
XDfeEqu_WriteReg(InstancePtr,
XDFEEQU_DYNAMIC_POWER_DOWN_MODE_TRIGGER_OFFSET, Data);
}
/*************************** Init API ***************************************/
/*****************************************************************************/
/**
*
* API initialises one instance of an Equalizer driver.
* Traverse "/sys/bus/platform/device" directory (in Linux), to find registered
* EQU device with the name DeviceNodeName. The first available slot in
* the instances array XDfeEqu_ChFilter[] will be taken as a DeviceNodeName
* object.
*
* @param DeviceNodeName is device node name.
*
* @return
* - pointer to instance if successful.
* - NULL on error.
*
******************************************************************************/
XDfeEqu *XDfeEqu_InstanceInit(const char *DeviceNodeName)
{
u32 Index;
XDfeEqu *InstancePtr;
#ifdef __BAREMETAL__
char Str[XDFEEQU_NODE_NAME_MAX_LENGTH];
char *AddrStr;
u32 Addr;
#endif
Xil_AssertNonvoid(DeviceNodeName != NULL);
Xil_AssertNonvoid(strlen(DeviceNodeName) <
XDFEEQU_NODE_NAME_MAX_LENGTH);
/* Is this first EQU initialisation ever? */
if (0U == XDfeEqu_DriverHasBeenRegisteredOnce) {
/* Set up environment to non-initialized */
for (Index = 0; Index < XDFEEQU_MAX_NUM_INSTANCES; Index++) {
XDfeEqu_Equalizer[Index].StateId =
XDFEEQU_STATE_NOT_READY;
XDfeEqu_Equalizer[Index].NodeName[0] = '\0';
}
XDfeEqu_DriverHasBeenRegisteredOnce = 1U;
}
/*
* Check has DeviceNodeName been already created:
* a) if no, do full initialization
* b) if yes, skip initialization and return the object pointer
*/
for (Index = 0; Index < XDFEEQU_MAX_NUM_INSTANCES; Index++) {
if (0U == strncmp(XDfeEqu_Equalizer[Index].NodeName,
DeviceNodeName, strlen(DeviceNodeName))) {
return &XDfeEqu_Equalizer[Index];
}
}
/*
* Find the available slot for this instance.
*/
for (Index = 0; Index < XDFEEQU_MAX_NUM_INSTANCES; Index++) {
if (XDfeEqu_Equalizer[Index].NodeName[0] == '\0') {
strncpy(XDfeEqu_Equalizer[Index].NodeName,
DeviceNodeName, strlen(DeviceNodeName));
InstancePtr = &XDfeEqu_Equalizer[Index];
goto register_metal;
}
}
/* Failing as there is no available slot. */
return NULL;
register_metal:
#ifdef __BAREMETAL__
memcpy(Str, InstancePtr->NodeName, XDFEEQU_NODE_NAME_MAX_LENGTH);
AddrStr = strtok(Str, ".");
Addr = strtol(AddrStr, NULL, 16);
for (Index = 0; Index < XDFEEQU_MAX_NUM_INSTANCES; Index++) {
if (Addr == metal_phys[Index]) {
InstancePtr->Device = &CustomDevice[Index];
goto bm_register_metal;
}
}
return NULL;
bm_register_metal:
#endif
/* Register libmetal for this OS process */
if (XST_SUCCESS != XDfeEqu_RegisterMetal(InstancePtr,
&InstancePtr->Device,
DeviceNodeName)) {
metal_log(METAL_LOG_ERROR, "\n Failed to register device %s",
DeviceNodeName);
goto return_error;
}
/* Setup config data */
if (XST_FAILURE == XDfeEqu_LookupConfig(InstancePtr)) {
metal_log(METAL_LOG_ERROR, "\n Failed to configure device %s",
DeviceNodeName);
goto return_error;
}
/* Configure HW and the driver instance */
XDfeEqu_CfgInitialize(InstancePtr);
InstancePtr->StateId = XDFEEQU_STATE_READY;
return InstancePtr;
return_error:
InstancePtr->StateId = XDFEEQU_STATE_NOT_READY;
InstancePtr->NodeName[0] = '\0';
return NULL;
}
/*****************************************************************************/
/**
*
* API closes the instance of an Equalizer driver.
*
* @param InstancePtr is a pointer to the XDfeEqu instance.
*
******************************************************************************/
void XDfeEqu_InstanceClose(XDfeEqu *InstancePtr)
{
u32 Index;
Xil_AssertVoid(InstancePtr != NULL);
for (Index = 0; Index < XDFEEQU_MAX_NUM_INSTANCES; Index++) {
/* Find the instance in XDfeEqu_Equalizer array */
if (&XDfeEqu_Equalizer[Index] == InstancePtr) {
/* Release libmetal */
metal_device_close(InstancePtr->Device);
InstancePtr->StateId = XDFEEQU_STATE_NOT_READY;
InstancePtr->NodeName[0] = '\0';
return;
}
}
/* Assert as you should never get to this point. */
Xil_AssertVoidAlways();
return;
}
/****************************************************************************/
/**
*
* This function puts the block into a reset state.
* Sets bit 0 of the Master Reset register (0x4) high.
*
* @param InstancePtr is a pointer to the Equalizer instance.
*
*
****************************************************************************/
void XDfeEqu_Reset(XDfeEqu *InstancePtr)
{
Xil_AssertVoid(InstancePtr != NULL);
Xil_AssertVoid(InstancePtr->StateId != XDFEEQU_STATE_NOT_READY);
/* Put Equalizer in reset */
XDfeEqu_WriteReg(InstancePtr, XDFEEQU_RESET_OFFSET, XDFEEQU_RESET_ON);
InstancePtr->StateId = XDFEEQU_STATE_RESET;
}
/****************************************************************************/
/**
*
* Reads configuration from device tree/xparameters.h and IP registers. S/W
* reset removed by setting bit 0 of the Master Reset register (0x4) low.
*
* @param InstancePtr is a pointer to the Equalizer instance.
* @param Cfg is a pointer to the device config structure.
*
****************************************************************************/
void XDfeEqu_Configure(XDfeEqu *InstancePtr, XDfeEqu_Cfg *Cfg)
{
u32 Version;
u32 ModelParam;
Xil_AssertVoid(InstancePtr != NULL);
Xil_AssertVoid(InstancePtr->StateId == XDFEEQU_STATE_RESET);
Xil_AssertVoid(Cfg != NULL);
/* Read vearsion */
Version = XDfeEqu_ReadReg(InstancePtr, XDFEEQU_VERSION_OFFSET);
Cfg->Version.Patch =
XDfeEqu_RdBitField(XDFEEQU_VERSION_PATCH_WIDTH,
XDFEEQU_VERSION_PATCH_OFFSET, Version);
Cfg->Version.Revision =
XDfeEqu_RdBitField(XDFEEQU_VERSION_REVISION_WIDTH,
XDFEEQU_VERSION_REVISION_OFFSET, Version);
Cfg->Version.Minor =
XDfeEqu_RdBitField(XDFEEQU_VERSION_MINOR_WIDTH,
XDFEEQU_VERSION_MINOR_OFFSET, Version);
Cfg->Version.Major =
XDfeEqu_RdBitField(XDFEEQU_VERSION_MAJOR_WIDTH,
XDFEEQU_VERSION_MAJOR_OFFSET, Version);
/* Copy configs model parameters from InstancePtr */
ModelParam = XDfeEqu_ReadReg(InstancePtr, XDFEEQU_MODEL_PARAM_OFFSET);
InstancePtr->Config.NumChannels =
XDfeEqu_RdBitField(XDFEEQU_MODEL_PARAM_NUM_CHANNELS_WIDTH,
XDFEEQU_MODEL_PARAM_NUM_CHANNELS_OFFSET,
ModelParam);
InstancePtr->Config.SampleWidth =
XDfeEqu_RdBitField(XDFEEQU_MODEL_PARAM_SAMPLE_WIDTH_WIDTH,
XDFEEQU_MODEL_PARAM_SAMPLE_WIDTH_OFFSET,
ModelParam);
InstancePtr->Config.ComplexModel =
XDfeEqu_RdBitField(XDFEEQU_MODEL_PARAM_COMPLEX_MODE_WIDTH,
XDFEEQU_MODEL_PARAM_COMPLEX_MODE_OFFSET,
ModelParam);
InstancePtr->Config.TuserWidth =
XDfeEqu_RdBitField(XDFEEQU_MODEL_PARAM_TUSER_WIDTH_WIDTH,
XDFEEQU_MODEL_PARAM_TUSER_WIDTH_OFFSET,
ModelParam);
Cfg->ModelParams.SampleWidth = InstancePtr->Config.SampleWidth;
Cfg->ModelParams.ComplexModel = InstancePtr->Config.ComplexModel;
Cfg->ModelParams.NumChannels = InstancePtr->Config.NumChannels;
Cfg->ModelParams.TuserWidth = InstancePtr->Config.TuserWidth;
/* Release RESET */
XDfeEqu_WriteReg(InstancePtr, XDFEEQU_RESET_OFFSET, XDFEEQU_RESET_OFF);
InstancePtr->StateId = XDFEEQU_STATE_CONFIGURED;
}
/****************************************************************************/
/**
*
* DFE Equalizer driver one time initialisation.
*
* @param InstancePtr is a pointer to the Equalizer instance.
* @param Config is a configuration data container.
*
****************************************************************************/
void XDfeEqu_Initialize(XDfeEqu *InstancePtr, const XDfeEqu_EqConfig *Config)
{
XDfeEqu_Trigger Update;
u32 Data;
Xil_AssertVoid(InstancePtr != NULL);
Xil_AssertVoid(InstancePtr->StateId == XDFEEQU_STATE_CONFIGURED);
Xil_AssertVoid(Config != NULL);
Xil_AssertVoid(Config->DatapathMode <= XDFEEQU_DATAPATH_MODE_MATRIX);
Data = XDfeEqu_ReadReg(InstancePtr, XDFEEQU_NEXT_CONTROL_OFFSET);
/* The software sets bit 2 of the Next Control register to:
- high if Config.DatapathMode is set to complex or matrix
- low if Config.DatapathMode is set to real. */
if (Config->DatapathMode == XDFEEQU_DATAPATH_MODE_REAL) {
Data = XDfeEqu_WrBitField(XDFEEQU_COMPLEX_MODE_WIDTH,
XDFEEQU_COMPLEX_MODE_OFFSET, Data,
XDFEEQU_REAL_MODE);
} else {
Data = XDfeEqu_WrBitField(XDFEEQU_COMPLEX_MODE_WIDTH,
XDFEEQU_COMPLEX_MODE_OFFSET, Data,
XDFEEQU_COMPLEX_MODE);
}
/* Trigger NEXT_CONTROL (UPDATE) immediately using Register source to
update CURRENT from NEXT */
Update.TriggerEnable = XDFEEQU_TRIGGERS_TRIGGER_ENABLE_ENABLED;
Update.Mode = XDFEEQU_TRIGGERS_MODE_IMMEDIATE;
Data = XDfeEqu_ReadReg(InstancePtr,
XDFEEQU_NEXT_CONTROL_TRIGGER_OFFSET);
Data = XDfeEqu_WrBitField(XDFEEQU_TRIGGERS_TRIGGER_ENABLE_WIDTH,
XDFEEQU_TRIGGERS_TRIGGER_ENABLE_OFFSET, Data,
Update.TriggerEnable);
Data = XDfeEqu_WrBitField(XDFEEQU_TRIGGERS_MODE_WIDTH,
XDFEEQU_TRIGGERS_MODE_OFFSET, Data,
Update.Mode);
XDfeEqu_WriteReg(InstancePtr, XDFEEQU_NEXT_CONTROL_TRIGGER_OFFSET,
Data);
InstancePtr->StateId = XDFEEQU_STATE_INITIALISED;
}
/*****************************************************************************/
/**
*
* Activates mixer.
*
* @param InstancePtr is a pointer to the Equalizer instance.
* @param EnableLowPower is a flag indicating low power.
*
******************************************************************************/
void XDfeEqu_Activate(XDfeEqu *InstancePtr, bool EnableLowPower)
{
u32 IsOperational;
Xil_AssertVoid(InstancePtr != NULL);
Xil_AssertVoid((InstancePtr->StateId == XDFEEQU_STATE_INITIALISED) ||
(InstancePtr->StateId == XDFEEQU_STATE_OPERATIONAL));
/* Do nothing if the block already operational */
IsOperational =
XDfeEqu_RdRegBitField(InstancePtr,
XDFEEQU_CURRENT_OPERATIONAL_MODE_OFFSET,
XDFEEQU_CURRENT_MODE_OPERATIONAL_WIDTH,
XDFEEQU_CURRENT_MODE_OPERATIONAL_OFFSET);
if (IsOperational == XDFEEQU_CURRENT_MODE_OPERATIONAL_ENABLED) {
return;
}
/* Enable the Activate trigger and set to one-shot */
XDfeEqu_EnableActivateTrigger(InstancePtr);
/* Enable the LowPower trigger, set to continuous triggering */
if (EnableLowPower == true) {
XDfeEqu_EnableLowPowerTrigger(InstancePtr);
}
/* Equalizer is operational now, change a state */
InstancePtr->StateId = XDFEEQU_STATE_OPERATIONAL;
}
/*****************************************************************************/
/**
*
* Deactivates chfilter.
*
* @param InstancePtr is a pointer to the Equalizer instance.
*
******************************************************************************/
void XDfeEqu_Deactivate(XDfeEqu *InstancePtr)
{
u32 IsOperational;
Xil_AssertVoid(InstancePtr != NULL);
Xil_AssertVoid((InstancePtr->StateId == XDFEEQU_STATE_INITIALISED) ||
(InstancePtr->StateId == XDFEEQU_STATE_OPERATIONAL));
/* Do nothing if the block already deactivated */
IsOperational =
XDfeEqu_RdRegBitField(InstancePtr,
XDFEEQU_CURRENT_OPERATIONAL_MODE_OFFSET,
XDFEEQU_CURRENT_MODE_OPERATIONAL_WIDTH,
XDFEEQU_CURRENT_MODE_OPERATIONAL_OFFSET);
if (IsOperational == XDFEEQU_CURRENT_MODE_OPERATIONAL_DISABLED) {
return;
}
/* Disable LowPower trigger (may not be enabled) */
XDfeEqu_DisableLowPowerTrigger(InstancePtr);
/* Disable Activate trigger */
XDfeEqu_EnableDeactivateTrigger(InstancePtr);
InstancePtr->StateId = XDFEEQU_STATE_INITIALISED;
}
/*************************** Component API **********************************/
/****************************************************************************/
/**
*
* The software first sets bits 7:4 of the Next Control register (0x24) with
* the values in Config.Real_Datapath_Set, Config.Im_Datapath_Set.
* In real mode bits, 5:4 are set to the value held in
* Config.Real_Datapath_Set.
* Bits 7:6 are set to the value held in Config.Real_Datapath_Set.
* In complex mode bits, 5:4 are set to the value held in value
* Config.Real_Datapath_Set. Bits 7:6 are set to the value held in
* Config.Real_Datapath_Set plus 1.
* In matrix mode bits 5:4 are set to the value held in
* Config.Real_Datapath_Set. Bits 7:6 are set to the value held in
* Config.Im_Datapath_Set.
* The software sets bit 1 depending on Config.Flush.
* The software then sets the _Enable bit in the Next Control Trigger
* Source register (0x28) high.
*
* @param InstancePtr is a pointer to the Equalizer instance.
* @param Config configuration container.
*
****************************************************************************/
void XDfeEqu_Update(const XDfeEqu *InstancePtr, const XDfeEqu_EqConfig *Config)
{
u32 Offset;
u32 Data;
u32 ReTmp;
u32 ImTmp;
u32 CoeffTmp;
u32 FlushTmp;
Xil_AssertVoid(InstancePtr != NULL);
Xil_AssertVoid(Config != NULL);
Offset = XDFEEQU_CURRENT_CONTROL_OFFSET;
Data = XDfeEqu_ReadReg(InstancePtr, Offset);
/* Set bits 7:4 of the Next Control register (0x24) with the values in
Config.Real_Datapath_Set, Config.Im_Datapath_Set. */
ReTmp = Config->RealDatapathSet & XDFEEQU_COEFF_SET_CONTROL_MASK;
if (XDFEEQU_DATAPATH_MODE_COMPLEX == Config->DatapathMode) {
ImTmp = Config->RealDatapathSet + 1U;
} else {
ImTmp = Config->ImDatapathSet;
}
ImTmp &= XDFEEQU_COEFF_SET_CONTROL_MASK;
CoeffTmp = ReTmp | (ImTmp << XDFEEQU_COEFF_SET_CONTROL_IM_OFFSET);
Data = XDfeEqu_WrBitField(XDFEEQU_COEFF_SET_CONTROL_WIDTH,
XDFEEQU_COEFF_SET_CONTROL_OFFSET, Data,
CoeffTmp);
/* The software sets bit 1 depending on Config.Flush */
FlushTmp = Config->Flush & XDFEEQU_FLUSH_BUFFERS_WIDTH;
Data = XDfeEqu_WrBitField(XDFEEQU_FLUSH_BUFFERS_WIDTH,
XDFEEQU_FLUSH_BUFFERS_OFFSET, Data, FlushTmp);
XDfeEqu_WriteReg(InstancePtr, XDFEEQU_NEXT_CONTROL_OFFSET, Data);
XDfeEqu_EnableUpdateTrigger(InstancePtr);
}
/****************************************************************************/
/**
*
* Returns current trigger configuration.
*
* @param InstancePtr is a pointer to the Ccf instance.
* @param TriggerCfg is a trigger configuration container.
*
****************************************************************************/
void XDfeEqu_GetTriggersCfg(const XDfeEqu *InstancePtr,
XDfeEqu_TriggerCfg *TriggerCfg)
{
u32 Val;
Xil_AssertVoid(InstancePtr != NULL);
Xil_AssertVoid(InstancePtr->StateId != XDFEEQU_STATE_NOT_READY);
Xil_AssertVoid(TriggerCfg != NULL);
/* Read OPERATIONAL (ACTIVATE) triggers */
Val = XDfeEqu_ReadReg(InstancePtr,
XDFEEQU_OPERATIONAL_MODE_TRIGGER_OFFSET);
TriggerCfg->Activate.TriggerEnable =
XDfeEqu_RdBitField(XDFEEQU_TRIGGERS_TRIGGER_ENABLE_WIDTH,
XDFEEQU_TRIGGERS_TRIGGER_ENABLE_OFFSET, Val);
TriggerCfg->Activate.Mode = XDfeEqu_RdBitField(
XDFEEQU_TRIGGERS_MODE_WIDTH, XDFEEQU_TRIGGERS_MODE_OFFSET, Val);
TriggerCfg->Activate.TUSERBit =
XDfeEqu_RdBitField(XDFEEQU_TRIGGERS_TUSER_BIT_WIDTH,
XDFEEQU_TRIGGERS_TUSER_BIT_OFFSET, Val);
TriggerCfg->Activate.TuserEdgeLevel =
XDfeEqu_RdBitField(XDFEEQU_TRIGGERS_TUSER_EDGE_LEVEL_WIDTH,
XDFEEQU_TRIGGERS_TUSER_EDGE_LEVEL_OFFSET,
Val);
TriggerCfg->Activate.StateOutput =
XDfeEqu_RdBitField(XDFEEQU_TRIGGERS_STATE_OUTPUT_WIDTH,
XDFEEQU_TRIGGERS_STATE_OUTPUT_OFFSET, Val);
/* Read LOW_POWER triggers */
Val = XDfeEqu_ReadReg(InstancePtr,
XDFEEQU_DYNAMIC_POWER_DOWN_MODE_TRIGGER_OFFSET);
TriggerCfg->LowPower.TriggerEnable =
XDfeEqu_RdBitField(XDFEEQU_TRIGGERS_TRIGGER_ENABLE_WIDTH,
XDFEEQU_TRIGGERS_TRIGGER_ENABLE_OFFSET, Val);
TriggerCfg->LowPower.Mode = XDfeEqu_RdBitField(
XDFEEQU_TRIGGERS_MODE_WIDTH, XDFEEQU_TRIGGERS_MODE_OFFSET, Val);
TriggerCfg->LowPower.TUSERBit =
XDfeEqu_RdBitField(XDFEEQU_TRIGGERS_TUSER_BIT_WIDTH,
XDFEEQU_TRIGGERS_TUSER_BIT_OFFSET, Val);
TriggerCfg->LowPower.TuserEdgeLevel =
XDfeEqu_RdBitField(XDFEEQU_TRIGGERS_TUSER_EDGE_LEVEL_WIDTH,
XDFEEQU_TRIGGERS_TUSER_EDGE_LEVEL_OFFSET,
Val);
TriggerCfg->LowPower.StateOutput =
XDfeEqu_RdBitField(XDFEEQU_TRIGGERS_STATE_OUTPUT_WIDTH,
XDFEEQU_TRIGGERS_STATE_OUTPUT_OFFSET, Val);
/* Read NEXT_CONTROL (UPDATE) triggers */
Val = XDfeEqu_ReadReg(InstancePtr, XDFEEQU_NEXT_CONTROL_TRIGGER_OFFSET);
TriggerCfg->Update.TriggerEnable =
XDfeEqu_RdBitField(XDFEEQU_TRIGGERS_TRIGGER_ENABLE_WIDTH,
XDFEEQU_TRIGGERS_TRIGGER_ENABLE_OFFSET, Val);
TriggerCfg->Update.Mode = XDfeEqu_RdBitField(
XDFEEQU_TRIGGERS_MODE_WIDTH, XDFEEQU_TRIGGERS_MODE_OFFSET, Val);
TriggerCfg->Update.TUSERBit =
XDfeEqu_RdBitField(XDFEEQU_TRIGGERS_TUSER_BIT_WIDTH,
XDFEEQU_TRIGGERS_TUSER_BIT_OFFSET, Val);
TriggerCfg->Update.TuserEdgeLevel =
XDfeEqu_RdBitField(XDFEEQU_TRIGGERS_TUSER_EDGE_LEVEL_WIDTH,
XDFEEQU_TRIGGERS_TUSER_EDGE_LEVEL_OFFSET,
Val);
TriggerCfg->Update.StateOutput =
XDfeEqu_RdBitField(XDFEEQU_TRIGGERS_STATE_OUTPUT_WIDTH,
XDFEEQU_TRIGGERS_STATE_OUTPUT_OFFSET, Val);
}
/****************************************************************************/
/**
*
* Sets trigger configuration.
*
* @param InstancePtr is a pointer to the Equalizer instance.
* @param TriggerCfg is a trigger configuration container.
*
****************************************************************************/
void XDfeEqu_SetTriggersCfg(const XDfeEqu *InstancePtr,
XDfeEqu_TriggerCfg *TriggerCfg)
{
u32 Val;
u32 TUSERWidth;
Xil_AssertVoid(InstancePtr != NULL);
Xil_AssertVoid(InstancePtr->StateId == XDFEEQU_STATE_INITIALISED);
Xil_AssertVoid(TriggerCfg != NULL);
/* Write trigger configuration members */
TUSERWidth =
XDfeEqu_RdRegBitField(InstancePtr,
XDFEEQU_NEXT_CONTROL_TRIGGER_OFFSET,
XDFEEQU_MODEL_PARAM_TUSER_WIDTH_WIDTH,
XDFEEQU_MODEL_PARAM_TUSER_WIDTH_OFFSET);
if (TUSERWidth == 0U) {
TriggerCfg->Activate.Mode = XDFEEQU_TRIGGERS_MODE_IMMEDIATE;
TriggerCfg->LowPower.Mode = XDFEEQU_TRIGGERS_MODE_IMMEDIATE;
TriggerCfg->Update.Mode = XDFEEQU_TRIGGERS_MODE_IMMEDIATE;
} else {
TriggerCfg->Activate.Mode =
XDFEEQU_TRIGGERS_MODE_TUSER_SINGLE_SHOT;
TriggerCfg->LowPower.Mode =
XDFEEQU_TRIGGERS_MODE_TUSER_CONTINUOUS;
TriggerCfg->Update.Mode =
XDFEEQU_TRIGGERS_MODE_TUSER_SINGLE_SHOT;
}
/* Activate defined as SingleShot (as per the programming model) or
immediate if there is no TUSER on the IP. */
/* Read/set/write OPERATIONAL (ACTIVATE) triggers */
TriggerCfg->Activate.TriggerEnable =
XDFEEQU_TRIGGERS_TRIGGER_ENABLE_DISABLED;
Val = XDfeEqu_ReadReg(InstancePtr,
XDFEEQU_OPERATIONAL_MODE_TRIGGER_OFFSET);
Val = XDfeEqu_WrBitField(XDFEEQU_TRIGGERS_TRIGGER_ENABLE_WIDTH,
XDFEEQU_TRIGGERS_TRIGGER_ENABLE_OFFSET, Val,
TriggerCfg->Activate.TriggerEnable);
Val = XDfeEqu_WrBitField(XDFEEQU_TRIGGERS_MODE_WIDTH,
XDFEEQU_TRIGGERS_MODE_OFFSET, Val,
TriggerCfg->Activate.Mode);
Val = XDfeEqu_WrBitField(XDFEEQU_TRIGGERS_TUSER_EDGE_LEVEL_WIDTH,
XDFEEQU_TRIGGERS_TUSER_EDGE_LEVEL_OFFSET, Val,
TriggerCfg->Activate.TuserEdgeLevel);
Val = XDfeEqu_WrBitField(XDFEEQU_TRIGGERS_TUSER_BIT_WIDTH,
XDFEEQU_TRIGGERS_TUSER_BIT_OFFSET, Val,
TriggerCfg->Activate.TUSERBit);
Val = XDfeEqu_WrBitField(XDFEEQU_TRIGGERS_STATE_OUTPUT_WIDTH,
XDFEEQU_TRIGGERS_STATE_OUTPUT_OFFSET, Val,
TriggerCfg->Activate.StateOutput);
XDfeEqu_WriteReg(InstancePtr, XDFEEQU_OPERATIONAL_MODE_TRIGGER_OFFSET,
Val);
/* LowPower defined as Continuous */
TriggerCfg->LowPower.TriggerEnable =
XDFEEQU_TRIGGERS_TRIGGER_ENABLE_DISABLED;
/* Read/set/write LOW_POWER triggers */
Val = XDfeEqu_ReadReg(InstancePtr,
XDFEEQU_DYNAMIC_POWER_DOWN_MODE_TRIGGER_OFFSET);
Val = XDfeEqu_WrBitField(XDFEEQU_TRIGGERS_TRIGGER_ENABLE_WIDTH,
XDFEEQU_TRIGGERS_TRIGGER_ENABLE_OFFSET, Val,
TriggerCfg->LowPower.TriggerEnable);
Val = XDfeEqu_WrBitField(XDFEEQU_TRIGGERS_MODE_WIDTH,
XDFEEQU_TRIGGERS_MODE_OFFSET, Val,
TriggerCfg->LowPower.Mode);
Val = XDfeEqu_WrBitField(XDFEEQU_TRIGGERS_TUSER_EDGE_LEVEL_WIDTH,
XDFEEQU_TRIGGERS_TUSER_EDGE_LEVEL_OFFSET, Val,
TriggerCfg->LowPower.TuserEdgeLevel);
Val = XDfeEqu_WrBitField(XDFEEQU_TRIGGERS_TUSER_BIT_WIDTH,
XDFEEQU_TRIGGERS_TUSER_BIT_OFFSET, Val,
TriggerCfg->LowPower.TUSERBit);
Val = XDfeEqu_WrBitField(XDFEEQU_TRIGGERS_STATE_OUTPUT_WIDTH,
XDFEEQU_TRIGGERS_STATE_OUTPUT_OFFSET, Val,
TriggerCfg->LowPower.StateOutput);
XDfeEqu_WriteReg(InstancePtr,
XDFEEQU_DYNAMIC_POWER_DOWN_MODE_TRIGGER_OFFSET, Val);
/* Update defined as SingleShot (as per the programming model) */
/* Read/set/write NEXT_CONTROL (UPDATE) triggers */
TriggerCfg->Update.TriggerEnable =
XDFEEQU_TRIGGERS_TRIGGER_ENABLE_DISABLED;
Val = XDfeEqu_ReadReg(InstancePtr, XDFEEQU_NEXT_CONTROL_TRIGGER_OFFSET);
Val = XDfeEqu_WrBitField(XDFEEQU_TRIGGERS_TRIGGER_ENABLE_WIDTH,
XDFEEQU_TRIGGERS_TRIGGER_ENABLE_OFFSET, Val,
TriggerCfg->Update.TriggerEnable);
Val = XDfeEqu_WrBitField(XDFEEQU_TRIGGERS_MODE_WIDTH,
XDFEEQU_TRIGGERS_MODE_OFFSET, Val,
TriggerCfg->Update.Mode);
Val = XDfeEqu_WrBitField(XDFEEQU_TRIGGERS_TUSER_EDGE_LEVEL_WIDTH,
XDFEEQU_TRIGGERS_TUSER_EDGE_LEVEL_OFFSET, Val,
TriggerCfg->Update.TuserEdgeLevel);
Val = XDfeEqu_WrBitField(XDFEEQU_TRIGGERS_TUSER_BIT_WIDTH,
XDFEEQU_TRIGGERS_TUSER_BIT_OFFSET, Val,
TriggerCfg->Update.TUSERBit);
Val = XDfeEqu_WrBitField(XDFEEQU_TRIGGERS_STATE_OUTPUT_WIDTH,
XDFEEQU_TRIGGERS_STATE_OUTPUT_OFFSET, Val,
TriggerCfg->Update.StateOutput);
XDfeEqu_WriteReg(InstancePtr, XDFEEQU_NEXT_CONTROL_TRIGGER_OFFSET, Val);
}
/****************************************************************************/
/**
*
* Sets Equalizer filter coefficients in Real, Complex or Matrix mode.
*
* @param InstancePtr is a pointer to the Equalizer instance.
* @param ChannelField is a flag in which bits indicate the channel is
* enabled.
* @param Mode is an Equalizer mode.
* @param Shift is a coefficient shift value.
* @param EqCoeffs is the Equalizer coefficients container.
*
****************************************************************************/
void XDfeEqu_LoadCoefficients(const XDfeEqu *InstancePtr, u32 ChannelField,
u32 Mode, u32 Shift,
const XDfeEqu_Coefficients *EqCoeffs)
{
u32 NumValues;
u32 LoadDone;
u32 Index;
Xil_AssertVoid(InstancePtr != NULL);
Xil_AssertVoid(InstancePtr->StateId == XDFEEQU_STATE_OPERATIONAL);
Xil_AssertVoid(ChannelField <
((u32)1U << XDFEEQU_CHANNEL_FIELD_FIELD_WIDTH));
Xil_AssertVoid(Mode <= XDFEEQU_DATAPATH_MODE_MATRIX);
Xil_AssertVoid(EqCoeffs != NULL);
Xil_AssertVoid(EqCoeffs->Set < (1U << XDFEEQU_SET_TO_WRITE_SET_WIDTH));
Xil_AssertVoid(EqCoeffs->NUnits > 0U);
NumValues = EqCoeffs->NUnits * XDFEEQU_TAP_UNIT_SIZE;
/* Check is load in progress */
for (Index = 0; Index < XDFEEQU_COEFF_LOAD_TIMEOUT; Index++) {
LoadDone = XDfeEqu_RdRegBitField(
InstancePtr, XDFEEQU_CHANNEL_FIELD_OFFSET,
XDFEEQU_CHANNEL_FIELD_DONE_WIDTH,
XDFEEQU_CHANNEL_FIELD_DONE_OFFSET);
if (XDFEEQU_CHANNEL_FIELD_DONE_LOADING_DONE == LoadDone) {
/* Loading is finished */
break;
}
usleep(XDFEEQU_WAIT);
if (Index == (XDFEEQU_COEFF_LOAD_TIMEOUT - 1U)) {
/* Loading still on, this is serious problem block
the system */
Xil_AssertVoidAlways();
}
}
/* Write filter coefficients and initiate new coefficient load */
if (Mode == XDFEEQU_DATAPATH_MODE_REAL) {
/* Mode == real */
XDfeEqu_LoadRealCoefficients(InstancePtr, ChannelField,
EqCoeffs, NumValues, Shift);
} else if (Mode == XDFEEQU_DATAPATH_MODE_COMPLEX) {
/* Mode == complex */
XDfeEqu_LoadComplexCoefficients(InstancePtr, ChannelField,
EqCoeffs, NumValues, Shift);
} else {
/* Mode == matrix */
XDfeEqu_LoadMatrixCoefficients(InstancePtr, ChannelField,
EqCoeffs, NumValues, Shift);
}
}
/****************************************************************************/
/**
*
* Gets used coefficients settings.
*
* @param InstancePtr is a pointer to the Equalizer instance.
* @param RealSet is a pointer to a real value.
* @param ImagSet is a pointer to an imaginary value.
*
****************************************************************************/
void XDfeEqu_GetActiveSets(const XDfeEqu *InstancePtr, u32 *RealSet,
u32 *ImagSet)
{
u32 Data;
Xil_AssertVoid(InstancePtr != NULL);
Xil_AssertVoid(InstancePtr->StateId == XDFEEQU_STATE_OPERATIONAL);
Xil_AssertVoid(RealSet != NULL);
Xil_AssertVoid(ImagSet != NULL);
/* Gets the values in bits 7:4 of the Current control register and
populates Config.Real_Datapath_Set and Config.Im_Datapath_Set. */
Data = XDfeEqu_ReadReg(InstancePtr, XDFEEQU_CURRENT_CONTROL_OFFSET);
if (0U != (Data & (1U << XDFEEQU_COMPLEX_MODE_OFFSET))) {
*ImagSet = ((Data >> XDFEEQU_COEFF_SET_CONTROL_OFFSET) >>
XDFEEQU_COEFF_SET_CONTROL_IM_OFFSET) &
XDFEEQU_COEFF_SET_CONTROL_MASK;
*RealSet = (Data >> XDFEEQU_COEFF_SET_CONTROL_OFFSET) &
XDFEEQU_COEFF_SET_CONTROL_MASK;
} else {
*ImagSet = 0U;
*RealSet = (Data >> XDFEEQU_COEFF_SET_CONTROL_OFFSET) &
((1U << XDFEEQU_COEFF_SET_CONTROL_WIDTH) - 1U);
}
}
/****************************************************************************/
/**
*
* Sets the delay, which will be added to TUSER and TLAST (delay matched
* through the IP).
*
* @param InstancePtr is a pointer to the Equalizer instance.
* @param Delay is a requested delay variable.
*
****************************************************************************/
void XDfeEqu_SetTUserDelay(const XDfeEqu *InstancePtr, u32 Delay)
{
Xil_AssertVoid(InstancePtr != NULL);
Xil_AssertVoid(InstancePtr->StateId == XDFEEQU_STATE_INITIALISED);
Xil_AssertVoid(Delay < (1U << XDFEEQU_DELAY_VALUE_WIDTH));
XDfeEqu_WriteReg(InstancePtr, XDFEEQU_DELAY_OFFSET, Delay);
}
/****************************************************************************/
/**
*
* Reads the delay, which will be added to TUSER and TLAST (delay matched
* through the IP).
*
* @param InstancePtr is a pointer to the Equalizer instance.
*
* @return Delay value
*
****************************************************************************/
u32 XDfeEqu_GetTUserDelay(const XDfeEqu *InstancePtr)
{
Xil_AssertNonvoid(InstancePtr != NULL);
return XDfeEqu_RdRegBitField(InstancePtr, XDFEEQU_DELAY_OFFSET,
XDFEEQU_DELAY_VALUE_WIDTH,
XDFEEQU_DELAY_VALUE_OFFSET);
}
/****************************************************************************/
/**
*
* Returns CONFIG.DATA_LATENCY.VALUE + tap, where the tap is between 0
* and 23 in real mode and between 0 and 11 in complex/matrix mode.
*
* @param InstancePtr is a pointer to the Equalizer instance.
* @param Tap is a tap variable.
*
* @return Data latency value.
*
****************************************************************************/
u32 XDfeEqu_GetTDataDelay(const XDfeEqu *InstancePtr, u32 Tap)
{
u32 Data;
Xil_AssertNonvoid(InstancePtr != NULL);
Xil_AssertNonvoid(Tap < XDFEEQU_TAP_MAX);
Data = XDfeEqu_RdRegBitField(InstancePtr, XDFEEQU_DATA_LATENCY_OFFSET,
XDFEEQU_DATA_LATENCY_VALUE_WIDTH,
XDFEEQU_DATA_LATENCY_VALUE_OFFSET);
return (Data + Tap);
}
/*****************************************************************************/
/**
*
* This API gets the driver and HW design version.
*
* @param SwVersion is driver version number.
* @param HwVersion is HW version number.
*
*
******************************************************************************/
void XDfeEqu_GetVersions(const XDfeEqu *InstancePtr, XDfeEqu_Version *SwVersion,
XDfeEqu_Version *HwVersion)
{
u32 Version;
Xil_AssertVoid(InstancePtr->StateId != XDFEEQU_STATE_NOT_READY);
/* Driver version */
SwVersion->Major = XDFEEQU_DRIVER_VERSION_MAJOR;
SwVersion->Minor = XDFEEQU_DRIVER_VERSION_MINOR;
/* Component HW version */
Version = XDfeEqu_ReadReg(InstancePtr, XDFEEQU_VERSION_OFFSET);
HwVersion->Patch =
XDfeEqu_RdBitField(XDFEEQU_VERSION_PATCH_WIDTH,
XDFEEQU_VERSION_PATCH_OFFSET, Version);
HwVersion->Revision =
XDfeEqu_RdBitField(XDFEEQU_VERSION_REVISION_WIDTH,
XDFEEQU_VERSION_REVISION_OFFSET, Version);
HwVersion->Minor =
XDfeEqu_RdBitField(XDFEEQU_VERSION_MINOR_WIDTH,
XDFEEQU_VERSION_MINOR_OFFSET, Version);
HwVersion->Major =
XDfeEqu_RdBitField(XDFEEQU_VERSION_MAJOR_WIDTH,
XDFEEQU_VERSION_MAJOR_OFFSET, Version);
}
/** @} */
| 35.801509 | 80 | 0.670321 | [
"object",
"model"
] |
b89059a713c29ef28003d1951b52da014e9f321e | 2,378 | h | C | src/planner/control/command.h | anuranbaka/Vulcan | 56339f77f6cf64b5fda876445a33e72cd15ce028 | [
"MIT"
] | 3 | 2020-03-05T23:56:14.000Z | 2021-02-17T19:06:50.000Z | src/planner/control/command.h | anuranbaka/Vulcan | 56339f77f6cf64b5fda876445a33e72cd15ce028 | [
"MIT"
] | 1 | 2021-03-07T01:23:47.000Z | 2021-03-07T01:23:47.000Z | src/planner/control/command.h | anuranbaka/Vulcan | 56339f77f6cf64b5fda876445a33e72cd15ce028 | [
"MIT"
] | 1 | 2021-03-03T07:54:16.000Z | 2021-03-03T07:54:16.000Z | /* Copyright (C) 2010-2019, The Regents of The University of Michigan.
All rights reserved.
This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab
under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an
MIT-style License that can be found at "https://github.com/h2ssh/Vulcan".
*/
/**
* \file command.h
* \author Collin Johnson
*
* Definition of ControlCommand.
*/
#ifndef PLANNER_CONTROL_COMMAND_H
#define PLANNER_CONTROL_COMMAND_H
#include "mpepc/metric_planner/task/task.h"
#include "planner/control/task.h"
#include "system/message_traits.h"
#include <cereal/types/memory.hpp>
#include <cereal/types/string.hpp>
#include <cereal/types/vector.hpp>
namespace vulcan
{
namespace planner
{
/**
* ControlCommand describes a task to be performed by the control planner. The command contains identifying information
* about the source of the task along with the task to be performed.
*
* The id and source are used for all communications of ControlResult to identify the task being performed.
*/
class ControlCommand
{
public:
/**
* Default constructor for ControlCommand.
*/
ControlCommand(void) : timestamp_(-1), source_("default constructor") { }
/**
* Constructor for ControlCommand.
*/
ControlCommand(int64_t timestamp, const std::string& source, const std::shared_ptr<ControlTask>& task)
: timestamp_(timestamp)
, source_(source)
, task_(task)
{
}
/**
* timestamp retrieves the timestamp for when this command was created.
*/
int64_t timestamp(void) const { return timestamp_; }
/**
* source retrieves the source of the command.
*/
std::string source(void) const { return source_; }
/**
* task retrieves the task to be performed to satisfy the command.
*/
std::shared_ptr<ControlTask> task(void) const { return task_; }
private:
int64_t timestamp_;
std::string source_;
std::shared_ptr<ControlTask> task_;
// Serialization support
friend class cereal::access;
template <class Archive>
void serialize(Archive& ar)
{
ar(timestamp_, source_, task_);
}
};
} // namespace planner
} // namespace vulcan
DEFINE_SYSTEM_MESSAGE(planner::ControlCommand, ("CONTROL_COMMAND"))
#endif // PLANNER_CONTROL_COMMAND_H
| 25.847826 | 119 | 0.703532 | [
"vector"
] |
b891d59146a120758b65f6ca5c6c43c488b6408f | 19,753 | h | C | Barycentric_coordinates_2/include/CGAL/Barycentric_coordinates_2/Mean_value_coordinates_2.h | ffteja/cgal | c1c7f4ad9a4cd669e33ca07a299062a461581812 | [
"CC0-1.0"
] | 3,227 | 2015-03-05T00:19:18.000Z | 2022-03-31T08:20:35.000Z | Barycentric_coordinates_2/include/CGAL/Barycentric_coordinates_2/Mean_value_coordinates_2.h | ffteja/cgal | c1c7f4ad9a4cd669e33ca07a299062a461581812 | [
"CC0-1.0"
] | 5,574 | 2015-03-05T00:01:56.000Z | 2022-03-31T15:08:11.000Z | Barycentric_coordinates_2/include/CGAL/Barycentric_coordinates_2/Mean_value_coordinates_2.h | ffteja/cgal | c1c7f4ad9a4cd669e33ca07a299062a461581812 | [
"CC0-1.0"
] | 1,274 | 2015-03-05T00:01:12.000Z | 2022-03-31T14:47:56.000Z | // Copyright (c) 2014 INRIA Sophia-Antipolis (France).
// 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) : Dmitry Anisimov, David Bommes, Kai Hormann, Pierre Alliez
//
#ifndef CGAL_BARYCENTRIC_MEAN_VALUE_COORDINATES_2_H
#define CGAL_BARYCENTRIC_MEAN_VALUE_COORDINATES_2_H
#include <CGAL/license/Barycentric_coordinates_2.h>
// Internal includes.
#include <CGAL/Weights/mean_value_weights.h>
#include <CGAL/Barycentric_coordinates_2/internal/utils_2.h>
// [1] Reference: "K. Hormann and M. Floater.
// Mean value coordinates for arbitrary planar polygons.
// ACM Transactions on Graphics, 25(4):1424-1441, 2006.".
// [2] Reference: "M. S. Floater.
// Wachspress and mean value coordinates.
// Proceedings of the 14th International Conference on Approximation Theory.
// G. Fasshauer and L. L. Schumaker (eds.)."
namespace CGAL {
namespace Barycentric_coordinates {
/*!
\ingroup PkgBarycentricCoordinates2RefAnalytic
\brief 2D mean value coordinates.
This class implements 2D mean value coordinates ( \cite cgal:bc:hf-mvcapp-06,
\cite cgal:bc:fhk-gcbcocp-06, \cite cgal:f-mvc-03 ), which can be computed
at any point in the plane.
Mean value coordinates are well-defined everywhere in the plane and are
non-negative in the kernel of a star-shaped polygon. The coordinates are
computed analytically. See more details in the user manual \ref compute_mv_coord "here".
\tparam VertexRange
a model of `ConstRange` whose iterator type is `RandomAccessIterator`
\tparam GeomTraits
a model of `BarycentricTraits_2`
\tparam PointMap
a model of `ReadablePropertyMap` whose key type is `VertexRange::value_type` and
value type is `Point_2`. The default is `CGAL::Identity_property_map`.
*/
template<
typename VertexRange,
typename GeomTraits,
typename PointMap = CGAL::Identity_property_map<typename GeomTraits::Point_2> >
class Mean_value_coordinates_2 {
public:
/// \name Types
/// @{
/// \cond SKIP_IN_MANUAL
using Vertex_range = VertexRange;
using Geom_traits = GeomTraits;
using Point_map = PointMap;
using Vector_2 = typename GeomTraits::Vector_2;
using Area_2 = typename GeomTraits::Compute_area_2;
using Construct_vector_2 = typename GeomTraits::Construct_vector_2;
using Squared_length_2 = typename GeomTraits::Compute_squared_length_2;
using Scalar_product_2 = typename GeomTraits::Compute_scalar_product_2;
using Get_sqrt = internal::Get_sqrt<GeomTraits>;
using Sqrt = typename Get_sqrt::Sqrt;
using Mean_value_weights_2 =
Weights::Mean_value_weights_2<VertexRange, GeomTraits, PointMap>;
/// \endcond
/// Number type.
typedef typename GeomTraits::FT FT;
/// Point type.
typedef typename GeomTraits::Point_2 Point_2;
/// @}
/// \name Initialization
/// @{
/*!
\brief initializes all internal data structures.
This class implements the behavior of mean value coordinates
for 2D query points.
\param polygon
an instance of `VertexRange` with the vertices of a simple polygon
\param policy
one of the `Computation_policy_2`;
the default is `Computation_policy_2::PRECISE_WITH_EDGE_CASES`
\param traits
a traits class with geometric objects, predicates, and constructions;
the default initialization is provided
\param point_map
an instance of `PointMap` that maps a vertex from `polygon` to `Point_2`;
the default initialization is provided
\pre polygon.size() >= 3
\pre polygon is simple
*/
Mean_value_coordinates_2(
const VertexRange& polygon,
const Computation_policy_2 policy
= Computation_policy_2::PRECISE_WITH_EDGE_CASES,
const GeomTraits traits = GeomTraits(),
const PointMap point_map = PointMap()) :
m_polygon(polygon),
m_computation_policy(policy),
m_traits(traits),
m_point_map(point_map),
m_area_2(m_traits.compute_area_2_object()),
m_construct_vector_2(m_traits.construct_vector_2_object()),
m_squared_length_2(m_traits.compute_squared_length_2_object()),
m_scalar_product_2(m_traits.compute_scalar_product_2_object()),
m_sqrt(Get_sqrt::sqrt_object(m_traits)),
m_mean_value_weights_2(
polygon, traits, point_map) {
CGAL_precondition(
polygon.size() >= 3);
CGAL_precondition(
internal::is_simple_2(polygon, traits, point_map));
resize();
}
/// @}
/// \name Access
/// @{
/*!
\brief computes 2D mean value weights.
This function fills `weights` with 2D mean value weights computed at the `query`
point with respect to the vertices of the input polygon. If `query` belongs to
the polygon boundary, the returned weights are normalized.
The number of returned weights equals to the number of polygon vertices.
\tparam OutIterator
a model of `OutputIterator` that accepts values of type `FT`
\param query
a query point
\param w_begin
the beginning of the destination range with the computed weights
\return an output iterator to the element in the destination range,
one past the last weight stored
*/
template<typename OutIterator>
OutIterator weights(const Point_2& query, OutIterator w_begin) {
const bool normalize = false;
return compute(query, w_begin, normalize);
}
/*!
\brief computes 2D mean value coordinates.
This function fills `c_begin` with 2D mean value coordinates computed
at the `query` point with respect to the vertices of the input polygon.
The number of returned coordinates equals to the number of polygon vertices.
After the coordinates \f$b_i\f$ with \f$i = 1\dots n\f$ are computed, where
\f$n\f$ is the number of polygon vertices, the query point \f$q\f$ can be obtained
as \f$q = \sum_{i = 1}^{n}b_ip_i\f$, where \f$p_i\f$ are the polygon vertices.
\tparam OutIterator
a model of `OutputIterator` that accepts values of type `FT`
\param query
a query point
\param c_begin
the beginning of the destination range with the computed coordinates
\return an output iterator to the element in the destination range,
one past the last coordinate stored
*/
template<typename OutIterator>
OutIterator operator()(const Point_2& query, OutIterator c_begin) {
const bool normalize = true;
return compute(query, c_begin, normalize);
}
/// @}
private:
// Fields.
const VertexRange& m_polygon;
const Computation_policy_2 m_computation_policy;
const GeomTraits m_traits;
const PointMap m_point_map;
const Area_2 m_area_2;
const Construct_vector_2 m_construct_vector_2;
const Squared_length_2 m_squared_length_2;
const Scalar_product_2 m_scalar_product_2;
const Sqrt m_sqrt;
Mean_value_weights_2 m_mean_value_weights_2;
std::vector<Vector_2> s;
std::vector<FT> r;
std::vector<FT> A;
std::vector<FT> B;
std::vector<FT> P;
std::vector<FT> w;
// Functions.
void resize() {
s.resize(m_polygon.size());
r.resize(m_polygon.size());
A.resize(m_polygon.size());
B.resize(m_polygon.size());
P.resize(m_polygon.size());
w.resize(m_polygon.size());
}
template<typename OutputIterator>
OutputIterator compute(
const Point_2& query, OutputIterator output, const bool normalize) {
switch (m_computation_policy) {
case Computation_policy_2::PRECISE: {
if (normalize) {
return max_precision_coordinates(query, output);
} else {
std::cerr << "WARNING: you can't use the precise version of unnormalized weights! ";
std::cerr << "They are not valid weights!" << std::endl;
internal::get_default(m_polygon.size(), output);
return output;
}
}
case Computation_policy_2::PRECISE_WITH_EDGE_CASES: {
const auto edge_case = verify(query, output);
if (edge_case == internal::Edge_case::BOUNDARY) {
return output;
}
if (normalize) {
return max_precision_coordinates(query, output);
} else {
std::cerr << "WARNING: you can't use the precise version of unnormalized weights! ";
std::cerr << "They are not valid weights!" << std::endl;
internal::get_default(m_polygon.size(), output);
return output;
}
}
case Computation_policy_2::FAST: {
return m_mean_value_weights_2(query, output, normalize);
}
case Computation_policy_2::FAST_WITH_EDGE_CASES: {
const auto edge_case = verify(query, output);
if (edge_case == internal::Edge_case::BOUNDARY) {
return output;
}
return m_mean_value_weights_2(query, output, normalize);
}
default: {
internal::get_default(m_polygon.size(), output);
return output;
}
}
return output;
}
template<typename OutputIterator>
internal::Edge_case verify(
const Point_2& query, OutputIterator output) const {
const auto result = internal::locate_wrt_polygon_2(
m_polygon, query, m_traits, m_point_map);
if (!result) {
return internal::Edge_case::EXTERIOR;
}
const auto location = (*result).first;
const std::size_t index = (*result).second;
if (location == internal::Query_point_location::ON_UNBOUNDED_SIDE) {
return internal::Edge_case::EXTERIOR;
}
if (
location == internal::Query_point_location::ON_VERTEX ||
location == internal::Query_point_location::ON_EDGE ) {
internal::boundary_coordinates_2(
m_polygon, query, location, index, output, m_traits, m_point_map);
return internal::Edge_case::BOUNDARY;
}
return internal::Edge_case::INTERIOR;
}
template<typename OutputIterator>
OutputIterator max_precision_coordinates(
const Point_2& query, OutputIterator coordinates) {
// Get the number of vertices in the polygon.
const std::size_t n = m_polygon.size();
// Compute vectors s and its lengths r following the pseudo-code
// in the Figure 10 from [1].
const auto& p1 = get(m_point_map, *(m_polygon.begin() + 0));
const auto& p2 = get(m_point_map, *(m_polygon.begin() + 1));
const auto& pn = get(m_point_map, *(m_polygon.begin() + (n - 1)));
s[0] = m_construct_vector_2(query, p1);
r[0] = m_sqrt(m_squared_length_2(s[0]));
// Compute areas A and B following the notation from [1] (see Figure 2).
// Split the loop to make this computation faster.
A[0] = m_area_2(p1, p2, query);
B[0] = m_area_2(pn, p2, query);
for (std::size_t i = 1; i < n - 1; ++i) {
const auto& pi0 = get(m_point_map, *(m_polygon.begin() + (i - 1)));
const auto& pi1 = get(m_point_map, *(m_polygon.begin() + (i + 0)));
const auto& pi2 = get(m_point_map, *(m_polygon.begin() + (i + 1)));
s[i] = m_construct_vector_2(query, pi1);
r[i] = m_sqrt(m_squared_length_2(s[i]));
A[i] = m_area_2(pi1, pi2, query);
B[i] = m_area_2(pi0, pi2, query);
}
const auto& pm = get(m_point_map, *(m_polygon.begin() + (n - 2)));
s[n - 1] = m_construct_vector_2(query, pn);
r[n - 1] = m_sqrt(m_squared_length_2(s[n - 1]));
A[n - 1] = m_area_2(pn, p1, query);
B[n - 1] = m_area_2(pm, p1, query);
// Following section 4.2 from [2] we denote P_j = r_j*r_{j+1} + dot_product(d_j, d_{j+1}).
// Vector s_i from [1] corresponds to that one with the name d_i in [2].
for (std::size_t j = 0; j < n - 1; ++j) {
P[j] = (CGAL::max)(r[j] * r[j + 1] + m_scalar_product_2(s[j], s[j + 1]), FT(0));
}
P[n - 1] = (CGAL::max)(r[n - 1] * r[0] + m_scalar_product_2(s[n - 1], s[0]), FT(0));
// Compute mean value weights using the formula (16) from [2].
// Since the formula (16) always gives positive values,
// we have to add a proper sign to all the weight functions.
w[0] = r[n - 1] * r[1] - m_scalar_product_2(s[n - 1], s[1]);
for (std::size_t j = 1; j < n - 1; ++j) {
w[0] *= P[j];
}
w[0] = sign_of_weight(A[n - 1], A[0], B[0]) * m_sqrt(w[0]);
for (std::size_t i = 1; i < n - 1; ++i) {
w[i] = r[i - 1] * r[i + 1] - m_scalar_product_2(s[i - 1], s[i + 1]);
for (std::size_t j = 0; j < i - 1; ++j) {
w[i] *= P[j];
}
for (std::size_t j = i + 1; j < n; ++j) {
w[i] *= P[j];
}
w[i] = sign_of_weight(A[i - 1], A[i], B[i]) * m_sqrt(w[i]);
}
w[n - 1] = r[n - 2] * r[0] - m_scalar_product_2(s[n - 2], s[0]);
for (std::size_t j = 0; j < n - 2; ++j) {
w[n - 1] *= P[j];
}
w[n - 1] = sign_of_weight(A[n - 2], A[n - 1], B[n - 1]) * m_sqrt(w[n - 1]);
// Return coordinates.
internal::normalize(w);
for (std::size_t i = 0; i < n; ++i) {
*(coordinates++) = w[i];
}
return coordinates;
}
// Return the sign of a mean value weight function.
// We can have 3 different values: 0 if the weight = 0,
// -1 if the weight is negative, and +1 if the weight is positive.
FT sign_of_weight(const FT& A_prev, const FT& A, const FT& B) const {
if (A_prev > FT(0) && A > FT(0) && B <= FT(0)) return FT(1);
if (A_prev < FT(0) && A < FT(0) && B >= FT(0)) return -FT(1);
if (B > FT(0)) return FT(1);
if (B < FT(0)) return -FT(1);
return FT(0);
}
};
/*!
\ingroup PkgBarycentricCoordinates2RefFunctions
\brief computes 2D mean value weights.
This function computes 2D mean value weights at a given `query` point
with respect to the vertices of a simple `polygon`, that is one
weight per vertex. The weights are stored in a destination range
beginning at `w_begin`.
Internally, the class `Mean_value_coordinates_2` is used. If one wants to process
multiple query points, it is better to use that class. When using the free function,
internal memory is allocated for each query point, while when using the class,
it is allocated only once, which is much more efficient. However, for a few query
points, it is easier to use this function. It can also be used when the processing
time is not a concern.
\tparam PointRange
a model of `ConstRange` whose iterator type is `RandomAccessIterator`
and value type is `GeomTraits::Point_2`
\tparam OutIterator
a model of `OutputIterator` that accepts values of type `GeomTraits::FT`
\tparam GeomTraits
a model of `BarycentricTraits_2`
\param polygon
an instance of `PointRange` with 2D points, which form a simple polygon
\param query
a query point
\param w_begin
the beginning of the destination range with the computed weights
\param traits
a traits class with geometric objects, predicates, and constructions;
this parameter can be omitted if the traits class can be deduced from the point type
\param policy
one of the `Computation_policy_2`;
the default is `Computation_policy_2::FAST_WITH_EDGE_CASES`
\return an output iterator to the element in the destination range,
one past the last weight stored
\pre polygon.size() >= 3
\pre polygon is simple
*/
template<
typename PointRange,
typename OutIterator,
typename GeomTraits>
OutIterator mean_value_weights_2(
const PointRange& polygon,
const typename GeomTraits::Point_2& query,
OutIterator w_begin,
const GeomTraits& traits,
const Computation_policy_2 policy =
Computation_policy_2::FAST_WITH_EDGE_CASES) {
Mean_value_coordinates_2<PointRange, GeomTraits>
mean_value(polygon, policy, traits);
return mean_value.weights(query, w_begin);
}
/// \cond SKIP_IN_MANUAL
template<
typename PointRange,
typename OutIterator>
OutIterator mean_value_weights_2(
const PointRange& polygon,
const typename PointRange::value_type& query,
OutIterator w_begin,
const Computation_policy_2 policy =
Computation_policy_2::FAST_WITH_EDGE_CASES) {
using Point_2 = typename PointRange::value_type;
using GeomTraits = typename Kernel_traits<Point_2>::Kernel;
const GeomTraits traits;
return mean_value_weights_2(
polygon, query, w_begin, traits, policy);
}
/// \endcond
/*!
\ingroup PkgBarycentricCoordinates2RefFunctions
\brief computes 2D mean value coordinates.
This function computes 2D mean value coordinates at a given `query` point
with respect to the vertices of a simple `polygon`, that is one
coordinate per vertex. The coordinates are stored in a destination range
beginning at `c_begin`.
Internally, the class `Mean_value_coordinates_2` is used. If one wants to process
multiple query points, it is better to use that class. When using the free function,
internal memory is allocated for each query point, while when using the class,
it is allocated only once, which is much more efficient. However, for a few query
points, it is easier to use this function. It can also be used when the processing
time is not a concern.
\tparam PointRange
a model of `ConstRange` whose iterator type is `RandomAccessIterator`
and value type is `GeomTraits::Point_2`
\tparam OutIterator
a model of `OutputIterator` that accepts values of type `GeomTraits::FT`
\tparam GeomTraits
a model of `BarycentricTraits_2`
\param polygon
an instance of `PointRange` with 2D points, which form a simple polygon
\param query
a query point
\param c_begin
the beginning of the destination range with the computed coordinates
\param traits
a traits class with geometric objects, predicates, and constructions;
this parameter can be omitted if the traits class can be deduced from the point type
\param policy
one of the `Computation_policy_2`;
the default is `Computation_policy_2::PRECISE_WITH_EDGE_CASES`
\return an output iterator to the element in the destination range,
one past the last coordinate stored
\pre polygon.size() >= 3
\pre polygon is simple
*/
template<
typename PointRange,
typename OutIterator,
typename GeomTraits>
OutIterator mean_value_coordinates_2(
const PointRange& polygon,
const typename GeomTraits::Point_2& query,
OutIterator c_begin,
const GeomTraits& traits,
const Computation_policy_2 policy =
Computation_policy_2::PRECISE_WITH_EDGE_CASES) {
Mean_value_coordinates_2<PointRange, GeomTraits>
mean_value(polygon, policy, traits);
return mean_value(query, c_begin);
}
/// \cond SKIP_IN_MANUAL
template<
typename PointRange,
typename OutIterator>
OutIterator mean_value_coordinates_2(
const PointRange& polygon,
const typename PointRange::value_type& query,
OutIterator c_begin,
const Computation_policy_2 policy =
Computation_policy_2::PRECISE_WITH_EDGE_CASES) {
using Point_2 = typename PointRange::value_type;
using GeomTraits = typename Kernel_traits<Point_2>::Kernel;
const GeomTraits traits;
return mean_value_coordinates_2(
polygon, query, c_begin, traits, policy);
}
/// \endcond
} // namespace Barycentric_coordinates
} // namespace CGAL
#endif // CGAL_BARYCENTRIC_MEAN_VALUE_COORDINATES_2_H
| 33.254209 | 96 | 0.66476 | [
"vector",
"model"
] |
b89ae6c59e6d603957a701ac6861ae15bab503cb | 3,515 | h | C | src/workload/stencil/StencilTerminal.h | qzcx/supersim | 34829411d02fd3bd3f3d7a075edef8749eb8748e | [
"Apache-2.0"
] | 17 | 2017-05-09T07:08:41.000Z | 2021-08-03T01:22:09.000Z | src/workload/stencil/StencilTerminal.h | qzcx/supersim | 34829411d02fd3bd3f3d7a075edef8749eb8748e | [
"Apache-2.0"
] | 6 | 2016-12-02T22:07:31.000Z | 2020-04-22T07:43:42.000Z | src/workload/stencil/StencilTerminal.h | qzcx/supersim | 34829411d02fd3bd3f3d7a075edef8749eb8748e | [
"Apache-2.0"
] | 13 | 2016-12-02T22:01:04.000Z | 2020-03-23T16:44:04.000Z | /*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. 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 WORKLOAD_STENCIL_STENCILTERMINAL_H_
#define WORKLOAD_STENCIL_STENCILTERMINAL_H_
#include <json/json.h>
#include <prim/prim.h>
#include <string>
#include <tuple>
#include <vector>
#include "event/Component.h"
#include "workload/Terminal.h"
class Application;
namespace Stencil {
class Application;
class StencilTerminal : public Terminal {
public:
StencilTerminal(
const std::string& _name, const Component* _parent, u32 _id,
const std::vector<u32>& _address, const std::vector<u32>* _termToProc,
const std::vector<u32>* _procToTerm,
const std::vector<std::tuple<u32, u32> >& _exchangeSendMessages,
u32 _exchangeRecvMessages, ::Application* _app, Json::Value _settings);
~StencilTerminal();
void processEvent(void* _event, s32 _type) override;
f64 percentComplete() const;
void start();
protected:
void handleDeliveredMessage(Message* _message) override;
void handleReceivedMessage(Message* _message) override;
private:
// kWaiting = waiting to start
// kCompute = computing
// kExchange = exchanging information in halo
// kCollective = performance collective operation
// kDone = done with all iterations
enum class Fsm : s32 {kWaiting = 0, kCompute = 1, kExchange = 2,
kCollective = 3, kDone = 4};
void advanceFsm(); // enqueue event to perform transition
void transitionFsm(); // called by processEvent
void processReceivedMessage(Message* _message); // called by processEvent
void startCompute();
void finishCompute();
void startExchange();
void handleExchangeMessage(Message* _message);
void finishExchange();
void startCollective();
void handleCollectiveMessage(Message* _message);
void finishCollective();
void generateMessage(u32 _destination, u32 _size, u32 _protocolClass,
u32 _msgType);
static u32 encodeOp(Fsm _state, u32 _iteration);
static Fsm decodeState(u32 _opCode);
static u32 decodeIteration(u32 _opCode);
u32 collectiveDestination(u32 _offset);
u32 collectiveSource(u32 _offset);
// traffic generation
const u32 numIterations_;
const u32 maxPacketSize_; // flits
const std::vector<u32>* termToProc_; // [term]->proc
const std::vector<u32>* procToTerm_; // [proc]->term
const std::vector<std::tuple<u32, u32> > exchangeSendMessages_; // {dst,size}
const u32 exchangeRecvMessages_;
const u32 collectiveSize_;
// protocol classes
const u32 exchangeProtocolClass_;
const u32 collectiveProtocolClass_;
// compute time modeling
const u64 computeDelay_;
// state tracking
u32 iteration_;
Fsm fsm_;
std::unordered_map<u32, u32> exchangeRecvCount_; // [iter]=count
std::unordered_map<u32, std::unordered_set<u32> > collectiveRecv_; // [iter]
u32 collectiveOffset_;
};
} // namespace Stencil
#endif // WORKLOAD_STENCIL_STENCILTERMINAL_H_
| 31.666667 | 80 | 0.737127 | [
"vector"
] |
b89c2ddff7dd288427782a91f84944af93060632 | 4,314 | h | C | include/dsn/utility/string_conv.h | Smityz/rdsn | dccb6b3c273197e334ef02f742dc590894e58be8 | [
"MIT"
] | 2 | 2019-08-01T11:17:19.000Z | 2019-08-01T11:17:22.000Z | include/dsn/utility/string_conv.h | Skysheepwang/rdsn | 4a7eb44a5a6b4591a91475f54bcabb9df2c271f9 | [
"MIT"
] | null | null | null | include/dsn/utility/string_conv.h | Skysheepwang/rdsn | 4a7eb44a5a6b4591a91475f54bcabb9df2c271f9 | [
"MIT"
] | null | null | null | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#pragma once
#include <climits>
#include <cmath>
#include <dsn/utility/string_view.h>
namespace dsn {
namespace internal {
template <typename T>
bool buf2signed(string_view buf, T &result)
{
static_assert(std::is_signed<T>::value, "buf2signed works only with signed integer");
if (buf.empty()) {
return false;
}
std::string str(buf.data(), buf.length());
const int saved_errno = errno;
errno = 0;
char *p = nullptr;
long long v = std::strtoll(str.data(), &p, 0);
if (p - str.data() != str.length()) {
return false;
}
if (v > std::numeric_limits<T>::max() || v < std::numeric_limits<T>::min() || errno != 0) {
return false;
}
if (errno == 0) {
errno = saved_errno;
}
result = v;
return true;
}
template <typename T>
bool buf2unsigned(string_view buf, T &result)
{
static_assert(std::is_unsigned<T>::value, "buf2unsigned works only with unsigned integer");
if (buf.empty()) {
return false;
}
std::string str(buf.data(), buf.length());
const int saved_errno = errno;
errno = 0;
char *p = nullptr;
unsigned long long v = std::strtoull(str.data(), &p, 0);
if (p - str.data() != str.length()) {
return false;
}
if (v > std::numeric_limits<T>::max() || v < std::numeric_limits<T>::min() || errno != 0) {
return false;
}
if (errno == 0) {
errno = saved_errno;
}
// strtoull() will convert a negative integer to an unsigned integer,
// return false in this condition. (but we consider "-0" is correct)
if (v != 0 && str.find('-') != std::string::npos) {
return false;
}
result = v;
return true;
}
} // namespace internal
/// buf2*: `result` will keep unmodified if false is returned.
inline bool buf2int32(string_view buf, int32_t &result)
{
return internal::buf2signed(buf, result);
}
inline bool buf2int64(string_view buf, int64_t &result)
{
return internal::buf2signed(buf, result);
}
inline bool buf2uint64(string_view buf, uint64_t &result)
{
return internal::buf2unsigned(buf, result);
}
inline bool buf2bool(string_view buf, bool &result, bool ignore_case = true)
{
std::string data(buf.data(), buf.length());
if (ignore_case) {
std::transform(data.begin(), data.end(), data.begin(), ::tolower);
}
if (data == "true") {
result = true;
return true;
}
if (data == "false") {
result = false;
return true;
}
return false;
}
inline bool buf2double(string_view buf, double &result)
{
if (buf.empty()) {
return false;
}
std::string str(buf.data(), buf.length());
const int saved_errno = errno;
errno = 0;
char *p = nullptr;
double v = std::strtod(str.data(), &p);
if (p - str.data() != str.length()) {
return false;
}
if (v == HUGE_VAL || v == -HUGE_VAL || std::isnan(v) || errno != 0) {
return false;
}
if (errno == 0) {
errno = saved_errno;
}
result = v;
return true;
}
} // namespace dsn
| 25.526627 | 95 | 0.629578 | [
"transform"
] |
b89ce651bfcc8f09e03554bbf933334688fe561d | 2,722 | h | C | libvig/verified/emap.h | pmdm56/vigor | 0a65733a2b7bf48fc7d6071ea89c1af36f1cba80 | [
"MIT"
] | 36 | 2019-09-06T15:33:31.000Z | 2022-02-02T21:11:36.000Z | libvig/verified/emap.h | pmdm56/vigor | 0a65733a2b7bf48fc7d6071ea89c1af36f1cba80 | [
"MIT"
] | 3 | 2019-10-03T10:33:19.000Z | 2020-08-10T13:06:01.000Z | libvig/verified/emap.h | pmdm56/vigor | 0a65733a2b7bf48fc7d6071ea89c1af36f1cba80 | [
"MIT"
] | 9 | 2019-09-18T15:12:29.000Z | 2021-01-20T12:45:01.000Z | #ifndef _EMAP_H_INCLUDED_
#define _EMAP_H_INCLUDED_
#include "vigor-time.h"
#include "map.h"
#include "vector.h"
#include "double-chain.h"
#include "cht.h"
/*@
inductive emap<T> = emap(list<pair<T, int> > m, list<pair<T, real> > v, dchain ch);
fixpoint emap<T> emap_expire_all<T>(emap<T> em, vigor_time_t t) {
switch(em) { case emap(m, v, ch):
return emap(map_erase_all_fp(m, vector_get_values_fp(v, dchain_get_expired_indexes_fp(ch, t))),
vector_erase_all_fp(v, dchain_get_expired_indexes_fp(ch, t)),
dchain_expire_old_indexes_fp(ch, t));
}
}
fixpoint bool emap_has<T>(emap<T> em, T k) {
switch(em) { case emap(m, v, ch):
return map_has_fp(m, k);
}
}
fixpoint int emap_get<T>(emap<T> em, T k) {
switch(em) { case emap(m, v, ch):
return map_get_fp(m, k);
}
}
fixpoint emap<T> emap_refresh_idx<T>(emap<T> em, int i, vigor_time_t t) {
switch(em) { case emap(m, v, ch):
return emap(m, v, dchain_rejuvenate_fp(ch, i, t));
}
}
fixpoint emap<T> emap_erase<T>(emap<T> em, T k) {
switch(em) { case emap(m, v, ch):
return emap(map_erase_fp(m, k),
update(map_get_fp(m, k), pair(k, 1.0), v),
dchain_remove_index_fp(ch, map_get_fp(m, k)));
}
}
fixpoint bool emap_has_idx<T>(emap<T> em, int i) {
switch(em) { case emap(m, v, ch):
return dchain_allocated_fp(ch, i);
}
}
fixpoint T emap_get_key<T>(emap<T> em, int i) {
switch(em) { case emap(m, v, ch):
return fst(nth(i, v));
}
}
fixpoint emap<T> emap_add<T>(emap<T> em, T k, int i, vigor_time_t t) {
switch(em) { case emap(m, v, ch):
return emap(map_put_fp(m, k, i), update(i, pair(k, 0.75), v), dchain_allocate_fp(ch, i, t));
}
}
fixpoint bool emap_full<T>(emap<T> em) {
switch(em) { case emap(m, v, ch):
return dchain_out_of_space_fp(ch);
}
}
// Consistent hashing table-related
fixpoint bool emap_exists_with_cht<T>(emap<T> em, list<pair<uint32_t, real> > cht, int hash) {
switch(em) { case emap(m, v, ch):
return cht_exists(hash, cht, ch);
}
}
fixpoint int emap_choose_with_cht<T>(emap<T> em, list<pair<uint32_t, real> > cht, int hash) {
switch(em) { case emap(m, v, ch):
return cht_choose(hash, cht, ch);
}
}
// Vector
inductive vector<T> = vector(list<pair<T, real> >);
fixpoint T vector_get<T>(vector<T> v, int i) {
switch(v) { case vector(l):
return fst(nth(i, l));
}
}
fixpoint vector<T> vector_set<T>(vector<T> vec, int i, T val) {
switch(vec) { case vector(l):
return vector(update(i, pair(val, 1.0), l));
}
}
@*/
#endif//_EMAP_H_INCLUDED_
| 26.427184 | 101 | 0.59662 | [
"vector"
] |
b89dff98dabf8d55f5f4c4aec34a95cb25d151ab | 628 | h | C | src/mnetwork/XMLNode_p.h | 0of/WebOS-Magna | a0fe2c9708fd4dd07928c11fcb03fb29fdd2d511 | [
"Apache-2.0"
] | 1 | 2016-03-26T13:25:08.000Z | 2016-03-26T13:25:08.000Z | src/mnetwork/XMLNode_p.h | 0of/WebOS-Magna | a0fe2c9708fd4dd07928c11fcb03fb29fdd2d511 | [
"Apache-2.0"
] | null | null | null | src/mnetwork/XMLNode_p.h | 0of/WebOS-Magna | a0fe2c9708fd4dd07928c11fcb03fb29fdd2d511 | [
"Apache-2.0"
] | null | null | null | #ifndef XMLNODE_P_H
#define XMLNODE_P_H
#include "libxml/tree.h"
#include "XMLNode.h"
namespace Magna{
namespace Network{
typedef std::vector< XMLNode > ChildNodes;
class XMLNode::NodeData{
public:
NodeData();
explicit NodeData( xmlNodePtr node_ptr );
~NodeData();
NodeData *detachingClone();
public:
xmlNodePtr m_node;
AtomicInt m_invRefCount;
String m_name;
String m_content;
XMLAttributes m_attributes;
ChildNodes m_childNodes;
};
}//namespace Network
}//namespace Magna
#endif /*XMLNODE_P_H */ | 17.942857 | 48 | 0.624204 | [
"vector"
] |
b8a210169531517b45a95f6dd33e306d8e769e35 | 2,977 | h | C | app/src/main/c/trs_uart.h | apuder/TRS-80 | 549f4e502a0f34da31e6e6aa635bbd761e3c954f | [
"Apache-2.0"
] | 13 | 2016-08-02T10:09:23.000Z | 2022-02-25T23:52:37.000Z | app/src/main/c/trs_uart.h | apuder/TRS-80 | 549f4e502a0f34da31e6e6aa635bbd761e3c954f | [
"Apache-2.0"
] | 6 | 2015-12-15T05:13:00.000Z | 2020-04-17T05:12:58.000Z | app/src/main/c/trs_uart.h | apuder/TRS-80 | 549f4e502a0f34da31e6e6aa635bbd761e3c954f | [
"Apache-2.0"
] | 4 | 2015-12-14T22:08:18.000Z | 2020-11-14T23:28:11.000Z | /* Copyright (c) 2000, Timothy Mann */
/* $Id: trs_uart.h,v 1.2 2008/06/26 04:39:56 mann Exp $ */
/* This software may be copied, modified, and used for any purpose
* without fee, provided that (1) the above copyright notice is
* retained, and (2) modified versions are clearly marked as having
* been modified, with the modifier's name and the date included. */
/*
* Emulation of the Radio Shack TRS-80 Model I/III/4/4P serial port.
*/
#include <errno.h>
#include "trs.h"
#include "trs_hard.h"
extern void trs_uart_init(int reset_button);
extern int trs_uart_check_avail();
extern int trs_uart_modem_in();
extern void trs_uart_reset_out(int value);
extern int trs_uart_switches_in();
extern void trs_uart_baud_out(int value);
extern int trs_uart_status_in();
extern void trs_uart_control_out(int value);
extern int trs_uart_data_in();
extern void trs_uart_data_out(int value);
extern char *trs_uart_name;
extern int trs_uart_switches;
#define TRS_UART_MODEM 0xE8 /* in */
#define TRS_UART_RESET 0xE8 /* out */
#define TRS_UART_SWITCHES 0xE9 /* in, model I only */
#define TRS_UART_BAUD 0xE9 /* out */
#define TRS_UART_STATUS 0xEA /* in */
#define TRS_UART_CONTROL 0xEA /* out */
#define TRS_UART_DATA 0xEB /* in/out */
/* Bits in TRS_UART_MODEM port */
#define TRS_UART_CTS 0x80
#define TRS_UART_DSR 0x40
#define TRS_UART_CD 0x20
#define TRS_UART_RI 0x10
#define TRS_UART_RCVIN 0x02
/* Bits in TRS_UART_BAUD port */
#define TRS_UART_SNDBAUD(v) (((v)&0xf0)>>4)
#define TRS_UART_RCVBAUD(v) (((v)&0x0f)>>0)
#define TRS_UART_50 0x00
#define TRS_UART_75 0x01
#define TRS_UART_110 0x02
#define TRS_UART_134 0x03
#define TRS_UART_150 0x04
#define TRS_UART_300 0x05
#define TRS_UART_600 0x06
#define TRS_UART_1200 0x07
#define TRS_UART_1800 0x08
#define TRS_UART_2000 0x09
#define TRS_UART_2400 0x0a
#define TRS_UART_3600 0x0b
#define TRS_UART_4800 0x0c
#define TRS_UART_7200 0x0d
#define TRS_UART_9600 0x0e
#define TRS_UART_19200 0x0f
#define TRS_UART_BAUD_TABLE \
{ 50.0, 75.0, 110.0, 134.5, 150.0, 300.0, 600.0, 1200.0, 1800.0, \
2000.0, 2400.0, 3600.0, 4800.0, 7200.0, 9600.0, 19200.0 }
/* Bits in TRS_UART_STATUS port */
#define TRS_UART_RCVD 0x80
#define TRS_UART_SENT 0x40
#define TRS_UART_OVRERR 0x20
#define TRS_UART_FRMERR 0x10
#define TRS_UART_PARERR 0x08
/* Bits in TRS_UART_CONTROL port */
#define TRS_UART_EVENPAR 0x80
#define TRS_UART_WORDMASK 0x60
#define TRS_UART_WORD5 0x00
#define TRS_UART_WORD6 0x40
#define TRS_UART_WORD7 0x20
#define TRS_UART_WORD8 0x60
#define TRS_UART_WORDBITS(v) (((v)&TRS_UART_WORDMASK)>>5)
#define TRS_UART_WORDBITS_TABLE { 5, 7, 6, 8 }
#define TRS_UART_STOP2 0x10
#define TRS_UART_NOPAR 0x08
#define TRS_UART_NOTBREAK 0x04
#define TRS_UART_DTR 0x02 /* mislabelled as RTS in Model I manual */
#define TRS_UART_RTS 0x01 /* mislabelled as DTR in Model I manual */
| 33.449438 | 73 | 0.728586 | [
"model"
] |
b8a59c9c1a4755d39d1a31b4aef6add07c7e34fc | 1,384 | h | C | examples/pxScene2d/external/libnode-v10.15.3/deps/v8/src/lookup-cache.h | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 5,964 | 2016-09-27T03:46:29.000Z | 2022-03-31T16:25:27.000Z | examples/pxScene2d/external/libnode-v10.15.3/deps/v8/src/lookup-cache.h | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 1,432 | 2017-06-21T04:08:48.000Z | 2020-08-25T16:21:15.000Z | examples/pxScene2d/external/libnode-v10.15.3/deps/v8/src/lookup-cache.h | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 1,006 | 2016-09-27T05:17:27.000Z | 2022-03-30T02:46:51.000Z | // Copyright 2016 the V8 project 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 V8_LOOKUP_CACHE_H_
#define V8_LOOKUP_CACHE_H_
#include "src/objects.h"
namespace v8 {
namespace internal {
// Cache for mapping (map, property name) into descriptor index.
// The cache contains both positive and negative results.
// Descriptor index equals kNotFound means the property is absent.
// Cleared at startup and prior to any gc.
class DescriptorLookupCache {
public:
// Lookup descriptor index for (map, name).
// If absent, kAbsent is returned.
inline int Lookup(Map* source, Name* name);
// Update an element in the cache.
inline void Update(Map* source, Name* name, int result);
// Clear the cache.
void Clear();
static const int kAbsent = -2;
private:
DescriptorLookupCache() {
for (int i = 0; i < kLength; ++i) {
keys_[i].source = nullptr;
keys_[i].name = nullptr;
results_[i] = kAbsent;
}
}
static inline int Hash(Object* source, Name* name);
static const int kLength = 64;
struct Key {
Map* source;
Name* name;
};
Key keys_[kLength];
int results_[kLength];
friend class Isolate;
DISALLOW_COPY_AND_ASSIGN(DescriptorLookupCache);
};
} // namespace internal
} // namespace v8
#endif // V8_LOOKUP_CACHE_H_
| 23.457627 | 73 | 0.695809 | [
"object"
] |
b8c2efdd2f3b7caabdf1904b72c07275aa94f592 | 39,976 | h | C | core/sql/sqlcat/TrafDDLdesc.h | apache/incubator-trafodion | 8455c839ad6b6d7b6e04edda5715053095b78046 | [
"Apache-2.0"
] | 148 | 2015-06-18T21:26:04.000Z | 2017-12-25T01:47:01.000Z | core/sql/sqlcat/TrafDDLdesc.h | ditdb/trafodion | 8455c839ad6b6d7b6e04edda5715053095b78046 | [
"Apache-2.0"
] | 1,352 | 2015-06-20T03:05:01.000Z | 2017-12-25T14:13:18.000Z | core/sql/sqlcat/TrafDDLdesc.h | ditdb/trafodion | 8455c839ad6b6d7b6e04edda5715053095b78046 | [
"Apache-2.0"
] | 166 | 2015-06-19T18:52:10.000Z | 2017-12-27T06:19:32.000Z | /**********************************************************************
// @@@ START COPYRIGHT @@@
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
// @@@ END COPYRIGHT @@@
//
**********************************************************************/
#ifndef TRAF_DDL_DESC_H
#define TRAF_DDL_DESC_H
// ****************************************************************************
// This file contains DDLDesc classes. DDLDesc classes are used to store
// object definitions that are read from system and privilege manager metadata.
// The DDLDesc's are referenced by other classes such as NATable and SHOWDDL
// that save and display metadata contents.
//
// When DDL operations are performed, the associated DDLDesc structure is
// flatten out and stored in the text table related to object. When the
// compiler or DDL subsequently require this information, the flattened DDLDesc
// is read from the metadata and expanded. This information can then be used
// by the the different components - such as NATable.
//
// Why are there no initializers for most of these classes? The answer is
// that they are all allocated via the factory function TrafAllocateDDLdesc
// (declared at the end of this file). That function zeroes everything out.
// ****************************************************************************
#include "Platform.h"
#include "NAVersionedObject.h"
#include "charinfo.h"
#include "ComSmallDefs.h"
#define GENHEAP(h) (h ? (NAMemory*)h : CmpCommon::statementHeap())
enum ConstraintType { UNIQUE_CONSTRAINT, PRIMARY_KEY_CONSTRAINT, REF_CONSTRAINT,
CHECK_CONSTRAINT
};
enum desc_nodetype {
DESC_UNKNOWN_TYPE = 0,
DESC_CHECK_CONSTRNTS_TYPE,
DESC_COLUMNS_TYPE,
DESC_CONSTRNTS_TYPE,
DESC_CONSTRNT_KEY_COLS_TYPE,
DESC_FILES_TYPE,
DESC_HBASE_RANGE_REGION_TYPE,
DESC_HISTOGRAM_TYPE,
DESC_HIST_INTERVAL_TYPE,
DESC_INDEXES_TYPE,
DESC_KEYS_TYPE,
DESC_PARTNS_TYPE,
DESC_REF_CONSTRNTS_TYPE,
DESC_TABLE_TYPE,
DESC_USING_MV_TYPE, // MV -- marks an MV using this object
DESC_VIEW_TYPE,
DESC_SCHEMA_LABEL_TYPE,
DESC_SEQUENCE_GENERATOR_TYPE,
DESC_ROUTINE_TYPE,
DESC_LIBRARY_TYPE,
DESC_PRIV_TYPE,
DESC_PRIV_GRANTEE_TYPE,
DESC_PRIV_BITMAP_TYPE
};
class TrafDesc;
typedef NAVersionedObjectPtrTempl<TrafDesc> DescStructPtr;
class TrafCheckConstrntsDesc;
class TrafColumnsDesc;
class TrafConstrntsDesc;
class TrafConstrntKeyColsDesc;
class TrafHbaseRegionDesc;
class TrafHistogramDesc;
class TrafHistIntervalDesc;
class TrafFilesDesc;
class TrafKeysDesc;
class TrafIndexesDesc;
class TrafLibraryDesc;
class TrafPartnsDesc;
class TrafRefConstrntsDesc;
class TrafRoutineDesc;
class TrafSequenceGeneratorDesc;
class TrafTableDesc;
class TrafUsingMvDesc;
class TrafViewDesc;
class TrafPrivDesc;
class TrafPrivGranteeDesc;
class TrafPrivBitmapDesc;
class TrafDesc : public NAVersionedObject {
public:
enum {CURR_VERSION = 1};
TrafDesc(UInt16 nodeType);
TrafDesc() : NAVersionedObject(-1) {}
// ---------------------------------------------------------------------
// Redefine virtual functions required for Versioning.
//----------------------------------------------------------------------
virtual unsigned char getClassVersionID()
{
return 1;
}
virtual void populateImageVersionIDArray()
{
setImageVersionID(0,getClassVersionID());
}
virtual short getClassSize() { return (short)sizeof(TrafDesc); }
virtual Lng32 migrateToNewVersion(NAVersionedObject *&newImage);
virtual char *findVTblPtr(short classID);
virtual Long pack(void *space);
virtual Lng32 unpack(void * base, void * reallocator);
Lng32 validateSize();
Lng32 validateVersion();
UInt16 nodetype;
UInt16 version;
UInt32 descFlags;
DescStructPtr next;
char* descExtension; // extension of descriptor, if it needs to be extended
virtual TrafCheckConstrntsDesc *checkConstrntsDesc() const { return NULL; }
virtual TrafColumnsDesc *columnsDesc() const { return NULL; }
virtual TrafConstrntsDesc *constrntsDesc() const { return NULL; }
virtual TrafConstrntKeyColsDesc *constrntKeyColsDesc() const { return NULL; }
virtual TrafFilesDesc *filesDesc() const { return NULL; }
virtual TrafHbaseRegionDesc *hbaseRegionDesc() const { return NULL; }
virtual TrafHistogramDesc *histogramDesc() const { return NULL; }
virtual TrafHistIntervalDesc *histIntervalDesc() const { return NULL; }
virtual TrafKeysDesc *keysDesc() const { return NULL; }
virtual TrafIndexesDesc *indexesDesc() const { return NULL; }
virtual TrafLibraryDesc *libraryDesc() const { return NULL; }
virtual TrafPartnsDesc *partnsDesc() const { return NULL; }
virtual TrafRefConstrntsDesc *refConstrntsDesc() const { return NULL; }
virtual TrafRoutineDesc *routineDesc() const { return NULL; }
virtual TrafSequenceGeneratorDesc *sequenceGeneratorDesc() const { return NULL; }
virtual TrafTableDesc *tableDesc() const { return NULL; }
virtual TrafUsingMvDesc *usingMvDesc() const { return NULL; }
virtual TrafViewDesc *viewDesc() const { return NULL; }
virtual TrafPrivDesc *privDesc() const { return NULL; }
virtual TrafPrivGranteeDesc *privGranteeDesc() const { return NULL; }
virtual TrafPrivBitmapDesc *privBitmapDesc() const { return NULL; }
};
class TrafCheckConstrntsDesc : public TrafDesc {
public:
// why almost no initializers? see note at top of file
TrafCheckConstrntsDesc() : TrafDesc(DESC_CHECK_CONSTRNTS_TYPE)
{}
// ---------------------------------------------------------------------
// Redefine virtual functions required for Versioning.
//----------------------------------------------------------------------
virtual unsigned char getClassVersionID()
{
return 1;
}
virtual void populateImageVersionIDArray()
{
setImageVersionID(0,getClassVersionID());
}
virtual short getClassSize() { return (short)sizeof(TrafCheckConstrntsDesc); }
virtual Long pack(void *space);
virtual Lng32 unpack(void * base, void * reallocator);
virtual TrafCheckConstrntsDesc *checkConstrntsDesc() const { return (TrafCheckConstrntsDesc*)this; }
char* constrnt_text;
char filler[16];
};
class TrafColumnsDesc : public TrafDesc {
public:
// why almost no initializers? see note at top of file
TrafColumnsDesc() : TrafDesc(DESC_COLUMNS_TYPE)
{};
// ---------------------------------------------------------------------
// Redefine virtual functions required for Versioning.
//----------------------------------------------------------------------
virtual unsigned char getClassVersionID()
{
return 1;
}
virtual void populateImageVersionIDArray()
{
setImageVersionID(0,getClassVersionID());
}
virtual short getClassSize() { return (short)sizeof(TrafColumnsDesc); }
virtual Long pack(void *space);
virtual Lng32 unpack(void * base, void * reallocator);
virtual TrafColumnsDesc *columnsDesc() const { return (TrafColumnsDesc*)this; }
enum ColumnsDescFlags
{
NULLABLE = 0x0001,
ADDED = 0x0002,
UPSHIFTED = 0x0004,
CASEINSENSITIVE = 0x0008,
OPTIONAL = 0x0010
};
void setNullable(NABoolean v)
{(v ? columnsDescFlags |= NULLABLE : columnsDescFlags &= ~NULLABLE); };
NABoolean isNullable() { return (columnsDescFlags & NULLABLE) != 0; };
void setAdded(NABoolean v)
{(v ? columnsDescFlags |= ADDED : columnsDescFlags &= ~ADDED); };
NABoolean isAdded() { return (columnsDescFlags & ADDED) != 0; };
void setUpshifted(NABoolean v)
{(v ? columnsDescFlags |= UPSHIFTED : columnsDescFlags &= ~UPSHIFTED); };
NABoolean isUpshifted() { return (columnsDescFlags & UPSHIFTED) != 0; };
void setCaseInsensitive(NABoolean v)
{(v ? columnsDescFlags |= CASEINSENSITIVE : columnsDescFlags &= ~CASEINSENSITIVE); };
NABoolean isCaseInsensitive() { return (columnsDescFlags & CASEINSENSITIVE) != 0; };
void setOptional(NABoolean v)
{(v ? columnsDescFlags |= OPTIONAL : columnsDescFlags &= ~OPTIONAL); };
NABoolean isOptional() { return (columnsDescFlags & OPTIONAL) != 0; };
rec_datetime_field datetimeStart()
{ return (rec_datetime_field)datetimestart;}
rec_datetime_field datetimeEnd()
{ return (rec_datetime_field)datetimeend;}
ComColumnDefaultClass defaultClass()
{ return (ComColumnDefaultClass)defaultClass_;}
void setDefaultClass(ComColumnDefaultClass v)
{ defaultClass_ = (Int16)v;}
CharInfo::CharSet characterSet()
{ return (CharInfo::CharSet)character_set;}
CharInfo::CharSet encodingCharset()
{ return (CharInfo::CharSet)encoding_charset;}
CharInfo::Collation collationSequence()
{return (CharInfo::Collation)collation_sequence; }
ComParamDirection paramDirection()
{ return (ComParamDirection)paramDirection_;}
void setParamDirection(ComParamDirection v)
{paramDirection_ = (Int16)v; }
char* colname;
Int32 colnumber;
Int32 datatype;
Int32 offset;
Lng32 length;
Lng32 scale;
Lng32 precision;
Int16/*rec_datetime_field*/ datetimestart, datetimeend;
Int16 datetimefractprec, intervalleadingprec;
Int16/*ComColumnDefaultClass*/ defaultClass_;
Int16/*CharInfo::CharSet*/ character_set;
Int16/*CharInfo::CharSet*/ encoding_charset;
Int16/*CharInfo::Collation*/ collation_sequence;
ULng32 hbaseColFlags;
Int16/*ComParamDirection*/ paramDirection_;
char colclass; // 'S' -- system generated, 'U' -- user created
char filler0;
Int64 colFlags;
Int64 columnsDescFlags; // my flags
char* pictureText;
char* defaultvalue;
char* heading;
char* computed_column_text;
char* hbaseColFam;
char* hbaseColQual;
char filler[24];
};
class TrafConstrntKeyColsDesc : public TrafDesc {
public:
enum ConsrntKeyDescFlags
{
SYSTEM_KEY = 0x0001
};
// why almost no initializers? see note at top of file
TrafConstrntKeyColsDesc() : TrafDesc(DESC_CONSTRNT_KEY_COLS_TYPE)
{
constrntKeyColsDescFlags = 0;
}
void setSystemKey(NABoolean v)
{(v ? constrntKeyColsDescFlags |= SYSTEM_KEY: constrntKeyColsDescFlags&= ~SYSTEM_KEY); };
NABoolean isSystemKey() { return (constrntKeyColsDescFlags & SYSTEM_KEY) != 0; };
// ---------------------------------------------------------------------
// Redefine virtual functions required for Versioning.
//----------------------------------------------------------------------
virtual unsigned char getClassVersionID()
{
return 1;
}
virtual void populateImageVersionIDArray()
{
setImageVersionID(0,getClassVersionID());
}
virtual short getClassSize() { return (short)sizeof(TrafConstrntKeyColsDesc); }
virtual Long pack(void *space);
virtual Lng32 unpack(void * base, void * reallocator);
virtual TrafConstrntKeyColsDesc *constrntKeyColsDesc() const { return (TrafConstrntKeyColsDesc*)this; }
char* colname;
Int32 position;
Int64 constrntKeyColsDescFlags; // my flags
char filler[16];
};
class TrafConstrntsDesc : public TrafDesc {
public:
// why almost no initializers? see note at top of file
TrafConstrntsDesc() : TrafDesc(DESC_CONSTRNTS_TYPE)
{}
// ---------------------------------------------------------------------
// Redefine virtual functions required for Versioning.
//----------------------------------------------------------------------
virtual unsigned char getClassVersionID()
{
return 1;
}
virtual void populateImageVersionIDArray()
{
setImageVersionID(0,getClassVersionID());
}
virtual short getClassSize() { return (short)sizeof(TrafConstrntsDesc); }
virtual Long pack(void *space);
virtual Lng32 unpack(void * base, void * reallocator);
virtual TrafConstrntsDesc *constrntsDesc() const { return (TrafConstrntsDesc*)this; }
enum ConstrntsDescFlags
{
ENFORCED = 0x0001,
NOT_SERIALIZED = 0x0002
};
void setEnforced(NABoolean v)
{(v ? constrntsDescFlags |= ENFORCED : constrntsDescFlags &= ~ENFORCED); };
NABoolean isEnforced() { return (constrntsDescFlags & ENFORCED) != 0; };
void setNotSerialized(NABoolean v)
{(v ? constrntsDescFlags |= NOT_SERIALIZED : constrntsDescFlags &= ~NOT_SERIALIZED); };
NABoolean notSerialized() { return (constrntsDescFlags & NOT_SERIALIZED) != 0; };
char* constrntname;
char* tablename;
Int16 /*ConstraintType*/ type;
Int16 fillerInt16;
Int32 colcount;
Int64 constrntsDescFlags; // my flags
DescStructPtr check_constrnts_desc;
DescStructPtr constr_key_cols_desc;
DescStructPtr referenced_constrnts_desc;
DescStructPtr referencing_constrnts_desc;
char filler[24];
};
class TrafFilesDesc : public TrafDesc {
public:
// why almost no initializers? see note at top of file
TrafFilesDesc() : TrafDesc(DESC_FILES_TYPE)
{}
// ---------------------------------------------------------------------
// Redefine virtual functions required for Versioning.
//----------------------------------------------------------------------
virtual unsigned char getClassVersionID()
{
return 1;
}
virtual void populateImageVersionIDArray()
{
setImageVersionID(0,getClassVersionID());
}
virtual short getClassSize() { return (short)sizeof(TrafFilesDesc); }
virtual Long pack(void *space);
virtual Lng32 unpack(void * base, void * reallocator);
virtual TrafFilesDesc *filesDesc() const { return (TrafFilesDesc*)this; }
enum FilesDescFlags
{
AUDITED = 0x0001
};
void setAudited(NABoolean v)
{(v ? filesDescFlags |= AUDITED : filesDescFlags &= ~AUDITED); };
NABoolean isAudited() { return (filesDescFlags & AUDITED) != 0; };
Int64 filesDescFlags; // my flags
DescStructPtr partns_desc;
};
class TrafHbaseRegionDesc : public TrafDesc {
public:
// why almost no initializers? see note at top of file
TrafHbaseRegionDesc() : TrafDesc(DESC_HBASE_RANGE_REGION_TYPE)
{}
// ---------------------------------------------------------------------
// Redefine virtual functions required for Versioning.
//----------------------------------------------------------------------
virtual unsigned char getClassVersionID()
{
return 1;
}
virtual void populateImageVersionIDArray()
{
setImageVersionID(0,getClassVersionID());
}
virtual short getClassSize() { return (short)sizeof(TrafHbaseRegionDesc); }
virtual Long pack(void *space);
virtual Lng32 unpack(void * base, void * reallocator);
virtual TrafHbaseRegionDesc *hbaseRegionDesc() const { return (TrafHbaseRegionDesc*)this; }
Int64 hbaseRegionDescFlags; // my flags
Lng32 beginKeyLen;
Lng32 endKeyLen;
char* beginKey;
char* endKey;
char filler[16];
};
class TrafHistogramDesc : public TrafDesc {
public:
// why almost no initializers? see note at top of file
TrafHistogramDesc() : TrafDesc(DESC_HISTOGRAM_TYPE)
{}
// ---------------------------------------------------------------------
// Redefine virtual functions required for Versioning.
//----------------------------------------------------------------------
virtual unsigned char getClassVersionID()
{
return 1;
}
virtual void populateImageVersionIDArray()
{
setImageVersionID(0,getClassVersionID());
}
virtual short getClassSize() { return (short)sizeof(TrafHistogramDesc); }
virtual Long pack(void *space);
virtual Lng32 unpack(void * base, void * reallocator);
virtual TrafHistogramDesc *histogramDesc() const { return (TrafHistogramDesc*)this; }
char* tablename;
char* histid;
Int32 tablecolnumber;
Int32 colposition;
Float32 rowcount;
Float32 uec;
char* highval;
char* lowval;
Int64 histogramDescFlags; // my flags
DescStructPtr hist_interval_desc;
char filler[24];
};
class TrafHistIntervalDesc : public TrafDesc {
public:
// why almost no initializers? see note at top of file
TrafHistIntervalDesc() : TrafDesc(DESC_HIST_INTERVAL_TYPE)
{}
// ---------------------------------------------------------------------
// Redefine virtual functions required for Versioning.
//----------------------------------------------------------------------
virtual unsigned char getClassVersionID()
{
return 1;
}
virtual void populateImageVersionIDArray()
{
setImageVersionID(0,getClassVersionID());
}
virtual short getClassSize() { return (short)sizeof(TrafHistIntervalDesc); }
virtual Long pack(void *space);
virtual Lng32 unpack(void * base, void * reallocator);
virtual TrafHistIntervalDesc *histIntervalDesc() const { return (TrafHistIntervalDesc*)this; }
char* histid;
char* intboundary;
Float32 rowcount;
Float32 uec;
Int32 intnum;
Int32 fillerInt32;
Int64 histIntervalDescFlags; // my flags
char filler[16];
};
class TrafIndexesDesc : public TrafDesc {
public:
// why almost no initializers? see note at top of file
TrafIndexesDesc() : TrafDesc(DESC_INDEXES_TYPE)
{}
// ---------------------------------------------------------------------
// Redefine virtual functions required for Versioning.
//----------------------------------------------------------------------
virtual unsigned char getClassVersionID()
{
return 1;
}
virtual void populateImageVersionIDArray()
{
setImageVersionID(0,getClassVersionID());
}
virtual short getClassSize() { return (short)sizeof(TrafIndexesDesc); }
virtual Long pack(void *space);
virtual Lng32 unpack(void * base, void * reallocator);
virtual TrafIndexesDesc *indexesDesc() const { return (TrafIndexesDesc*)this; }
enum IndexesDescFlags
{
SYSTEM_TABLE_CODE = 0x0001,
EXPLICIT = 0x0002,
VOLATILE = 0x0004,
IN_MEM_OBJ = 0x0008,
UNIQUE = 0x0010
};
void setSystemTableCode(NABoolean v)
{(v ? indexesDescFlags |= SYSTEM_TABLE_CODE : indexesDescFlags &= ~SYSTEM_TABLE_CODE); };
NABoolean isSystemTableCode() { return (indexesDescFlags & SYSTEM_TABLE_CODE) != 0; };
void setExplicit(NABoolean v)
{(v ? indexesDescFlags |= EXPLICIT : indexesDescFlags &= ~EXPLICIT); };
NABoolean isExplicit() { return (indexesDescFlags & EXPLICIT) != 0; };
void setVolatile(NABoolean v)
{(v ? indexesDescFlags |= VOLATILE : indexesDescFlags &= ~VOLATILE); };
NABoolean isVolatile() { return (indexesDescFlags & VOLATILE) != 0; };
void setInMemoryObject(NABoolean v)
{(v ? indexesDescFlags |= IN_MEM_OBJ : indexesDescFlags &= ~IN_MEM_OBJ); };
NABoolean isInMemoryObject() { return (indexesDescFlags & IN_MEM_OBJ) != 0; };
void setUnique(NABoolean v)
{(v ? indexesDescFlags |= UNIQUE : indexesDescFlags &= ~UNIQUE); };
NABoolean isUnique() { return (indexesDescFlags & UNIQUE) != 0; };
ComPartitioningScheme partitioningScheme()
{ return (ComPartitioningScheme)partitioningScheme_; }
void setPartitioningScheme(ComPartitioningScheme v)
{ partitioningScheme_ = (Int16)v; }
ComRowFormat rowFormat() { return (ComRowFormat)rowFormat_; }
void setRowFormat(ComRowFormat v) { rowFormat_ = (Int16)v; }
char* tablename; // name of the base table
char* indexname; // physical name of index. Different from ext_indexname
// for ARK tables.
Int64 indexUID;
Int32 keytag;
Int32 record_length;
Int32 colcount;
Int32 blocksize;
Int16 /*ComPartitioningScheme*/ partitioningScheme_;
Int16 /*ComRowFormat*/ rowFormat_;
Lng32 numSaltPartns; // number of salted partns created for a seabase table.
Lng32 numInitialSaltRegions; // initial # of regions created for salted table
char filler0[4];
Int64 indexesDescFlags; // my flags
char* hbaseSplitClause;
char* hbaseCreateOptions;
DescStructPtr files_desc;
// Clustering keys columns
DescStructPtr keys_desc;
// Columns that are not part of the clustering key.
// Used specially for vertical partition column(s).
DescStructPtr non_keys_desc;
// for hbase's region keys
DescStructPtr hbase_regionkey_desc;
char filler[16];
};
class TrafKeysDesc : public TrafDesc {
public:
// why almost no initializers? see note at top of file
TrafKeysDesc() : TrafDesc(DESC_KEYS_TYPE)
{}
// ---------------------------------------------------------------------
// Redefine virtual functions required for Versioning.
//----------------------------------------------------------------------
virtual unsigned char getClassVersionID()
{
return 1;
}
virtual void populateImageVersionIDArray()
{
setImageVersionID(0,getClassVersionID());
}
virtual short getClassSize() { return (short)sizeof(TrafKeysDesc); }
virtual Long pack(void *space);
virtual Lng32 unpack(void * base, void * reallocator);
virtual TrafKeysDesc *keysDesc() const { return (TrafKeysDesc*)this; }
enum KeysDescFlags
{
DESCENDING = 0x0001
};
void setDescending(NABoolean v)
{(v ? keysDescFlags |= DESCENDING : keysDescFlags &= ~DESCENDING); };
NABoolean isDescending() { return (keysDescFlags & DESCENDING) != 0; };
char* keyname;
Int32 keyseqnumber;
Int32 tablecolnumber;
Int64 keysDescFlags; // my flags
char* hbaseColFam;
char* hbaseColQual;
char filler[16];
};
class TrafLibraryDesc : public TrafDesc {
public:
// why almost no initializers? see note at top of file
TrafLibraryDesc() : TrafDesc(DESC_LIBRARY_TYPE)
{}
// ---------------------------------------------------------------------
// Redefine virtual functions required for Versioning.
//----------------------------------------------------------------------
virtual unsigned char getClassVersionID()
{
return 1;
}
virtual void populateImageVersionIDArray()
{
setImageVersionID(0,getClassVersionID());
}
virtual short getClassSize() { return (short)sizeof(TrafLibraryDesc); }
virtual Long pack(void *space);
virtual Lng32 unpack(void * base, void * reallocator);
virtual TrafLibraryDesc *libraryDesc() const { return (TrafLibraryDesc*)this; }
char* libraryName;
char* libraryFilename;
Int64 libraryUID;
Int32 libraryVersion;
Int32 libraryOwnerID;
Int32 librarySchemaOwnerID;
char filler[20];
};
class TrafPartnsDesc : public TrafDesc {
public:
// why almost no initializers? see note at top of file
TrafPartnsDesc() : TrafDesc(DESC_PARTNS_TYPE)
{}
// ---------------------------------------------------------------------
// Redefine virtual functions required for Versioning.
//----------------------------------------------------------------------
virtual unsigned char getClassVersionID()
{
return 1;
}
virtual void populateImageVersionIDArray()
{
setImageVersionID(0,getClassVersionID());
}
virtual short getClassSize() { return (short)sizeof(TrafPartnsDesc); }
virtual Long pack(void *space);
virtual Lng32 unpack(void * base, void * reallocator);
virtual TrafPartnsDesc *partnsDesc() const { return (TrafPartnsDesc*)this; }
char* tablename;
Int32 primarypartition;
char* partitionname;
char* logicalpartitionname;
char* firstkey;
Lng32 firstkeylen; //soln:10-031112-1256
Lng32 encodedkeylen;
char* encodedkey;
char* lowKey;
char* highKey;
Int32 indexlevel;
Int32 priExt;
Int32 secExt;
Int32 maxExt;
char* givenname;
};
class TrafRefConstrntsDesc : public TrafDesc {
public:
// why almost no initializers? see note at top of file
TrafRefConstrntsDesc() : TrafDesc(DESC_REF_CONSTRNTS_TYPE)
{}
// ---------------------------------------------------------------------
// Redefine virtual functions required for Versioning.
//----------------------------------------------------------------------
virtual unsigned char getClassVersionID()
{
return 1;
}
virtual void populateImageVersionIDArray()
{
setImageVersionID(0,getClassVersionID());
}
virtual short getClassSize() { return (short)sizeof(TrafRefConstrntsDesc); }
virtual Long pack(void *space);
virtual Lng32 unpack(void * base, void * reallocator);
virtual TrafRefConstrntsDesc *refConstrntsDesc() const { return (TrafRefConstrntsDesc*)this; }
Int64 refConstrntsDescFlags; // my flags
char* constrntname;
char* tablename;
char filler[16];
};
class TrafRoutineDesc : public TrafDesc {
public:
// why almost no initializers? see note at top of file
TrafRoutineDesc() : TrafDesc(DESC_ROUTINE_TYPE)
{}
// ---------------------------------------------------------------------
// Redefine virtual functions required for Versioning.
//----------------------------------------------------------------------
virtual unsigned char getClassVersionID()
{
return 1;
}
virtual void populateImageVersionIDArray()
{
setImageVersionID(0,getClassVersionID());
}
virtual short getClassSize() { return (short)sizeof(TrafRoutineDesc); }
virtual Long pack(void *space);
virtual Lng32 unpack(void * base, void * reallocator);
virtual TrafRoutineDesc *routineDesc() const { return (TrafRoutineDesc*)this; }
Int64 objectUID;
char* routineName;
char* externalName;
char* librarySqlName;
char* libraryFileName;
char* signature;
Int32 paramsCount;
DescStructPtr params;
ComRoutineLanguage language;
ComRoutineType UDRType;
ComRoutineSQLAccess sqlAccess;
ComRoutineTransactionAttributes transactionAttributes;
Int32 maxResults;
ComRoutineParamStyle paramStyle;
NABoolean isDeterministic;
NABoolean isCallOnNull;
NABoolean isIsolate;
ComRoutineExternalSecurity externalSecurity;
ComRoutineExecutionMode executionMode;
Int32 stateAreaSize;
ComRoutineParallelism parallelism;
Int32 owner;
Int32 schemaOwner;
DescStructPtr priv_desc;
Int64 routineDescFlags; // my flags
Int64 libRedefTime;
char *libBlobHandle;
char *libSchName;
Int32 libVersion;
Int64 libObjUID;
char filler[24];
};
class TrafSequenceGeneratorDesc : public TrafDesc {
public:
// why almost no initializers? see note at top of file
TrafSequenceGeneratorDesc() : TrafDesc(DESC_SEQUENCE_GENERATOR_TYPE)
{}
// ---------------------------------------------------------------------
// Redefine virtual functions required for Versioning.
//----------------------------------------------------------------------
virtual unsigned char getClassVersionID()
{
return 1;
}
virtual void populateImageVersionIDArray()
{
setImageVersionID(0,getClassVersionID());
}
virtual short getClassSize() { return (short)sizeof(TrafSequenceGeneratorDesc); }
virtual Long pack(void *space);
virtual Lng32 unpack(void * base, void * reallocator);
virtual TrafSequenceGeneratorDesc *sequenceGeneratorDesc() const { return (TrafSequenceGeneratorDesc*)this; }
ComSequenceGeneratorType sgType()
{ return (ComSequenceGeneratorType)sgType_; }
void setSgType(ComSequenceGeneratorType v)
{ sgType_ = (Int16)v; }
Int64 startValue;
Int64 increment;
Int16 /*ComSequenceGeneratorType*/ sgType_;
Int16 /*ComSQLDataType*/ sqlDataType;
Int16 /*ComFSDataType*/ fsDataType;
Int16 cycleOption;
Int64 maxValue;
Int64 minValue;
Int64 cache;
Int64 objectUID;
char* sgLocation;
Int64 nextValue;
Int64 redefTime;
Int64 sequenceGeneratorDescFlags; // my flags
char filler[16];
};
class TrafTableDesc : public TrafDesc {
public:
// why almost no initializers? see note at top of file
TrafTableDesc() : TrafDesc(DESC_TABLE_TYPE)
{}
// ---------------------------------------------------------------------
// Redefine virtual functions required for Versioning.
//----------------------------------------------------------------------
virtual unsigned char getClassVersionID()
{
return 1;
}
virtual void populateImageVersionIDArray()
{
setImageVersionID(0,getClassVersionID());
}
virtual short getClassSize() { return (short)sizeof(TrafTableDesc); }
virtual Long pack(void *space);
virtual Lng32 unpack(void * base, void * reallocator);
virtual TrafTableDesc *tableDesc() const { return (TrafTableDesc*)this; }
enum TableDescFlags
{
SYSTEM_TABLE_CODE = 0x0001,
UMD_TABLE = 0x0002,
MV_TABLE = 0x0004,
IUD_LOG = 0x0008,
MV_MD_OBJECT = 0x0010,
SYN_TRANS_DONE = 0x0020,
VOLATILE = 0x0040,
IN_MEM_OBJ = 0x0080,
DROPPABLE = 0x0100,
INSERT_ONLY = 0x0200
};
void setSystemTableCode(NABoolean v)
{(v ? tableDescFlags |= SYSTEM_TABLE_CODE : tableDescFlags &= ~SYSTEM_TABLE_CODE); };
NABoolean isSystemTableCode() { return (tableDescFlags & SYSTEM_TABLE_CODE) != 0; };
void setUMDTable(NABoolean v)
{(v ? tableDescFlags |= UMD_TABLE : tableDescFlags &= ~UMD_TABLE); };
NABoolean isUMDTable() { return (tableDescFlags & UMD_TABLE) != 0; };
void setMVTable(NABoolean v)
{(v ? tableDescFlags |= MV_TABLE : tableDescFlags &= ~MV_TABLE); };
NABoolean isMVTable() { return (tableDescFlags & MV_TABLE) != 0; };
void setIUDLog(NABoolean v)
{(v ? tableDescFlags |= IUD_LOG : tableDescFlags &= ~IUD_LOG); };
NABoolean isIUDLog() { return (tableDescFlags & IUD_LOG) != 0; };
void setMVMetadataObject(NABoolean v)
{(v ? tableDescFlags |= MV_MD_OBJECT : tableDescFlags &= ~MV_MD_OBJECT); };
NABoolean isMVMetadataObject() { return (tableDescFlags & MV_MD_OBJECT) != 0; };
void setSynonymTranslationDone(NABoolean v)
{(v ? tableDescFlags |= SYN_TRANS_DONE : tableDescFlags &= ~SYN_TRANS_DONE); };
NABoolean isSynonymTranslationDone() { return (tableDescFlags & SYN_TRANS_DONE) != 0; };
void setVolatileTable(NABoolean v)
{(v ? tableDescFlags |= VOLATILE : tableDescFlags &= ~VOLATILE); };
NABoolean isVolatileTable() { return (tableDescFlags & VOLATILE) != 0; };
void setInMemoryObject(NABoolean v)
{(v ? tableDescFlags |= IN_MEM_OBJ : tableDescFlags &= ~IN_MEM_OBJ); };
NABoolean isInMemoryObject() { return (tableDescFlags & IN_MEM_OBJ) != 0; };
void setDroppable(NABoolean v)
{(v ? tableDescFlags |= DROPPABLE : tableDescFlags &= ~DROPPABLE); };
NABoolean isDroppable() { return (tableDescFlags & DROPPABLE) != 0; };
void setInsertOnly(NABoolean v)
{(v ? tableDescFlags |= INSERT_ONLY : tableDescFlags &= ~INSERT_ONLY); };
NABoolean isInsertOnly() { return (tableDescFlags & INSERT_ONLY) != 0; };
ComInsertMode insertMode() { return (ComInsertMode)insertMode_;}
void setInsertMode(ComInsertMode v) {insertMode_ = (Int16)v;}
ComPartitioningScheme partitioningScheme()
{ return (ComPartitioningScheme)partitioningScheme_; }
void setPartitioningScheme(ComPartitioningScheme v)
{ partitioningScheme_ = (Int16)v; }
ComRowFormat rowFormat() { return (ComRowFormat)rowFormat_; }
void setRowFormat(ComRowFormat v) { rowFormat_ = (Int16)v; }
ComObjectType objectType() { return (ComObjectType)objectType_; }
void setObjectType(ComObjectType v) { objectType_ = (Int16)v; }
char* tablename;
Int64 createTime;
Int64 redefTime;
Int64 cacheTime;
Int32 mvAttributesBitmap;
Int32 record_length;
Int32 colcount;
Int32 constr_count;
Int16 /*ComInsertMode*/ insertMode_;
Int16 /*ComPartitioningScheme*/ partitioningScheme_;
Int16 /*ComRowFormat*/ rowFormat_;
Int16 /*ComObjectType*/ objectType_;
// next 8 bytes are fillers for future usage
Int16 /*ComStorageType*/ storageType_;
char filler0[6];
Int64 catUID;
Int64 schemaUID;
Int64 objectUID;
Lng32 owner;
Lng32 schemaOwner;
char * snapshotName;
char* default_col_fam;
char* all_col_fams;
Int64 objectFlags;
Int64 tablesFlags;
Int64 tableDescFlags; // my flags
DescStructPtr columns_desc;
DescStructPtr indexes_desc;
DescStructPtr constrnts_desc;
DescStructPtr views_desc;
DescStructPtr constrnts_tables_desc;
DescStructPtr referenced_tables_desc;
DescStructPtr referencing_tables_desc;
DescStructPtr histograms_desc;
DescStructPtr files_desc;
DescStructPtr priv_desc;
// for hbase's region keys
DescStructPtr hbase_regionkey_desc;
DescStructPtr sequence_generator_desc;
char filler[32];
};
class TrafUsingMvDesc : public TrafDesc {
public:
// why almost no initializers? see note at top of file
TrafUsingMvDesc() : TrafDesc(DESC_USING_MV_TYPE)
{}
// ---------------------------------------------------------------------
// Redefine virtual functions required for Versioning.
//----------------------------------------------------------------------
virtual unsigned char getClassVersionID()
{
return 1;
}
virtual void populateImageVersionIDArray()
{
setImageVersionID(0,getClassVersionID());
}
virtual short getClassSize() { return (short)sizeof(TrafUsingMvDesc); }
virtual Long pack(void *space);
virtual Lng32 unpack(void * base, void * reallocator);
virtual TrafUsingMvDesc *usingMvDesc() const { return (TrafUsingMvDesc*)this; }
ComMVRefreshType refreshType() { return (ComMVRefreshType)refreshType_;}
void setRefreshType(ComMVRefreshType v)
{ refreshType_ = (Int16)v;}
char* mvName;
Int32 rewriteEnabled;
Int32 isInitialized;
Int16 /*ComMVRefreshType*/ refreshType_; // unknown here means "non incremental"
char filler[14];
};
class TrafViewDesc : public TrafDesc {
public:
// why almost no initializers? see note at top of file
TrafViewDesc() : TrafDesc(DESC_VIEW_TYPE)
{}
// ---------------------------------------------------------------------
// Redefine virtual functions required for Versioning.
//----------------------------------------------------------------------
virtual unsigned char getClassVersionID()
{
return 1;
}
virtual void populateImageVersionIDArray()
{
setImageVersionID(0,getClassVersionID());
}
virtual short getClassSize() { return (short)sizeof(TrafViewDesc); }
virtual Long pack(void *space);
virtual Lng32 unpack(void * base, void * reallocator);
virtual TrafViewDesc *viewDesc() const { return (TrafViewDesc*)this; }
enum ViewDescFlags
{
UPDATABLE = 0x0001,
INSERTABLE = 0x0002
};
void setUpdatable(NABoolean v)
{(v ? viewDescFlags |= UPDATABLE : viewDescFlags &= ~UPDATABLE); };
NABoolean isUpdatable() { return (viewDescFlags & UPDATABLE) != 0; };
void setInsertable(NABoolean v)
{(v ? viewDescFlags |= INSERTABLE : viewDescFlags &= ~INSERTABLE); };
NABoolean isInsertable() { return (viewDescFlags & INSERTABLE) != 0; };
char* viewname;
char* viewfilename; // the physical file, to be Opened for auth-cking.
char* viewtext;
char* viewchecktext;
char* viewcolusages;
Int64 viewDescFlags; // my flags
Int16 /*CharInfo::CharSet*/ viewtextcharset;
char filler[22];
};
// --------------------------- privilege descriptors ---------------------------
// The privilege descriptors are organized as follows:
// privDesc - a TrafPrivDesc containing the privGrantees
// privGrantees - a TrafPrivGranteeDesc descriptor containing:
// grantee - int32 value for each user granted a privilege directly or
// through a role granted to the user
// objectBitmap - a TrafPrivBitmapDesc containing granted object privs
// summarized across all grantors
// columnBitmaps - list of TrafPrivBitmapDesc, one per colummn, containing
// granted column privs, summarized across all grantors
// priv_bits desc - a TrafPrivBitmapDesc descriptor containing:
// privBitmap - bitmap containing granted privs such as SELECT
// privWGO - bitmap containing WGO for associated grant (privBitmap)
// columnOrdinal - column number for bitmap, for objects, column
// number is not relavent so it is set to -1.
// column bits - list of TrafPrivBitmapDesc
class TrafPrivDesc : public TrafDesc {
public:
// why almost no initializers? see note at top of file
TrafPrivDesc() : TrafDesc(DESC_PRIV_TYPE)
{}
// ---------------------------------------------------------------------
// Redefine virtual functions required for Versioning.
//----------------------------------------------------------------------
virtual unsigned char getClassVersionID()
{
return 1;
}
virtual void populateImageVersionIDArray()
{
setImageVersionID(0,getClassVersionID());
}
virtual short getClassSize() { return (short)sizeof(TrafPrivDesc); }
virtual Long pack(void *space);
virtual Lng32 unpack(void * base, void * reallocator);
virtual TrafPrivDesc *privDesc() const { return (TrafPrivDesc*)this; }
DescStructPtr privGrantees;
char filler[16];
};
class TrafPrivGranteeDesc : public TrafDesc {
public:
// why almost no initializers? see note at top of file
TrafPrivGranteeDesc() : TrafDesc(DESC_PRIV_GRANTEE_TYPE)
{}
// ---------------------------------------------------------------------
// Redefine virtual functions required for Versioning.
//----------------------------------------------------------------------
virtual unsigned char getClassVersionID()
{
return 1;
}
virtual void populateImageVersionIDArray()
{
setImageVersionID(0,getClassVersionID());
}
virtual short getClassSize() { return (short)sizeof(TrafPrivGranteeDesc); }
virtual Long pack(void *space);
virtual Lng32 unpack(void * base, void * reallocator);
virtual TrafPrivGranteeDesc *privGranteeDesc() const { return (TrafPrivGranteeDesc*)this; }
Int32 grantee;
DescStructPtr objectBitmap;
DescStructPtr columnBitmaps;
char filler[20];
};
class TrafPrivBitmapDesc : public TrafDesc {
public:
// why almost no initializers? see note at top of file
TrafPrivBitmapDesc() : TrafDesc(DESC_PRIV_BITMAP_TYPE)
{}
// ---------------------------------------------------------------------
// Redefine virtual functions required for Versioning.
//----------------------------------------------------------------------
virtual unsigned char getClassVersionID()
{
return 1;
}
virtual void populateImageVersionIDArray()
{
setImageVersionID(0,getClassVersionID());
}
virtual short getClassSize() { return (short)sizeof(TrafPrivBitmapDesc); }
//virtual Long pack(void *space);
//virtual Lng32 unpack(void * base, void * reallocator);
virtual TrafPrivBitmapDesc *privBitmapDesc() const { return (TrafPrivBitmapDesc*)this; }
Int32 columnOrdinal;
Int64 privBitmap;
Int64 privWGOBitmap;
char filler[20];
};
// ------------------------- end privilege descriptors -------------------------
// If "space" is passed in, use it. (It might be an NAHeap or a ComSpace.)
// If "space" is null, use the statement heap.
TrafDesc *TrafAllocateDDLdesc(desc_nodetype nodetype,
NAMemory * space);
TrafDesc *TrafMakeColumnDesc
(
const char *tablename,
const char *colname,
Lng32 &colnumber, // INOUT
Int32 datatype,
Lng32 length,
Lng32 &offset, // INOUT
NABoolean null_flag,
SQLCHARSET_CODE datacharset, // i.e., use CharInfo::DefaultCharSet;
NAMemory * space
);
#endif
| 30.516031 | 111 | 0.651791 | [
"object"
] |
b8c65cca01b43ae9eb9a469db0443b429400a957 | 654 | h | C | FlashCards/SubjectsModel.h | raulchacon/iPhone-Flash-Card-App | 07fa80976afa82e827052b496f03ceffbe2b8ffc | [
"MIT"
] | 1 | 2016-02-18T09:41:11.000Z | 2016-02-18T09:41:11.000Z | FlashCards/SubjectsModel.h | rchacon/iPhone-Flash-Card-App | 07fa80976afa82e827052b496f03ceffbe2b8ffc | [
"MIT"
] | null | null | null | FlashCards/SubjectsModel.h | rchacon/iPhone-Flash-Card-App | 07fa80976afa82e827052b496f03ceffbe2b8ffc | [
"MIT"
] | 2 | 2015-07-22T04:51:04.000Z | 2015-10-13T14:38:49.000Z | //
// SubjectsModel.h
// FlashCards
//
// Created by Raul Chacon on 12/2/11.
// Copyright (c) 2011 Student. All rights reserved.
//
#import <Foundation/Foundation.h>
/*
* Subjects Model:
* each property corresponds to a column in the subjects database table.
*/
@interface SubjectsModel : NSObject
@property (nonatomic, assign) int iD;
@property (nonatomic, strong) NSString *title;
@property (nonatomic, assign) int isHidden;
@property (nonatomic, strong) NSString *insertDate;
// initialize a new subject model
- (id) initWithId: (int) aId title: (NSString *) aTitle isHidden: (int) isHiddenBit insertDate: (NSString *) aInsertDate;
@end
| 23.357143 | 121 | 0.721713 | [
"model"
] |
b8c76d494a23f3ee4ecddfee658f2c791044d658 | 2,909 | h | C | chunk.h | BranchofLight/Chunk | 5f9ef6acab5b9553af471c95fe315896f17803aa | [
"MIT"
] | null | null | null | chunk.h | BranchofLight/Chunk | 5f9ef6acab5b9553af471c95fe315896f17803aa | [
"MIT"
] | null | null | null | chunk.h | BranchofLight/Chunk | 5f9ef6acab5b9553af471c95fe315896f17803aa | [
"MIT"
] | null | null | null | // TO DO based on priority
// int find(Chunk&) - reference string->find
#pragma once
#include <vector>
#include <iostream>
#include <string>
#include <sstream>
class Chunk
{
public:
Chunk();
Chunk(const Chunk&);
Chunk(const char[]);
Chunk(const char);
Chunk(const std::string);
Chunk(const int);
Chunk(const float);
~Chunk();
Chunk subchunk(int, int) const;
int find(Chunk&) const;
void clear() { chunk.clear(); }
int length() const { return chunk.size(); }
bool isEmpty() const { return length() == 0; }
bool greaterThan(const Chunk&) const;
bool lesserThan(const Chunk&) const;
bool isInteger() const;
bool isFloat() const;
std::string toString() const;
int toInt() const;
float toFloat() const;
// --------------------------------------
// --------------------------------------
// --------- Operator Overloads ---------
// --------------------------------------
// --------------------------------------
char& operator[](int index);
char operator[](int index) const;
Chunk& operator=(Chunk rhs);
bool operator==(const Chunk&) const;
bool operator!=(const Chunk&) const;
inline bool operator< (const Chunk& rhs) const;
inline bool operator> (const Chunk& rhs) const;
inline bool operator<=(const Chunk& rhs) const {return !(*this > rhs);}
inline bool operator>=(const Chunk& rhs) const {return !(*this < rhs);}
friend std::ostream& operator<<(std::ostream& os, const Chunk& obj)
{
// Write each character to the stream
for (int i = 0; i < obj.length(); i++)
os << obj[i];
return os;
}
friend std::istream& operator>>(std::istream& is, Chunk& obj)
{
// Create container the stream can write to
char *input = new char[MAX_SIZE_STREAM];
// Write to it
is >> input;
// Use the copy constructor to give obj the data from input
obj = input;
// Free memory and return
delete[] input;
return is;
}
friend void getchunk(std::istream& is, Chunk& obj)
{
// Create container the stream can write to
char *input = new char[MAX_SIZE_STREAM];
// Gets the entire line
is.getline(input, MAX_SIZE_STREAM);
// Sets object
obj = input;
// Free memory
delete[] input;
}
Chunk& operator+=(const Chunk& rhs);
friend inline Chunk operator+(Chunk lhs, const Chunk& rhs)
{
// lhs is a copy so simply using += is safe
lhs += rhs;
return lhs;
}
// ------------------------------------
// ------------------------------------
// ------- End of Public Scope --------
// ------------------------------------
// ------------------------------------
private:
void add(char c) { return chunk.push_back(c); }
std::vector<char> chunk;
static const int MAX_SIZE_STREAM;
};
| 24.241667 | 75 | 0.528017 | [
"object",
"vector"
] |
b8e560f327dc7fbfbe5936381364eb0d366683d9 | 1,300 | h | C | src/devices/openxrheadset/OpenXrEigenConversions.h | ami-iit/yarp-device-openxrheadset | 761a290c2c7be65ef142f8a5540f09bcb8d5749c | [
"BSD-2-Clause"
] | 1 | 2022-02-17T08:39:22.000Z | 2022-02-17T08:39:22.000Z | src/devices/openxrheadset/OpenXrEigenConversions.h | ami-iit/yarp-device-openxrheadset | 761a290c2c7be65ef142f8a5540f09bcb8d5749c | [
"BSD-2-Clause"
] | 1 | 2022-02-16T17:23:02.000Z | 2022-02-16T17:23:02.000Z | src/devices/openxrheadset/OpenXrEigenConversions.h | ami-iit/yarp-device-openxrheadset | 761a290c2c7be65ef142f8a5540f09bcb8d5749c | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (C) 2021 Istituto Italiano di Tecnologia (IIT)
* All rights reserved.
*
* This software may be modified and distributed under the terms of the
* BSD-2-Clause license. See the accompanying LICENSE file for details.
*/
#ifndef YARP_DEV_OPENXREIGENCONVERSIONS_H
#define YARP_DEV_OPENXREIGENCONVERSIONS_H
#include <OpenXrConfig.h>
#include <Eigen/Core>
#include <Eigen/Geometry>
inline Eigen::Vector3f toEigen(const XrVector3f vector)
{
Eigen::Vector3f output;
output[0] = vector.x;
output[1] = vector.y;
output[2] = vector.z;
return output;
}
inline Eigen::Quaternionf toEigen(const XrQuaternionf quaternion)
{
Eigen::Quaternionf output;
output.w() = quaternion.w;
output.x() = quaternion.x;
output.y() = quaternion.y;
output.z() = quaternion.z;
return output;
}
inline XrVector3f toXr(const Eigen::Vector3f &position)
{
XrVector3f output;
output.x = position[0];
output.y = position[1];
output.z = position[2];
return output;
}
inline XrQuaternionf toXr(const Eigen::Quaternionf &quaternion)
{
XrQuaternionf output;
output.w = quaternion.w();
output.x = quaternion.x();
output.y = quaternion.y();
output.z = quaternion.z();
return output;
}
#endif // YARP_DEV_OPENXREIGENCONVERSIONS_H
| 23.214286 | 71 | 0.699231 | [
"geometry",
"vector"
] |
b8e7962c1e9b83c22b160ece61deb9d3bbd452c3 | 7,839 | c | C | ConfProfile/jni/strongswan/src/libpts/tcg/swid/tcg_swid_attr_req.c | Infoss/conf-profile-4-android | 619bd63095bb0f5a67616436d5510d24a233a339 | [
"MIT"
] | null | null | null | ConfProfile/jni/strongswan/src/libpts/tcg/swid/tcg_swid_attr_req.c | Infoss/conf-profile-4-android | 619bd63095bb0f5a67616436d5510d24a233a339 | [
"MIT"
] | 5 | 2016-01-25T18:04:42.000Z | 2016-02-25T08:54:56.000Z | ConfProfile/jni/strongswan/src/libpts/tcg/swid/tcg_swid_attr_req.c | Infoss/conf-profile-4-android | 619bd63095bb0f5a67616436d5510d24a233a339 | [
"MIT"
] | 2 | 2016-01-25T17:14:17.000Z | 2016-02-13T20:14:09.000Z | /*
* Copyright (C) 2013 Andreas Steffen
* HSR Hochschule fuer Technik Rapperswil
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
*
* 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.
*/
#include "tcg_swid_attr_req.h"
#include "swid/swid_tag_id.h"
#include <pa_tnc/pa_tnc_msg.h>
#include <bio/bio_writer.h>
#include <bio/bio_reader.h>
#include <utils/debug.h>
#include <collections/linked_list.h>
typedef struct private_tcg_swid_attr_req_t private_tcg_swid_attr_req_t;
/**
* SWID Request
* see section 4.7 of TCG TNC SWID Message and Attributes for IF-M
*
* 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |Reserved |C|S|R| Tag ID Count |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Request ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Earliest EID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Tag Creator Length | Tag Creator (variable length) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Unique Software ID Length |Unique Software ID (var length)|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
#define SWID_REQ_SIZE 12
#define SWID_REQ_RESERVED_MASK 0x03
/**
* Private data of an tcg_swid_attr_req_t object.
*/
struct private_tcg_swid_attr_req_t {
/**
* Public members of tcg_swid_attr_req_t
*/
tcg_swid_attr_req_t public;
/**
* Vendor-specific attribute type
*/
pen_type_t type;
/**
* Attribute value
*/
chunk_t value;
/**
* Noskip flag
*/
bool noskip_flag;
/**
* SWID request flags
*/
u_int8_t flags;
/**
* Request ID
*/
u_int32_t request_id;
/**
* Earliest EID
*/
u_int32_t earliest_eid;
/**
* List of Target Tag Identifiers
*/
swid_inventory_t *targets;
/**
* Reference count
*/
refcount_t ref;
};
METHOD(pa_tnc_attr_t, get_type, pen_type_t,
private_tcg_swid_attr_req_t *this)
{
return this->type;
}
METHOD(pa_tnc_attr_t, get_value, chunk_t,
private_tcg_swid_attr_req_t *this)
{
return this->value;
}
METHOD(pa_tnc_attr_t, get_noskip_flag, bool,
private_tcg_swid_attr_req_t *this)
{
return this->noskip_flag;
}
METHOD(pa_tnc_attr_t, set_noskip_flag,void,
private_tcg_swid_attr_req_t *this, bool noskip)
{
this->noskip_flag = noskip;
}
METHOD(pa_tnc_attr_t, build, void,
private_tcg_swid_attr_req_t *this)
{
bio_writer_t *writer;
chunk_t tag_creator, unique_sw_id;
swid_tag_id_t *tag_id;
enumerator_t *enumerator;
if (this->value.ptr)
{
return;
}
writer = bio_writer_create(SWID_REQ_SIZE);
writer->write_uint8 (writer, this->flags);
writer->write_uint24(writer, this->targets->get_count(this->targets));
writer->write_uint32(writer, this->request_id);
writer->write_uint32(writer, this->earliest_eid);
enumerator = this->targets->create_enumerator(this->targets);
while (enumerator->enumerate(enumerator, &tag_id))
{
tag_creator = tag_id->get_tag_creator(tag_id);
unique_sw_id = tag_id->get_unique_sw_id(tag_id, NULL);
writer->write_data16(writer, tag_creator);
writer->write_data16(writer, unique_sw_id);
}
enumerator->destroy(enumerator);
this->value = writer->extract_buf(writer);
writer->destroy(writer);
}
METHOD(pa_tnc_attr_t, process, status_t,
private_tcg_swid_attr_req_t *this, u_int32_t *offset)
{
bio_reader_t *reader;
u_int32_t tag_id_count;
chunk_t tag_creator, unique_sw_id;
swid_tag_id_t *tag_id;
if (this->value.len < SWID_REQ_SIZE)
{
DBG1(DBG_TNC, "insufficient data for SWID Request");
*offset = 0;
return FAILED;
}
reader = bio_reader_create(this->value);
reader->read_uint8 (reader, &this->flags);
reader->read_uint24(reader, &tag_id_count);
reader->read_uint32(reader, &this->request_id);
reader->read_uint32(reader, &this->earliest_eid);
if (this->request_id == 0)
{
*offset = 4;
return FAILED;
}
*offset = SWID_REQ_SIZE;
this->flags &= SWID_REQ_RESERVED_MASK;
while (tag_id_count--)
{
if (!reader->read_data16(reader, &tag_creator))
{
DBG1(DBG_TNC, "insufficient data for Tag Creator field");
return FAILED;
}
*offset += 2 + tag_creator.len;
if (!reader->read_data16(reader, &unique_sw_id))
{
DBG1(DBG_TNC, "insufficient data for Unique Software ID");
return FAILED;
}
*offset += 2 + unique_sw_id.len;
tag_id = swid_tag_id_create(tag_creator, unique_sw_id, chunk_empty);
this->targets->add(this->targets, tag_id);
}
reader->destroy(reader);
return SUCCESS;
}
METHOD(pa_tnc_attr_t, get_ref, pa_tnc_attr_t*,
private_tcg_swid_attr_req_t *this)
{
ref_get(&this->ref);
return &this->public.pa_tnc_attribute;
}
METHOD(pa_tnc_attr_t, destroy, void,
private_tcg_swid_attr_req_t *this)
{
if (ref_put(&this->ref))
{
this->targets->destroy(this->targets);
free(this->value.ptr);
free(this);
}
}
METHOD(tcg_swid_attr_req_t, get_flags, u_int8_t,
private_tcg_swid_attr_req_t *this)
{
return this->flags;
}
METHOD(tcg_swid_attr_req_t, get_request_id, u_int32_t,
private_tcg_swid_attr_req_t *this)
{
return this->request_id;
}
METHOD(tcg_swid_attr_req_t, get_earliest_eid, u_int32_t,
private_tcg_swid_attr_req_t *this)
{
return this->earliest_eid;
}
METHOD(tcg_swid_attr_req_t, add_target, void,
private_tcg_swid_attr_req_t *this, swid_tag_id_t *tag_id)
{
this->targets->add(this->targets, tag_id);
}
METHOD(tcg_swid_attr_req_t, get_targets, swid_inventory_t*,
private_tcg_swid_attr_req_t *this)
{
return this->targets;
}
/**
* Described in header.
*/
pa_tnc_attr_t *tcg_swid_attr_req_create(u_int8_t flags, u_int32_t request_id,
u_int32_t eid)
{
private_tcg_swid_attr_req_t *this;
INIT(this,
.public = {
.pa_tnc_attribute = {
.get_type = _get_type,
.get_value = _get_value,
.get_noskip_flag = _get_noskip_flag,
.set_noskip_flag = _set_noskip_flag,
.build = _build,
.process = _process,
.get_ref = _get_ref,
.destroy = _destroy,
},
.get_flags = _get_flags,
.get_request_id = _get_request_id,
.get_earliest_eid = _get_earliest_eid,
.add_target = _add_target,
.get_targets = _get_targets,
},
.type = { PEN_TCG, TCG_SWID_REQUEST },
.flags = flags & SWID_REQ_RESERVED_MASK,
.request_id = request_id,
.earliest_eid = eid,
.targets = swid_inventory_create(FALSE),
.ref = 1,
);
return &this->public.pa_tnc_attribute;
}
/**
* Described in header.
*/
pa_tnc_attr_t *tcg_swid_attr_req_create_from_data(chunk_t data)
{
private_tcg_swid_attr_req_t *this;
INIT(this,
.public = {
.pa_tnc_attribute = {
.get_type = _get_type,
.get_value = _get_value,
.get_noskip_flag = _get_noskip_flag,
.set_noskip_flag = _set_noskip_flag,
.build = _build,
.process = _process,
.get_ref = _get_ref,
.destroy = _destroy,
},
.get_flags = _get_flags,
.get_request_id = _get_request_id,
.get_earliest_eid = _get_earliest_eid,
.add_target = _add_target,
.get_targets = _get_targets,
},
.type = { PEN_TCG, TCG_SWID_REQUEST },
.value = chunk_clone(data),
.targets = swid_inventory_create(FALSE),
.ref = 1,
);
return &this->public.pa_tnc_attribute;
}
| 23.754545 | 77 | 0.661309 | [
"object"
] |
b8e85aaced6f3476cb96339ad061b55122192572 | 1,412 | h | C | iphone/Maps/Classes/CustomAlert/BaseAlert/MWMAlert.h | yanncoupin/omim | 13d4deb38bc23ec20d6dd33e51ce42d2153593ee | [
"Apache-2.0"
] | null | null | null | iphone/Maps/Classes/CustomAlert/BaseAlert/MWMAlert.h | yanncoupin/omim | 13d4deb38bc23ec20d6dd33e51ce42d2153593ee | [
"Apache-2.0"
] | null | null | null | iphone/Maps/Classes/CustomAlert/BaseAlert/MWMAlert.h | yanncoupin/omim | 13d4deb38bc23ec20d6dd33e51ce42d2153593ee | [
"Apache-2.0"
] | null | null | null | #import <UIKit/UIKit.h>
#include "routing/router.hpp"
#include "storage/storage.hpp"
typedef void (^RightButtonAction)();
@class MWMAlertViewController;
@interface MWMAlert : UIView
@property (weak, nonatomic) MWMAlertViewController * alertController;
+ (MWMAlert *)alert:(routing::IRouter::ResultCode)type;
+ (MWMAlert *)downloaderAlertWithAbsentCountries:(vector<storage::TIndex> const &)countries
routes:(vector<storage::TIndex> const &)routes
code:(routing::IRouter::ResultCode)code;
+ (MWMAlert *)rateAlert;
+ (MWMAlert *)facebookAlert;
+ (MWMAlert *)locationAlert;
+ (MWMAlert *)routingDisclaimerAlertWithInitialOrientation:(UIInterfaceOrientation)orientation;
+ (MWMAlert *)disabledLocationAlert;
+ (MWMAlert *)noWiFiAlertWithName:(NSString *)name downloadBlock:(RightButtonAction)block;
+ (MWMAlert *)noConnectionAlert;
+ (MWMAlert *)locationServiceNotSupportedAlert;
+ (MWMAlert *)pedestrianToastShareAlert:(BOOL)isFirstLaunch;
+ (MWMAlert *)point2PointAlertWithOkBlock:(RightButtonAction)block needToRebuild:(BOOL)needToRebuild;
- (void)close;
- (void)setNeedsCloseAlertAfterEnterBackground;
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)orientation;
- (void)rotate:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration;
- (void)addControllerViewToWindow;
@end
| 38.162162 | 101 | 0.757082 | [
"vector"
] |
b8ea024f7934e7749e30401d2c7f3587b8b19144 | 2,410 | h | C | src/plugins/alarm_robotic_vehicle/include/plugins/alarm_robotic_vehicle/alarm_robotic_vehicle.h | fada-catec/piloting-mavsdk | 512316f0137b737323550b2b06ae014b6e9b2ae4 | [
"BSD-3-Clause"
] | 4 | 2021-04-12T09:21:10.000Z | 2022-01-11T18:20:32.000Z | src/plugins/alarm_robotic_vehicle/include/plugins/alarm_robotic_vehicle/alarm_robotic_vehicle.h | fada-catec/piloting-mavsdk | 512316f0137b737323550b2b06ae014b6e9b2ae4 | [
"BSD-3-Clause"
] | 1 | 2021-11-02T09:30:23.000Z | 2022-01-11T06:42:10.000Z | src/plugins/alarm_robotic_vehicle/include/plugins/alarm_robotic_vehicle/alarm_robotic_vehicle.h | fada-catec/piloting-mavsdk | 512316f0137b737323550b2b06ae014b6e9b2ae4 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <memory>
#include "plugin_base.h"
#include "alarm_base.h"
namespace mavsdk {
class System;
class AlarmRoboticVehicleImpl;
/**
* @brief Enable alarms.
*/
class AlarmRoboticVehicle : public PluginBase {
public:
/**
* @brief Constructor. Creates the plugin for a specific System.
*
* The plugin is typically created as shown below:
*
* ```cpp
* auto alarm = AlarmRoboticVehicle(system);
* ```
*
* @param system The specific system associated with this plugin.
*/
explicit AlarmRoboticVehicle(System& system); // deprecated
/**
* @brief Constructor. Creates the plugin for a specific System.
*
* The plugin is typically created as shown below:
*
* ```cpp
* auto alarm = AlarmRoboticVehicle(system);
* ```
*
* @param system The specific system associated with this plugin.
*/
explicit AlarmRoboticVehicle(std::shared_ptr<System> system); // new
/**
* @brief Destructor (internal use only).
*/
~AlarmRoboticVehicle();
/**
* @brief Sets the alarm list to be uploaded if requested by gRCS
*
* This function is non-blocking.
*/
void set_upload_alarm(AlarmBase::AlarmList alarms_list) const;
/**
* @brief Upload a list of alarm items to the system.
*
* Every time the robotic vehicle alarm list changes,
* it must be updated through the method 'set_upload_alarm'
*
* This function is non-blocking.
*/
void upload_alarm_async(
const AlarmBase::ResultAckCallback callback,
AlarmBase::AlarmList alarm_list = {});
/**
* @brief Cancel an ongoing alarm upload.
*
* This function is blocking.
*
* @return Result of request.
*/
AlarmBase::Result cancel_alarm_upload() const;
/**
* @brief Send 'AlarmStatus' updates.
*/
void send_alarm_status(const AlarmBase::AlarmStatus&);
/**
* @brief Copy constructor.
*/
AlarmRoboticVehicle(const AlarmRoboticVehicle& other);
/**
* @brief Equality operator (object is not copyable).
*/
const AlarmRoboticVehicle& operator=(const AlarmRoboticVehicle&) = delete;
private:
/** @private Underlying implementation, set at instantiation */
std::unique_ptr<AlarmRoboticVehicleImpl> _impl;
};
} // namespace mavsdk
| 24.591837 | 78 | 0.63278 | [
"object"
] |
b8ebf689d9a3495793e749d12c44959a67e3cbb0 | 5,848 | c | C | d/barriermnts/bpeak/obj/bpan.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-07-19T05:24:44.000Z | 2021-11-18T04:08:19.000Z | d/barriermnts/bpeak/obj/bpan.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 4 | 2021-03-15T18:56:39.000Z | 2021-08-17T17:08:22.000Z | d/barriermnts/bpeak/obj/bpan.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-09-12T06:22:38.000Z | 2022-01-31T01:15:12.000Z | // goldpan.c
#include <std.h>
inherit OBJECT;
int count;
void create(){
::create();
set_id(({"pan","gold pan"}));
set_name("pan");
set_short("a pan");
set_long("This is a small circular aluminum pan. It is somewhat cone shaped and the inside edge of one side has a set of ridges built into it that look like they are designed to catch something. Tiny %^YELLOW%^golden flecks %^RESET%^catch your eye from the inside of the pan. On the bottom of the pan is a small inscription.");
set_read("%^BOLD%^BLUE%^%^To the fair townsfolk of Levinshire, I gift you each"
" with this to help you live long your simple yet prosperous lifestyle. May the"
" bounties brought forth by this gift add to the beauty of your fine city.%^RESET%^");
set_language("common");
set_weight(1);
set_size(2);
}
void init(){
::init();
add_action("panning","pan");
}
int panning(string str){
if(!str) return notify_fail("Pan what?\n");
if(member_array(str,({"water","stream","river","for gold"})) == -1) return
notify_fail("You cannot pan that!\n");
if(!ETP->is_goldriver()) return notify_fail("This doesn't look like a good place to pan.\n");
if(TP->query_property("is_panning")) return notify_fail("You are already
panning!\n");
if(!TO->query_wielded()) return notify_fail("You must be wielding the pan to use it.\n");
else{
tell_object(TP,"%^RESET%^You sit down near the edge of the %^CYAN%^rive"
"r %^RESET%^and fill the pan with %^ORANGE%^dirt %^RESET%^and %^BOLD%^%^BLACK%^rock."
" %^RESET%^You begin %^BOLD%^%^CYAN%^swirling %^RESET%^the %^BOLD%^%^CYAN%^water"
" %^RESET%^in the pan around, washing away all the lighter %^BOLD%^%^BLACK%^debris."
"%^RESET%^");
tell_room(ETP,"%^RESET%^%^CYAN%^"+TP->query_cap_name()+" kneels down by the rivers edge and begins to pan for gold.%^RESET%^",TP);
}
TP->set_property("is_panning",1);
TP->set_paralyzed(5,"You are still panning for gold.");
call_out("while_panning",5,TP);
TP->use_stamina(10);
count = 1;
return 1;
}
void while_panning(string str2){
count++;
if(!TO->query_wielded()) {
tell_object(TP,"You cannot continue panning without the pan.");
TP->remove_property("is_panning");
return;
}
if(!ETP->is_goldriver()) {
tell_object(TP,"You cannot pan here.");
TP->remove_property("is_panning");
return;
}
if(TP->query_unconscious()) {
tell_object(TP,"You are lucky you didn't drown.");
TP->remove_property("is_panning");
return;
}
TP->set_paralyzed(5,"You are busy panning.");
switch(random(50)){
case 0..48:
switch (count) {
case 1..2:
tell_object(TP,"%^BOLD%^%^CYAN%^Water splashes around you from the moving stream.%^RESET%^");
TP->use_stamina(5);
call_out("while_panning",5,TP);
break;
case 3:
tell_object(TP,"The pan is slowly getting empty, but you still see no gold.");
tell_room(ETP,"The pan "+TPQCN+" is holding is getting empty but there still doesn't seem to be any gold.",TP);
TP->use_stamina(5);
call_out("while_panning",5,TP);
break;
case 4:
tell_object(TP,"%^RESET%^%^CYAN%^You're getting wet from all the water.%^RESET%^");
tell_room(ETP,"%^RESET%^%^CYAN%^"+TPQCN+" is getting soaked from the moving waters of the stream.%^RESET%^",TP);
TP->use_stamina(5);
call_out("while_panning",5,TP);
break;
case 5:
tell_object(TP,"Your arms are getting sore and you realize you're going to need some rest after this.");
tell_room(ETP,""+TPQCN+" is beginning to look tired from constantly swirling the water around.",TP);
TP->use_stamina(5);
call_out("end_panning",5,TP);
break;
}
break;
case 49:
tell_object(TP,"Darn! You got overzealous in your panning efforts and have accidentally splashed everything out!");
tell_room(ETP,""+TPQCN+" starts to swirl the water faster and faster until... Oops! There is nothing left in the pan!",TP);
TP->use_stamina(15);
call_out("stop_panning",5,TP);
break;
}
}
int end_panning(object who){
int total, found, i;
object ob, where;
if(!objectp(who)) return 1;
where = environment(who);
if(!objectp(where)) return 1;
tell_object(who,"You see that the pan is nearly empty and you stop to inspect it.");
tell_room(where,who->query_cap_name()+" stops swirling the water and peers into the pan.",who);
who->remove_property("is_panning");
total = where->query_to_find();
if(!random(2)){
found = random(total)+1;
where->set_found(found);
for(i=0;i<found;i++) {
ob = where->get_found_ob();
ob->move(where);
}
tell_room(where,"%^BOLD%^%^MAGENTA%^You see something solid inside the pan and watch as "+TPQCN+" dumps the contents of the pan onto the ground beside the river.%^RESET%^",TP);
tell_object(who,"%^BOLD%^%^MAGENTA%^Woo-Hoo! A chunk of something! Very carefully you dump the contents of the pan onto the ground beside the river.%^RESET%^");
}
else{
tell_object(who,"%^RESET%^%^ORANGE%^After all your work, there is nothing but flecks of dirt left!%^RESET%^");
}
count = 1;
return 1;
}
int stop_panning(object who){
object ob, where;
if(!objectp(who)) return 1;
where = environment(who);
if(!objectp(where)) return 1;
tell_object(who,"%^RESET%^%^ORANGE%^Well, the pan is completely empty now. Maybe you should calm down and try again%^RESET%^.");
tell_room(where,"%^RESET%^%^ORANGE%^"+who->query_cap_name()+" sighs slightly%^RESET%^.",who);
who->remove_property("is_panning");
}
| 41.771429 | 333 | 0.626368 | [
"object",
"solid"
] |
b8ec458e3c6af39f4aab958d431485a2bad6818d | 21,274 | c | C | src/Utils/HydrogenBond.c | xomachine/gabedit | 1f63b6675b8bffdda910012fec00b89630bcb4a2 | [
"MIT"
] | null | null | null | src/Utils/HydrogenBond.c | xomachine/gabedit | 1f63b6675b8bffdda910012fec00b89630bcb4a2 | [
"MIT"
] | null | null | null | src/Utils/HydrogenBond.c | xomachine/gabedit | 1f63b6675b8bffdda910012fec00b89630bcb4a2 | [
"MIT"
] | null | null | null | /*HydrogenBond.c*/
/**********************************************************************************************************
Copyright (c) 2002-2013 Abdul-Rahman Allouche. All rights reserved
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the Gabedit), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
************************************************************************************************************/
#include "../../Config.h"
#include <stdlib.h>
#include <math.h>
#include "../Common/Global.h"
#include "../Utils/UtilsInterface.h"
#include "../Utils/Utils.h"
#include "../Utils/AtomsProp.h"
#include "../Geometry/GeomGlobal.h"
#include "../Geometry/Fragments.h"
#include "../Geometry/DrawGeom.h"
#include "../Common/Windows.h"
#include "../Display/GLArea.h"
#include "../Common/StockIcons.h"
static gint nAtomsCanConnect = 6;
static gchar** atomsCanConnect = NULL;
static gdouble minDistance = 1.50; /* in Agnstrom */
static gdouble maxDistance = 3.15; /* in Agnstrom */
static gdouble minAngle = 145.0;
static gdouble maxAngle = 215.0;
static gint rowSelected = -1;
static GtkTreeView *treeViewOfAtoms = NULL;
static void rafreshTreeView(GtkTreeView *treeView);
/************************************************************************/
void initHBonds()
{
nAtomsCanConnect = 6;
atomsCanConnect = g_malloc(nAtomsCanConnect*sizeof(gchar*));
atomsCanConnect[0] = g_strdup("N");
atomsCanConnect[1] = g_strdup("O");
atomsCanConnect[2] = g_strdup("F");
atomsCanConnect[3] = g_strdup("Cl");
atomsCanConnect[4] = g_strdup("Br");
atomsCanConnect[5] = g_strdup("I");
minDistance = 1.50; /* in Agnstrom */
maxDistance = 3.15; /* in Agnstrom */
minAngle = 145.0;
maxAngle = 215.0;
}
/******************************************************************/
void save_HBonds_properties()
{
gchar *hbondsfile;
FILE *file;
gint i;
hbondsfile = g_strdup_printf("%s%shbonds",gabedit_directory(),G_DIR_SEPARATOR_S);
file = FOpen(hbondsfile, "w");
if(!file) return;
fprintf(file,"%f\n",minDistance);
fprintf(file,"%f\n",maxDistance);
fprintf(file,"%f\n",minAngle);
fprintf(file,"%f\n",maxAngle);
fprintf(file,"%d\n",nAtomsCanConnect);
for(i=0;i<nAtomsCanConnect;i++) fprintf(file,"%s\n",atomsCanConnect[i]);
fclose(file);
g_free(hbondsfile);
}
/******************************************************************/
void read_HBonds_properties()
{
gchar *hbondsfile;
FILE *file;
gint n;
gint i;
initHBonds();
hbondsfile = g_strdup_printf("%s%shbonds",gabedit_directory(),G_DIR_SEPARATOR_S);
file = FOpen(hbondsfile, "rb");
if(!file) return;
n = fscanf(file,"%lf\n",&minDistance);
if(n != 1) { initHBonds(); return ; fclose(file); g_free(hbondsfile);}
n = fscanf(file,"%lf\n",&maxDistance);
if(n != 1) { initHBonds(); return ; fclose(file); g_free(hbondsfile);}
n = fscanf(file,"%lf\n",&minAngle);
if(n != 1) { initHBonds(); return ; fclose(file); g_free(hbondsfile);}
n = fscanf(file,"%lf\n",&maxAngle);
if(n != 1) { initHBonds(); return ; fclose(file); g_free(hbondsfile);}
n = fscanf(file,"%d\n",&nAtomsCanConnect);
if(n != 1 || nAtomsCanConnect<0 ) { initHBonds(); return ; fclose(file); g_free(hbondsfile);}
for(i=0;i<nAtomsCanConnect;i++)
{
n = fscanf(file,"%s\n",atomsCanConnect[i]);
if(n != 1) { initHBonds(); return ; fclose(file); g_free(hbondsfile);}
delete_last_spaces(atomsCanConnect[i]);
delete_first_spaces(atomsCanConnect[i]);
str_delete_n(atomsCanConnect[i]);
}
fclose(file);
g_free(hbondsfile);
}
/******************************************************************/
static void set_HBonds(GtkWidget* fp,gpointer data)
{
GtkWidget** entrys = (GtkWidget**)data;
G_CONST_RETURN gchar* tentry;
gchar* t;
tentry = gtk_entry_get_text(GTK_ENTRY(entrys[0]));
minDistance = atof(tentry);
if(minDistance<1e-6)minDistance = 1.5;
tentry = gtk_entry_get_text(GTK_ENTRY(entrys[1]));
maxDistance = atof(tentry);
if(maxDistance<1e-6)maxDistance = 3.5;
if(maxDistance<=minDistance) maxDistance = minDistance + 1.0;
tentry = gtk_entry_get_text(GTK_ENTRY(entrys[2]));
minAngle = atof(tentry);
if(minAngle<1e-6)minAngle = 145.0;
tentry = gtk_entry_get_text(GTK_ENTRY(entrys[3]));
maxAngle = atof(tentry);
if(maxAngle<1e-6)maxAngle = 215.0;
if(maxAngle<=minAngle) maxAngle = minAngle + 70.0;
t = g_strdup_printf("%f",minDistance);
gtk_entry_set_text(GTK_ENTRY(entrys[0]),t);
g_free(t);
t = g_strdup_printf("%f",maxDistance);
gtk_entry_set_text(GTK_ENTRY(entrys[1]),t);
g_free(t);
t = g_strdup_printf("%f",minAngle);
gtk_entry_set_text(GTK_ENTRY(entrys[2]),t);
g_free(t);
t = g_strdup_printf("%f",maxAngle);
gtk_entry_set_text(GTK_ENTRY(entrys[3]),t);
g_free(t);
rafresh_window_orb();
if(GeomDrawingArea != NULL) draw_geometry(NULL,NULL);
}
/******************************************************************/
static void deleteAnAtomDlg()
{
gint j;
gint k = rowSelected;
if(k<0 || k >= nAtomsCanConnect) return;
if(!atomsCanConnect) return;
if(nAtomsCanConnect == 1)
{
GtkWidget* win;
win = Message(_("Sorry, You can not delete all atoms"),_("Warning"),TRUE);
gtk_window_set_modal(GTK_WINDOW(win),TRUE);
return;
}
for(j=k;j<nAtomsCanConnect-1;j++)
{
if(atomsCanConnect[j])
{
g_free(atomsCanConnect[j]);
atomsCanConnect[j] = g_strdup(atomsCanConnect[j+1]);
}
else break;
}
nAtomsCanConnect--;
atomsCanConnect = g_realloc(atomsCanConnect, nAtomsCanConnect*sizeof(gchar*));
rafreshTreeView(treeViewOfAtoms);
return;
}
/********************************************************************************/
static void addAtom(GtkWidget *button,gpointer data)
{
GtkWidget* winTable = g_object_get_data(G_OBJECT(button),"WinTable");
gchar* atomToInsert = (gchar*)data;
gint i;
gtk_widget_destroy(winTable);
for(i=0;i<nAtomsCanConnect;i++) if(strcmp(atomToInsert,atomsCanConnect[i])==0) return;
if(nAtomsCanConnect==0) atomsCanConnect = g_malloc(sizeof(gchar*));
else atomsCanConnect = g_realloc(atomsCanConnect,(nAtomsCanConnect+1)*sizeof(gchar*));
atomsCanConnect[nAtomsCanConnect] = g_strdup(atomToInsert);
nAtomsCanConnect++;
rafreshTreeView(treeViewOfAtoms);
}
/********************************************************************************/
static void addAnAtomDlg()
{
GtkWidget* table;
GtkWidget* button;
GtkWidget* frame;
GtkWidget* winTable;
guint i;
guint j;
GtkStyle *button_style;
GtkStyle *style;
gchar*** Symb = get_periodic_table();
winTable = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_modal(GTK_WINDOW(winTable),TRUE);
gtk_window_set_title(GTK_WINDOW(winTable),_("Select your atom"));
gtk_window_set_default_size (GTK_WINDOW(winTable),(gint)(ScreenWidth*0.5),(gint)(ScreenHeight*0.4));
frame = gtk_frame_new (NULL);
gtk_frame_set_shadow_type( GTK_FRAME(frame),GTK_SHADOW_ETCHED_OUT);
gtk_container_set_border_width (GTK_CONTAINER (frame), 10);
gtk_container_add(GTK_CONTAINER(winTable),frame);
gtk_widget_show (frame);
table = gtk_table_new(PERIODIC_TABLE_N_ROWS-1,PERIODIC_TABLE_N_COLUMNS,TRUE);
gtk_container_add(GTK_CONTAINER(frame),table);
button_style = gtk_widget_get_style(winTable);
for ( i = 0;i<PERIODIC_TABLE_N_ROWS-1;i++)
for ( j = 0;j<PERIODIC_TABLE_N_COLUMNS;j++)
{
if(strcmp(Symb[j][i],"00"))
{
button = gtk_button_new_with_label(Symb[j][i]);
style=set_button_style(button_style,button,Symb[j][i]);
g_signal_connect(G_OBJECT(button), "clicked",
(GCallback)addAtom,(gpointer )Symb[j][i]);
g_object_set_data(G_OBJECT(button),"WinTable",winTable);
gtk_table_attach(GTK_TABLE(table),button,j,j+1,i,i+1,
(GtkAttachOptions)(GTK_FILL | GTK_EXPAND) ,
(GtkAttachOptions)(GTK_FILL | GTK_EXPAND),
1,1);
}
}
gtk_widget_show_all(winTable);
}
/******************************************************************/
static void setDefaultAtomsDlg()
{
if(atomsCanConnect)
{
gint i;
for(i=0;i<nAtomsCanConnect;i++)
if(atomsCanConnect[i]) g_free(atomsCanConnect[i]);
g_free(atomsCanConnect);
}
nAtomsCanConnect = 6;
atomsCanConnect = g_malloc(nAtomsCanConnect*sizeof(gchar*));
atomsCanConnect[0] = g_strdup("N");
atomsCanConnect[1] = g_strdup("O");
atomsCanConnect[2] = g_strdup("F");
atomsCanConnect[3] = g_strdup("Cl");
atomsCanConnect[4] = g_strdup("Br");
atomsCanConnect[5] = g_strdup("I");
rafreshTreeView(treeViewOfAtoms);
}
/********************************************************************************/
static void set_sensitive_option(GtkUIManager *manager, gchar* path)
{
GtkWidget *wid = gtk_ui_manager_get_widget (manager, path);
gboolean sensitive = TRUE;
if(nAtomsCanConnect<2) sensitive = FALSE;
if(GTK_IS_WIDGET(wid)) gtk_widget_set_sensitive(wid, sensitive);
}
/**********************************************************************************/
static gboolean show_menu_popup(GtkUIManager *manager, guint button, guint32 time)
{
GtkWidget *menu = gtk_ui_manager_get_widget (manager, "/MenuHBonds");
if (GTK_IS_MENU (menu))
{
set_sensitive_option(manager,"/MenuHBonds/DeleteAtom");
gtk_menu_popup (GTK_MENU (menu), NULL, NULL, NULL, NULL, button, time);
return TRUE;
}
return FALSE;
}
/*********************************************************************************************************************/
static void activate_action (GtkAction *action)
{
const gchar *name = gtk_action_get_name (action);
if(!strcmp(name, "DeleteAtom")) deleteAnAtomDlg();
else if(!strcmp(name, "AddAtom")) addAnAtomDlg();
else if(!strcmp(name, "DefaultAtoms")) setDefaultAtomsDlg();
}
/*--------------------------------------------------------------------*/
static GtkActionEntry gtkActionEntries[] =
{
{"DeleteAtom", GABEDIT_STOCK_CUT, N_("_Delete selected atom"), NULL, "Delete selected atom", G_CALLBACK (activate_action) },
{"AddAtom", GABEDIT_STOCK_NEW, N_("_Add an atom"), NULL, "Add an atom", G_CALLBACK (activate_action) },
{"DefaultAtoms", NULL, N_("_Default atoms"), NULL, "Default atoms", G_CALLBACK (activate_action) },
};
static guint numberOfGtkActionEntries = G_N_ELEMENTS (gtkActionEntries);
/********************************************************************************/
/* XML description of the menus for the test app. The parser understands
* a subset of the Bonobo UI XML format, and uses GMarkup for parsing */
static const gchar *uiMenuInfo =
" <popup name=\"MenuHBonds\">\n"
" <separator name=\"sepMenuPopDelete\" />\n"
" <menuitem name=\"DeleteAtom\" action=\"DeleteAtom\" />\n"
" <separator name=\"sepMenuPopAdd\" />\n"
" <menuitem name=\"AddAtom\" action=\"AddAtom\" />\n"
" <separator name=\"sepMenuPopDefault\" />\n"
" <menuitem name=\"DefaultAtoms\" action=\"DefaultAtoms\" />\n"
" </popup>\n"
;
/*******************************************************************************************************************************/
static GtkUIManager *create_menu(GtkWidget* win)
{
GtkActionGroup *actionGroup = NULL;
GtkUIManager *manager = NULL;
GError *error = NULL;
manager = gtk_ui_manager_new ();
g_signal_connect_swapped (win, "destroy", G_CALLBACK (g_object_unref), manager);
actionGroup = gtk_action_group_new ("GabeditHBonds");
gtk_action_group_set_translation_domain(actionGroup,GETTEXT_PACKAGE);
gtk_action_group_add_actions (actionGroup, gtkActionEntries, numberOfGtkActionEntries, NULL);
gtk_ui_manager_insert_action_group (manager, actionGroup, 0);
gtk_window_add_accel_group (GTK_WINDOW (win), gtk_ui_manager_get_accel_group (manager));
if (!gtk_ui_manager_add_ui_from_string (manager, uiMenuInfo, -1, &error))
{
g_message ("building menus failed: %s", error->message);
g_error_free (error);
}
return manager;
}
/*******************************************************************************************************************************/
static void rafreshTreeView(GtkTreeView *treeView)
{
gint i;
GtkTreeIter iter;
GtkTreeModel *model = gtk_tree_view_get_model(treeView);
GtkTreeStore *store = GTK_TREE_STORE (model);
gtk_tree_store_clear(store);
model = GTK_TREE_MODEL (store);
for(i=0;i<nAtomsCanConnect;i++)
{
gchar* string = g_strdup_printf("%s",atomsCanConnect[i]);
gtk_tree_store_append (store, &iter, NULL);
gtk_tree_store_set (store, &iter, 0, string, -1);
g_free(string);
}
if(nAtomsCanConnect>0)
{
GtkTreePath *path;
rowSelected = 0;
path = gtk_tree_path_new_from_string ("0");
gtk_tree_selection_select_path (gtk_tree_view_get_selection (GTK_TREE_VIEW (treeView)), path);
gtk_tree_path_free(path);
}
}
/*******************************************************************************************************************************/
static void event_dispatcher2(GtkWidget *widget, GdkEventButton *event, gpointer user_data)
{
GtkTreePath *path;
gint row = -1;
if (event->window == gtk_tree_view_get_bin_window (GTK_TREE_VIEW (widget))
&& !gtk_tree_view_get_path_at_pos (GTK_TREE_VIEW (widget),
event->x, event->y, NULL, NULL, NULL, NULL)) {
gtk_tree_selection_unselect_all (gtk_tree_view_get_selection (GTK_TREE_VIEW (widget)));
}
if(gtk_tree_view_get_path_at_pos (GTK_TREE_VIEW (widget), event->x, event->y, &path, NULL, NULL, NULL))
{
if(path)
{
gtk_tree_selection_select_path (gtk_tree_view_get_selection (GTK_TREE_VIEW (widget)), path);
row = atoi(gtk_tree_path_to_string(path));
gtk_tree_path_free(path);
}
}
rowSelected = row;
if(row<0) return;
if (event->type == GDK_BUTTON_PRESS && ((GdkEventButton *) event)->button == 3)
{
GdkEventButton *bevent = (GdkEventButton *) event;
GtkUIManager *manager = GTK_UI_MANAGER(user_data);
show_menu_popup(manager, bevent->button, bevent->time);
}
}
/********************************************************************************/
static GtkTreeView* addListOfAtoms(GtkWidget *vbox, GtkUIManager *manager)
{
GtkWidget *scr;
gint i;
gint widall=0;
gint widths[]={10};
gint Factor=7;
gint len = 1;
GtkTreeStore *store;
GtkTreeModel *model;
GtkCellRenderer *renderer;
GtkTreeView *treeView;
GtkTreeViewColumn *column;
store = gtk_tree_store_new (1,G_TYPE_STRING);
model = GTK_TREE_MODEL (store);
for(i=0;i<len;i++) widall+=widths[i];
widall=widall*Factor+40;
scr=gtk_scrolled_window_new(NULL,NULL);
gtk_widget_set_size_request(scr,widall,(gint)(ScreenHeight*0.1));
gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scr),GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
gtk_box_pack_start(GTK_BOX (vbox), scr,TRUE, TRUE, 2);
treeView = (GtkTreeView*)gtk_tree_view_new_with_model (model);
gtk_tree_view_set_rules_hint (GTK_TREE_VIEW (treeView), TRUE);
gtk_tree_view_set_headers_visible (GTK_TREE_VIEW (treeView), FALSE);
gtk_container_add(GTK_CONTAINER(scr),GTK_WIDGET(treeView));
for (i=0;i<len;i++)
{
column = gtk_tree_view_column_new ();
gtk_tree_view_column_set_title (column, "There atoms can do an hydrogen bonds");
gtk_tree_view_column_set_min_width(column, widths[i]*Factor);
gtk_tree_view_column_set_reorderable(column, TRUE);
{
GtkWidget* t = gtk_tree_view_column_get_widget (column);
if(t) gtk_widget_hide(t);
}
renderer = gtk_cell_renderer_text_new ();
gtk_tree_view_column_pack_start (column, renderer, TRUE);
gtk_tree_view_column_set_attributes (column, renderer, "text", 0, NULL);
gtk_tree_view_append_column (GTK_TREE_VIEW (treeView), column);
}
set_base_style(GTK_WIDGET(treeView),55000,55000,55000);
gtk_widget_show (GTK_WIDGET(treeView));
g_signal_connect (treeView, "button_press_event", G_CALLBACK (event_dispatcher2), manager);
return treeView;
}
/******************************************************************/
void set_HBonds_dialog (GtkWidget* winParent)
{
GtkWidget *fp;
GtkWidget *frame;
GtkWidget *vboxall;
GtkWidget *vboxframe;
GtkWidget *hbox;
GtkWidget *button;
GtkWidget *hseparator;
GtkWidget *label;
static GtkWidget* entrys[4];
gchar* tlabel[4]={N_("Min Distance (Angstroms)"),N_("Max Distance (Angstroms)"),N_("Min angle (degrees)"),N_("Max angle (degrees)")};
gint i;
GtkWidget* table;
gchar* t = NULL;
GtkUIManager *manager = NULL;
if(!winParent || !GTK_IS_WIDGET(winParent)) return;
fp = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_modal(GTK_WINDOW(fp),TRUE);
gtk_window_set_title(GTK_WINDOW(fp),_("Set the hydrogen's bonds parameters"));
gtk_container_set_border_width (GTK_CONTAINER (fp), 5);
gtk_window_set_position(GTK_WINDOW(fp),GTK_WIN_POS_CENTER);
gtk_window_set_modal (GTK_WINDOW (fp), TRUE);
gtk_window_set_transient_for(GTK_WINDOW(fp),GTK_WINDOW(winParent));
g_signal_connect(G_OBJECT(fp),"delete_event",(GCallback)gtk_widget_destroy,NULL);
vboxall = create_vbox(fp);
frame = gtk_frame_new (NULL);
gtk_container_set_border_width (GTK_CONTAINER (frame), 5);
gtk_container_add (GTK_CONTAINER (vboxall), frame);
gtk_widget_show (frame);
vboxframe = create_vbox(frame);
table = gtk_table_new(10,3,FALSE);
gtk_box_pack_start(GTK_BOX(vboxframe), table,TRUE,TRUE,0);
for(i=0;i<4;i++)
{
add_label_table(table,tlabel[i],(gushort)i,0);
add_label_table(table," : ",(gushort)i,1);
entrys[i] = gtk_entry_new ();
gtk_table_attach(GTK_TABLE(table),entrys[i],2,2+1,i,i+1,
(GtkAttachOptions)(GTK_FILL | GTK_EXPAND) ,
(GtkAttachOptions)(GTK_FILL | GTK_EXPAND),
3,3);
}
t = g_strdup_printf("%f",minDistance);
gtk_entry_set_text(GTK_ENTRY(entrys[0]),t);
g_free(t);
t = g_strdup_printf("%f",maxDistance);
gtk_entry_set_text(GTK_ENTRY(entrys[1]),t);
g_free(t);
t = g_strdup_printf("%f",minAngle);
gtk_entry_set_text(GTK_ENTRY(entrys[2]),t);
g_free(t);
t = g_strdup_printf("%f",maxAngle);
gtk_entry_set_text(GTK_ENTRY(entrys[3]),t);
g_free(t);
i = 4;
hseparator = gtk_hseparator_new ();
gtk_table_attach(GTK_TABLE(table),hseparator,0,0+3,i,i+1,
(GtkAttachOptions)(GTK_FILL | GTK_EXPAND) ,
(GtkAttachOptions)(GTK_FILL | GTK_EXPAND),
3,3);
i = 5;
hbox = gtk_hbox_new(0,FALSE);
label = gtk_label_new (_(" There atoms can do an hydrogen bonds.\n Use right button of mouse to modify this list."));
gtk_label_set_justify(GTK_LABEL(label),GTK_JUSTIFY_LEFT);
gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0);
gtk_table_attach(GTK_TABLE(table),hbox,0,0+3,i,i+1,
(GtkAttachOptions)(GTK_FILL | GTK_EXPAND) ,
(GtkAttachOptions)(GTK_FILL | GTK_EXPAND),
3,3);
i = 6;
hbox = gtk_hbox_new (TRUE, 0);
gtk_table_attach(GTK_TABLE(table),hbox,0,0+3,i,i+1,
(GtkAttachOptions)(GTK_FILL | GTK_EXPAND) ,
(GtkAttachOptions)(GTK_FILL | GTK_EXPAND),
3,3);
manager = create_menu(fp);
treeViewOfAtoms = addListOfAtoms(hbox, manager);
hbox = create_hbox(vboxall);
button = create_button(winParent,"OK");
gtk_box_pack_start (GTK_BOX( hbox), button, TRUE, TRUE, 3);
g_signal_connect(G_OBJECT(button), "clicked",G_CALLBACK(set_HBonds),(gpointer)entrys);
g_signal_connect_swapped(G_OBJECT(button), "clicked",G_CALLBACK(gtk_widget_destroy),GTK_OBJECT(fp));
gtk_widget_show (button);
button = create_button(winParent,"Apply");
gtk_box_pack_start (GTK_BOX( hbox), button, TRUE, TRUE, 3);
g_signal_connect(G_OBJECT(button), "clicked",G_CALLBACK(set_HBonds),(gpointer)entrys);
gtk_widget_show (button);
button = create_button(winParent,"Close");
gtk_box_pack_start (GTK_BOX( hbox), button, TRUE, TRUE, 3);
g_signal_connect_swapped(G_OBJECT(button), "clicked",G_CALLBACK(gtk_widget_destroy),GTK_OBJECT(fp));
gtk_widget_show (button);
rafreshTreeView(treeViewOfAtoms);
gtk_widget_show_all(fp);
}
/************************************************************************/
gdouble getMinDistanceHBonds()
{
return minDistance;
}
/************************************************************************/
gdouble getMaxDistanceHBonds()
{
return maxDistance;
}
/************************************************************************/
gdouble getMinAngleHBonds()
{
return minAngle;
}
/************************************************************************/
gdouble getMaxAngleHBonds()
{
return maxAngle;
}
/************************************************************************/
gboolean atomCanDoHydrogenBond(gchar* symbol)
{
gint k;
for(k=0;k<nAtomsCanConnect;k++) if(strcmp(symbol,atomsCanConnect[k])==0) return TRUE;
return FALSE;
}
/************************************************************************/
| 34.202572 | 134 | 0.654555 | [
"geometry",
"model"
] |
b8f46031a58c2422582c72df1e622c1b871e10dd | 1,886 | h | C | lammps-master/lib/poems/poemstreenode.h | rajkubp020/helloword | 4bd22691de24b30a0f5b73821c35a7ac0666b034 | [
"MIT"
] | null | null | null | lammps-master/lib/poems/poemstreenode.h | rajkubp020/helloword | 4bd22691de24b30a0f5b73821c35a7ac0666b034 | [
"MIT"
] | null | null | null | lammps-master/lib/poems/poemstreenode.h | rajkubp020/helloword | 4bd22691de24b30a0f5b73821c35a7ac0666b034 | [
"MIT"
] | null | null | null | /*
*_________________________________________________________________________*
* POEMS: PARALLELIZABLE OPEN SOURCE EFFICIENT MULTIBODY SOFTWARE *
* DESCRIPTION: SEE READ-ME *
* FILE NAME: poemstreenode.h *
* AUTHORS: See Author List *
* GRANTS: See Grants List *
* COPYRIGHT: (C) 2005 by Authors as listed in Author's List *
* LICENSE: Please see License Agreement *
* DOWNLOAD: Free at www.rpi.edu/~anderk5 *
* ADMINISTRATOR: Prof. Kurt Anderson *
* Computational Dynamics Lab *
* Rensselaer Polytechnic Institute *
* 110 8th St. Troy NY 12180 *
* CONTACT: anderk5@rpi.edu *
*_________________________________________________________________________*/
#ifndef TREENODE_H
#define TREENODE_H
//#define NULL 0
//Tree depends on TreeNode
class Tree;
// declares a tree node object for a binary tree
class TreeNode{
private:
// points to the left and right children of the node
TreeNode *left;
TreeNode *right;
int balanceFactor;
int data;
void * aux_data;
public:
// make Tree a friend because it needs access to left and right pointer fields of a node
friend class Tree;
TreeNode * Left();
TreeNode * Right();
int GetData();
void * GetAuxData() {return aux_data;};
void SetAuxData(void * AuxData) {aux_data = AuxData;};
int GetBalanceFactor();
TreeNode(const int &item, TreeNode *lptr, TreeNode *rptr, int balfac = 0);
//friend class DCASolver;
};
#endif
| 35.584906 | 89 | 0.54666 | [
"object"
] |
b8f5221a68edf44186268c142a712109b87378b6 | 2,176 | h | C | Lumos/Source/Lumos/Graphics/Renderers/DeferredOffScreenRenderer.h | Derailedzack/Lumos | f5e1e4b408faebe4c393bab4bba3743608d4e171 | [
"MIT"
] | 2 | 2021-06-04T09:49:23.000Z | 2021-06-14T02:52:36.000Z | Lumos/Source/Lumos/Graphics/Renderers/DeferredOffScreenRenderer.h | gameconstructer/Lumos | 92f6e812fdfc9404bf557e131679ae9071f25c80 | [
"MIT"
] | null | null | null | Lumos/Source/Lumos/Graphics/Renderers/DeferredOffScreenRenderer.h | gameconstructer/Lumos | 92f6e812fdfc9404bf557e131679ae9071f25c80 | [
"MIT"
] | null | null | null | #pragma once
#include "IRenderer.h"
#include "Maths/Frustum.h"
namespace Lumos
{
class LightSetup;
namespace Graphics
{
class Pipeline;
class DescriptorSet;
class GBuffer;
class Texture2D;
class TextureDepth;
class TextureDepthArray;
class SkyboxRenderer;
class Shader;
class ShadowRenderer;
class Framebuffer;
class Material;
class LUMOS_EXPORT DeferredOffScreenRenderer : public IRenderer
{
public:
DeferredOffScreenRenderer(uint32_t width, uint32_t height);
~DeferredOffScreenRenderer() override;
void RenderScene() override;
void Init() override;
void Begin() override;
void BeginScene(Scene* scene, Camera* overrideCamera, Maths::Transform* overrideCameraTransforms) override;
void Submit(const RenderCommand& command) override;
void SubmitMesh(Mesh* mesh, Material* material, const Maths::Matrix4& transform, const Maths::Matrix4& textureMatrix) override;
void EndScene() override;
void End() override;
void Present() override;
void OnResize(uint32_t width, uint32_t height) override;
void PresentToScreen() override { }
void CreatePipeline();
void CreateBuffer();
void CreateFramebuffer();
void OnImGui() override;
bool HadRendered() const { return m_HasRendered; }
private:
void SetSystemUniforms(Shader* shader);
Material* m_DefaultMaterial;
UniformBuffer* m_UniformBuffer;
Ref<Shader> m_AnimatedShader = nullptr;
Ref<Lumos::Graphics::Pipeline> m_AnimatedPipeline;
UniformBuffer* m_AnimUniformBuffer;
uint8_t* m_VSSystemUniformBufferAnim = nullptr;
uint32_t m_VSSystemUniformBufferAnimSize = 0;
struct UniformBufferModel
{
Maths::Matrix4* model;
};
UniformBufferModel m_UBODataDynamic;
bool m_HasRendered = false;
};
}
}
| 29.808219 | 139 | 0.608456 | [
"mesh",
"model",
"transform"
] |
b8fac966de340903621fbb19d01b22db18a25905 | 3,649 | h | C | src/saiga/core/image/managedImage.h | SimonMederer/saiga | ff167e60c50b1cead4d19eb5ab2e93acce8c42a3 | [
"MIT"
] | null | null | null | src/saiga/core/image/managedImage.h | SimonMederer/saiga | ff167e60c50b1cead4d19eb5ab2e93acce8c42a3 | [
"MIT"
] | null | null | null | src/saiga/core/image/managedImage.h | SimonMederer/saiga | ff167e60c50b1cead4d19eb5ab2e93acce8c42a3 | [
"MIT"
] | null | null | null | /**
* Copyright (c) 2017 Darius Rückert
* Licensed under the MIT License.
* See LICENSE file for more information.
*/
#pragma once
#include "saiga/core/image/imageBase.h"
#include "saiga/core/image/imageFormat.h"
#include "saiga/core/image/imageView.h"
#include "saiga/core/util/DataStructures/ArrayView.h"
#include <vector>
namespace Saiga
{
#define DEFAULT_ALIGNMENT 4
/**
* Note: The first scanline is at position data[0].
*/
class SAIGA_CORE_API Image : public ImageBase
{
public:
using byte_t = unsigned char;
ImageType type = TYPE_UNKNOWN;
protected:
std::vector<byte_t> vdata;
public:
Image() {}
Image(ImageType type) : type(type) {}
Image(int h, int w, ImageType type);
Image(ImageDimensions dimensions, ImageType type);
Image(const std::string& file)
{
auto res = load(file);
SAIGA_ASSERT(res);
}
// Note: This creates a copy of img
template <typename T>
Image(ImageView<T> img)
{
setFormatFromImageView(img);
create();
img.copyTo(getImageView<T>());
}
void create();
void create(ImageDimensions dimensions);
void create(int h, int w);
void create(int h, int w, ImageType t);
void create(int h, int w, int p, ImageType t);
void clear();
void free();
/**
* @brief makeZero
* Sets all data to 0.
*/
void makeZero();
/**
* @brief valid
* Checks if this image has at least 1 pixel and a valid type.
*/
bool valid() const;
void* data() { return vdata.data(); }
const void* data() const { return vdata.data(); }
uint8_t* data8() { return vdata.data(); }
const uint8_t* data8() const { return vdata.data(); }
template <typename T>
inline T& at(int y, int x)
{
return reinterpret_cast<T*>(rowPtr(y))[x];
}
inline void* rowPtr(int y)
{
auto ptr = data8() + y * pitchBytes;
return ptr;
}
inline const void* rowPtr(int y) const
{
auto ptr = data8() + y * pitchBytes;
return ptr;
}
template <typename T>
ImageView<T> getImageView()
{
SAIGA_ASSERT(ImageTypeTemplate<T>::type == type);
ImageView<T> res(*this);
res.data = data();
return res;
}
template <typename T>
ImageView<const T> getConstImageView() const
{
SAIGA_ASSERT(ImageTypeTemplate<T>::type == type);
ImageView<const T> res(*this);
res.data = data();
return res;
}
template <typename T>
void setFormatFromImageView(ImageView<T> v)
{
ImageBase::operator=(v);
type = ImageTypeTemplate<T>::type;
pitchBytes = 0;
}
template <typename T>
void createEmptyFromImageView(ImageView<T> v)
{
setFormatFromImageView<T>(v);
create();
}
bool load(const std::string& path);
bool loadFromMemory(ArrayView<const char> data);
bool save(const std::string& path) const;
// save in a custom saiga format
// this can handle all image types
bool loadRaw(const std::string& path);
bool saveRaw(const std::string& path) const;
/**
* Tries to convert the given image to a storable format.
* For example:
* Floating point images are converted to 8-bit grayscale images.
*/
bool saveConvert(const std::string& path, float minValue = 0, float maxValue = 1);
std::vector<uint8_t> compress();
void decompress(std::vector<uint8_t> data);
SAIGA_CORE_API friend std::ostream& operator<<(std::ostream& os, const Image& f);
};
} // namespace Saiga
| 22.949686 | 86 | 0.607564 | [
"vector"
] |
b8fefd2a4218040b3557d97ab884e10b902789d0 | 5,801 | h | C | TestSTLL/async/async++/scheduler.h | daipech/STLL | c3a8e9e5ac7e39f2015041cb74735454833a709d | [
"MIT"
] | 3 | 2016-11-30T11:10:38.000Z | 2016-11-30T11:48:33.000Z | TestSTLL/async/async++/scheduler.h | daipech/STLL | c3a8e9e5ac7e39f2015041cb74735454833a709d | [
"MIT"
] | null | null | null | TestSTLL/async/async++/scheduler.h | daipech/STLL | c3a8e9e5ac7e39f2015041cb74735454833a709d | [
"MIT"
] | null | null | null | // Copyright (c) 2015 Amanieu d'Antras
//
// 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 ASYNCXX_H_
# error "Do not include this header directly, include <async++.h> instead."
#endif
namespace async {
// Improved version of std::hardware_concurrency:
// - It never returns 0, 1 is returned instead.
// - It is guaranteed to remain constant for the duration of the program.
LIBASYNC_EXPORT std::size_t hardware_concurrency() LIBASYNC_NOEXCEPT;
// Task handle used by a wait handler
class task_wait_handle {
detail::task_base* handle;
// Allow construction in wait_for_task()
friend LIBASYNC_EXPORT void detail::wait_for_task(detail::task_base* t);
task_wait_handle(detail::task_base* t)
: handle(t) {}
// Execution function for use by wait handlers
template<typename Func>
struct wait_exec_func: private detail::func_base<Func> {
template<typename F>
explicit wait_exec_func(F&& f)
: detail::func_base<Func>(std::forward<F>(f)) {}
void operator()(detail::task_base*)
{
// Just call the function directly, all this wrapper does is remove
// the task_base* parameter.
this->get_func()();
}
};
public:
task_wait_handle()
: handle(nullptr) {}
// Check if the handle is valid
explicit operator bool() const
{
return handle != nullptr;
}
// Check if the task has finished executing
bool ready() const
{
return detail::is_finished(handle->state.load(std::memory_order_acquire));
}
// Queue a function to be executed when the task has finished executing.
template<typename Func>
void on_finish(Func&& func)
{
// Make sure the function type is callable
static_assert(detail::is_callable<Func()>::value, "Invalid function type passed to on_finish()");
// We are passing nullptr to add_continuation because it doesn't use
// the parent's exception for always_cont continuations.
detail::task_ptr cont(new detail::task_func<typename std::remove_reference<decltype(inline_scheduler())>::type, wait_exec_func<typename std::decay<Func>::type>, detail::fake_void>(std::forward<Func>(func)));
handle->add_continuation(inline_scheduler(), std::move(cont), true, nullptr);
}
};
// Wait handler function prototype
typedef void (*wait_handler)(task_wait_handle t);
// Set a wait handler to control what a task does when it has "free time", which
// is when it is waiting for another task to complete. The wait handler can do
// other work, but should return when it detects that the task has completed.
// The previously installed handler is returned.
LIBASYNC_EXPORT wait_handler set_thread_wait_handler(wait_handler w) LIBASYNC_NOEXCEPT;
// Exception thrown if a task_run_handle is destroyed without being run
struct LIBASYNC_EXPORT_EXCEPTION task_not_executed {};
// Task handle used in scheduler, acts as a unique_ptr to a task object
class task_run_handle {
detail::task_ptr handle;
// Allow construction in schedule_task()
template<typename Sched>
friend void detail::schedule_task(Sched& sched, detail::task_ptr t);
explicit task_run_handle(detail::task_ptr t)
: handle(std::move(t)) {}
public:
// Movable but not copyable
task_run_handle() = default;
task_run_handle(task_run_handle&& other) LIBASYNC_NOEXCEPT
: handle(std::move(other.handle)) {}
task_run_handle& operator=(task_run_handle&& other) LIBASYNC_NOEXCEPT
{
handle = std::move(other.handle);
return *this;
}
// If the task is not executed, cancel it with an exception
~task_run_handle()
{
if (handle)
handle->vtable->cancel(handle.get(), std::make_exception_ptr(task_not_executed()));
}
// Check if the handle is valid
explicit operator bool() const
{
return handle != nullptr;
}
// Run the task and release the handle
void run()
{
handle->vtable->run(handle.get());
handle = nullptr;
}
// Run the task but run the given wait handler when waiting for a task,
// instead of just sleeping.
void run_with_wait_handler(wait_handler handler)
{
wait_handler old = set_thread_wait_handler(handler);
run();
set_thread_wait_handler(old);
}
// Conversion to and from void pointer. This allows the task handle to be
// sent through C APIs which don't preserve types.
void* to_void_ptr()
{
return handle.release();
}
static task_run_handle from_void_ptr(void* ptr)
{
return task_run_handle(detail::task_ptr(static_cast<detail::task_base*>(ptr)));
}
};
namespace detail {
// Schedule a task for execution using its scheduler
template<typename Sched>
void schedule_task(Sched& sched, task_ptr t)
{
static_assert(is_scheduler<Sched>::value, "Type is not a valid scheduler");
sched.schedule(task_run_handle(std::move(t)));
}
// Inline scheduler implementation
inline void inline_scheduler_impl::schedule(task_run_handle t)
{
t.run();
}
} // namespace detail
} // namespace async
| 32.774011 | 209 | 0.747285 | [
"object"
] |
6ae85b286ea1fb25648de502548473e17c59ce2b | 1,114 | h | C | include/bt_selector_random.h | willemt/yabtorrent | 2be304a831eb72be7baaf6c273c335049898b61c | [
"BSD-3-Clause"
] | 59 | 2015-02-25T01:44:22.000Z | 2022-03-26T07:41:13.000Z | include/bt_selector_random.h | willemt/yabtorrent | 2be304a831eb72be7baaf6c273c335049898b61c | [
"BSD-3-Clause"
] | 3 | 2016-01-20T21:54:33.000Z | 2017-06-19T13:44:01.000Z | include/bt_selector_random.h | willemt/yabtorrent | 2be304a831eb72be7baaf6c273c335049898b61c | [
"BSD-3-Clause"
] | 14 | 2015-02-25T01:38:19.000Z | 2020-11-07T21:44:19.000Z | #ifndef BT_SELECTOR_RANDOM_H
#define BT_SELECTOR_RANDOM_H
void *bt_random_selector_new(int npieces);
/**
* Add this piece back to the selector.
* This is usually when we want to make the piece a candidate again
*
* @param peer The peer that is giving it back.
* @param piece_idx The piece
*/
void bt_random_selector_giveback_piece(
void *r,
void* peer,
int piece_idx);
/**
* Notify selector that we have this piece */
void bt_random_selector_have_piece(void *r, int piece_idx);
void bt_random_selector_remove_peer(void *r, void *peer);
void bt_random_selector_add_peer(void *r, void *peer);
/**
* Let us know that there is a peer who has this piece
*/
void bt_random_selector_peer_have_piece(void *r, void *peer, int piece_idx);
int bt_random_selector_get_npeers(void *r);
int bt_random_selector_get_npieces(void *r);
/**
* Poll best piece from peer
* @param r random object
* @param peer Best piece in context of this peer
* @return idx of piece which is best; otherwise -1 */
int bt_random_selector_poll_best_piece(void *r, const void *peer);
#endif /* BT_SELECTOR_RANDOM_H */
| 25.906977 | 76 | 0.746858 | [
"object"
] |
6aed06cfd48b2856aafe8db7289d88152c7ba8bf | 15,445 | h | C | libvui/src/vui/lib/command.h | slankdev/netlinkd | 9873d845396b11beba771b55c4b87f66b1036019 | [
"MIT"
] | 2 | 2019-02-27T14:48:39.000Z | 2020-03-25T01:28:54.000Z | libvui/src/vui/lib/command.h | slankdev/netlinkd | 9873d845396b11beba771b55c4b87f66b1036019 | [
"MIT"
] | 1 | 2019-07-27T07:50:46.000Z | 2019-07-27T07:50:46.000Z | libvui/src/vui/lib/command.h | slankdev/netlinkd | 9873d845396b11beba771b55c4b87f66b1036019 | [
"MIT"
] | null | null | null | /*
* Zebra configuration command interface routine
* Copyright (C) 1997, 98 Kunihiro Ishiguro
*
* This file is part of GNU Zebra.
*
* GNU Zebra is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2, or (at your
* option) any later version.
*
* GNU Zebra is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; see the file COPYING; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _ZEBRA_COMMAND_H
#define _ZEBRA_COMMAND_H
#include "vector.h"
#include "vty.h"
#include "graph.h"
#include "memory.h"
#include "hash.h"
#include "command_graph.h"
#include "command_node.h"
#ifdef __cplusplus
extern "C" {
#endif
DECLARE_MTYPE(HOST)
DECLARE_MTYPE(COMPLETION)
/*
* From RFC 1123 (Requirements for Internet Hosts), Section 2.1 on hostnames:
* One aspect of host name syntax is hereby changed: the restriction on
* the first character is relaxed to allow either a letter or a digit.
* Host software MUST support this more liberal syntax.
*
* Host software MUST handle host names of up to 63 characters and
* SHOULD handle host names of up to 255 characters.
*/
#define HOSTNAME_LEN 255
/* Host configuration variable */
struct host {
/* Host name of this router. */
char *name;
/* Password for vty interface. */
char *password;
char *password_encrypt;
/* Enable password */
char *enable;
char *enable_encrypt;
/* System wide terminal lines. */
int lines;
/* Log filename. */
char *logfile;
/* config file name of this host */
char *config;
int noconfig;
/* Flags for services */
int advanced;
int encrypt;
/* Banner configuration. */
const char *motd;
char *motdfile;
};
extern vector cmdvec;
/* Return value of the commands. */
#define CMD_SUCCESS 0
#define CMD_WARNING 1
#define CMD_ERR_NO_MATCH 2
#define CMD_ERR_AMBIGUOUS 3
#define CMD_ERR_INCOMPLETE 4
#define CMD_ERR_EXEED_ARGC_MAX 5
#define CMD_ERR_NOTHING_TODO 6
#define CMD_COMPLETE_FULL_MATCH 7
#define CMD_COMPLETE_MATCH 8
#define CMD_COMPLETE_LIST_MATCH 9
#define CMD_SUCCESS_DAEMON 10
#define CMD_ERR_NO_FILE 11
#define CMD_SUSPEND 12
#define CMD_WARNING_CONFIG_FAILED 13
#define CMD_NOT_MY_INSTANCE 14
/* Argc max counts. */
#define CMD_ARGC_MAX 256
/* Turn off these macros when uisng cpp with extract.pl */
#ifndef VTYSH_EXTRACT_PL
/* helper defines for end-user DEFUN* macros */
#define DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, attrs, dnum) \
static struct cmd_element cmdname = { \
.string = cmdstr, \
.doc = helpstr, \
.daemon = dnum, \
.attr = attrs, \
.func = funcname, \
.name = #cmdname, \
};
#define DEFUN_CMD_FUNC_DECL(funcname) \
static int funcname(const struct cmd_element *, struct vty *, int, \
struct cmd_token *[]);
#define DEFUN_CMD_FUNC_TEXT(funcname) \
static int funcname(const struct cmd_element *self \
__attribute__((unused)), \
struct vty *vty __attribute__((unused)), \
int argc __attribute__((unused)), \
struct cmd_token *argv[] __attribute__((unused)))
#define DEFPY(funcname, cmdname, cmdstr, helpstr) \
DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, 0, 0) \
funcdecl_##funcname
#define DEFPY_NOSH(funcname, cmdname, cmdstr, helpstr) \
DEFPY(funcname, cmdname, cmdstr, helpstr)
#define DEFPY_ATTR(funcname, cmdname, cmdstr, helpstr, attr) \
DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, attr, 0) \
funcdecl_##funcname
#define DEFPY_HIDDEN(funcname, cmdname, cmdstr, helpstr) \
DEFPY_ATTR(funcname, cmdname, cmdstr, helpstr, CMD_ATTR_HIDDEN)
#define DEFUN(funcname, cmdname, cmdstr, helpstr) \
DEFUN_CMD_FUNC_DECL(funcname) \
DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, 0, 0) \
DEFUN_CMD_FUNC_TEXT(funcname)
#define DEFUN_ATTR(funcname, cmdname, cmdstr, helpstr, attr) \
DEFUN_CMD_FUNC_DECL(funcname) \
DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, attr, 0) \
DEFUN_CMD_FUNC_TEXT(funcname)
#define DEFUN_HIDDEN(funcname, cmdname, cmdstr, helpstr) \
DEFUN_ATTR(funcname, cmdname, cmdstr, helpstr, CMD_ATTR_HIDDEN)
/* DEFUN_NOSH for commands that vtysh should ignore */
#define DEFUN_NOSH(funcname, cmdname, cmdstr, helpstr) \
DEFUN(funcname, cmdname, cmdstr, helpstr)
/* DEFSH for vtysh. */
#define DEFSH(daemon, cmdname, cmdstr, helpstr) \
DEFUN_CMD_ELEMENT(NULL, cmdname, cmdstr, helpstr, 0, daemon)
#define DEFSH_HIDDEN(daemon, cmdname, cmdstr, helpstr) \
DEFUN_CMD_ELEMENT(NULL, cmdname, cmdstr, helpstr, CMD_ATTR_HIDDEN, \
daemon)
/* DEFUN + DEFSH */
#define DEFUNSH(daemon, funcname, cmdname, cmdstr, helpstr) \
DEFUN_CMD_FUNC_DECL(funcname) \
DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, 0, daemon) \
DEFUN_CMD_FUNC_TEXT(funcname)
/* DEFUN + DEFSH with attributes */
#define DEFUNSH_ATTR(daemon, funcname, cmdname, cmdstr, helpstr, attr) \
DEFUN_CMD_FUNC_DECL(funcname) \
DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, attr, daemon) \
DEFUN_CMD_FUNC_TEXT(funcname)
#define DEFUNSH_HIDDEN(daemon, funcname, cmdname, cmdstr, helpstr) \
DEFUNSH_ATTR(daemon, funcname, cmdname, cmdstr, helpstr, \
CMD_ATTR_HIDDEN)
#define DEFUNSH_DEPRECATED(daemon, funcname, cmdname, cmdstr, helpstr) \
DEFUNSH_ATTR(daemon, funcname, cmdname, cmdstr, helpstr, \
CMD_ATTR_DEPRECATED)
/* ALIAS macro which define existing command's alias. */
#define ALIAS(funcname, cmdname, cmdstr, helpstr) \
DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, 0, 0)
#define ALIAS_ATTR(funcname, cmdname, cmdstr, helpstr, attr) \
DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, attr, 0)
#define ALIAS_HIDDEN(funcname, cmdname, cmdstr, helpstr) \
DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, CMD_ATTR_HIDDEN, \
0)
#define ALIAS_DEPRECATED(funcname, cmdname, cmdstr, helpstr) \
DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, \
CMD_ATTR_DEPRECATED, 0)
#define ALIAS_SH(daemon, funcname, cmdname, cmdstr, helpstr) \
DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, 0, daemon)
#define ALIAS_SH_HIDDEN(daemon, funcname, cmdname, cmdstr, helpstr) \
DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, CMD_ATTR_HIDDEN, \
daemon)
#define ALIAS_SH_DEPRECATED(daemon, funcname, cmdname, cmdstr, helpstr) \
DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, \
CMD_ATTR_DEPRECATED, daemon)
#else /* VTYSH_EXTRACT_PL */
#define DEFPY(funcname, cmdname, cmdstr, helpstr) \
DEFUN(funcname, cmdname, cmdstr, helpstr)
#define DEFPY_NOSH(funcname, cmdname, cmdstr, helpstr) \
DEFUN_NOSH(funcname, cmdname, cmdstr, helpstr)
#define DEFPY_ATTR(funcname, cmdname, cmdstr, helpstr, attr) \
DEFUN_ATTR(funcname, cmdname, cmdstr, helpstr, attr)
#define DEFPY_HIDDEN(funcname, cmdname, cmdstr, helpstr) \
DEFUN_HIDDEN(funcname, cmdname, cmdstr, helpstr)
#endif /* VTYSH_EXTRACT_PL */
/* Some macroes */
/*
* Sometimes #defines create maximum values that
* need to have strings created from them that
* allow the parser to match against them.
* These macros allow that.
*/
#define CMD_CREATE_STR(s) CMD_CREATE_STR_HELPER(s)
#define CMD_CREATE_STR_HELPER(s) #s
#define CMD_RANGE_STR(a,s) "(" CMD_CREATE_STR(a) "-" CMD_CREATE_STR(s) ")"
/* Common descriptions. */
#define SHOW_STR "Show running system information\n"
#define IP_STR "IP information\n"
#define IPV6_STR "IPv6 information\n"
#define NO_STR "Negate a command or set its defaults\n"
#define REDIST_STR "Redistribute information from another routing protocol\n"
#define CLEAR_STR "Reset functions\n"
#define RIP_STR "RIP information\n"
#define EIGRP_STR "EIGRP information\n"
#define BGP_STR "BGP information\n"
#define BGP_SOFT_STR "Soft reconfig inbound and outbound updates\n"
#define BGP_SOFT_IN_STR "Send route-refresh unless using 'soft-reconfiguration inbound'\n"
#define BGP_SOFT_OUT_STR "Resend all outbound updates\n"
#define BGP_SOFT_RSCLIENT_RIB_STR "Soft reconfig for rsclient RIB\n"
#define OSPF_STR "OSPF information\n"
#define NEIGHBOR_STR "Specify neighbor router\n"
#define DEBUG_STR "Debugging functions\n"
#define UNDEBUG_STR "Disable debugging functions (see also 'debug')\n"
#define ROUTER_STR "Enable a routing process\n"
#define AS_STR "AS number\n"
#define MAC_STR "MAC address\n"
#define MBGP_STR "MBGP information\n"
#define MATCH_STR "Match values from routing table\n"
#define SET_STR "Set values in destination routing protocol\n"
#define OUT_STR "Filter outgoing routing updates\n"
#define IN_STR "Filter incoming routing updates\n"
#define V4NOTATION_STR "specify by IPv4 address notation(e.g. 0.0.0.0)\n"
#define OSPF6_NUMBER_STR "Specify by number\n"
#define INTERFACE_STR "Interface information\n"
#define IFNAME_STR "Interface name(e.g. ep0)\n"
#define IP6_STR "IPv6 Information\n"
#define OSPF6_STR "Open Shortest Path First (OSPF) for IPv6\n"
#define OSPF6_INSTANCE_STR "(1-65535) Instance ID\n"
#define SECONDS_STR "Seconds\n"
#define ROUTE_STR "Routing Table\n"
#define PREFIX_LIST_STR "Build a prefix list\n"
#define OSPF6_DUMP_TYPE_LIST "<neighbor|interface|area|lsa|zebra|config|dbex|spf|route|lsdb|redistribute|hook|asbr|prefix|abr>"
#define AREA_TAG_STR "[area tag]\n"
#define COMMUNITY_AANN_STR "Community number where AA and NN are (0-65535)\n"
#define COMMUNITY_VAL_STR "Community number in AA:NN format (where AA and NN are (0-65535)) or local-AS|no-advertise|no-export|internet or additive\n"
#define MPLS_TE_STR "MPLS-TE specific commands\n"
#define LINK_PARAMS_STR "Configure interface link parameters\n"
#define OSPF_RI_STR "OSPF Router Information specific commands\n"
#define PCE_STR "PCE Router Information specific commands\n"
#define MPLS_STR "MPLS information\n"
#define SR_STR "Segment-Routing specific commands\n"
#define WATCHFRR_STR "watchfrr information\n"
#define ZEBRA_STR "Zebra information\n"
#define CMD_VNI_RANGE "(1-16777215)"
#define CONF_BACKUP_EXT ".sav"
/* Command warnings. */
#define NO_PASSWD_CMD_WARNING \
"Please be aware that removing the password is a security risk and you should think twice about this command.\n"
/* IPv4 only machine should not accept IPv6 address for peer's IP
address. So we replace VTY command string like below. */
#define NEIGHBOR_ADDR_STR "Neighbor address\nIPv6 address\n"
#define NEIGHBOR_ADDR_STR2 "Neighbor address\nNeighbor IPv6 address\nInterface name or neighbor tag\n"
#define NEIGHBOR_ADDR_STR3 "Neighbor address\nIPv6 address\nInterface name\n"
/* Prototypes. */
extern void install_node(struct cmd_node *, int (*)(struct vty *));
extern void install_default(enum node_type);
extern void install_element(enum node_type, struct cmd_element *);
/* known issue with uninstall_element: changes to cmd_token->attr (i.e.
* deprecated/hidden) are not reversed. */
extern void uninstall_element(enum node_type, struct cmd_element *);
/* Concatenates argv[shift] through argv[argc-1] into a single NUL-terminated
string with a space between each element (allocated using
XMALLOC(MTYPE_TMP)). Returns NULL if shift >= argc. */
extern char *argv_concat(struct cmd_token **argv, int argc, int shift);
/*
* It is preferred that you set the index initial value
* to a 0. This way in the future if you modify the
* cli then there is no need to modify the initial
* value of the index
*/
extern int argv_find(struct cmd_token **argv, int argc, const char *text, int *index);
extern vector cmd_make_strvec(const char *);
extern void cmd_free_strvec(vector);
extern vector cmd_describe_command(vector, struct vty *, int *status);
extern char **cmd_complete_command(vector, struct vty *, int *status);
extern const char *cmd_prompt(enum node_type);
extern int command_config_read_one_line(struct vty *vty,
const struct cmd_element **,
uint32_t line_num, int use_config_node);
extern int config_from_file(struct vty *, FILE *, unsigned int *line_num);
/*
* Execute command under the given vty context.
*
* vty
* The vty context to execute under.
*
* cmd
* The command string to execute.
*
* matched
* If non-null and a match was found, the address of the matched command is
* stored here. No action otherwise.
*
* vtysh
* Whether or not this is being called from vtysh. If this is nonzero,
* XXX: then what?
*
* Returns:
* XXX: what does it return
*/
extern int cmd_execute(struct vty *vty, const char *cmd,
const struct cmd_element **matched, int vtysh);
extern int cmd_execute_command(vector, struct vty *,
const struct cmd_element **, int);
extern int cmd_execute_command_strict(vector, struct vty *,
const struct cmd_element **);
extern void cmd_init(void);
extern void cmd_terminate(void);
extern void cmd_exit(struct vty *vty);
extern int cmd_list_cmds(struct vty *vty, int do_permute);
extern int cmd_password_set(const char *password);
extern int cmd_hostname_set(const char *hostname);
extern const char *cmd_hostname_get(void);
extern vector completions_to_vec(struct list *completions);
/* Export typical functions. */
extern const char *host_config_get(void);
extern void host_config_set(const char *);
extern void print_version(const char *);
extern int cmd_banner_motd_file(const char *);
/* struct host global, ick */
extern struct host host;
struct cmd_variable_handler {
const char *tokenname, *varname;
void (*completions)(vector out, struct cmd_token *token);
};
extern void cmd_variable_complete(struct cmd_token *token, const char *arg, vector comps);
extern void cmd_variable_handler_register(const struct cmd_variable_handler *cvh);
extern char *cmd_variable_comp2str(vector comps, unsigned short cols);
extern void command_setup_early_logging(const char *dest, const char *level);
#ifdef __cplusplus
}
#endif
#endif /* _ZEBRA_COMMAND_H */
| 39.300254 | 151 | 0.689803 | [
"vector"
] |
6afe84f3f2a6990d6cdd73d82a4fa386f53c8bfe | 2,840 | h | C | deps/pog/include/pog/token_builder.h | xbabka01/yaramod | c6837f4ff4dfe2a731e5eefa95c0f58778e00c5d | [
"MIT",
"BSD-3-Clause"
] | 51 | 2019-04-25T14:54:05.000Z | 2022-03-16T22:34:09.000Z | deps/pog/include/pog/token_builder.h | xbabka01/yaramod | c6837f4ff4dfe2a731e5eefa95c0f58778e00c5d | [
"MIT",
"BSD-3-Clause"
] | 100 | 2019-04-21T01:22:54.000Z | 2022-03-23T11:52:56.000Z | deps/pog/include/pog/token_builder.h | xbabka01/yaramod | c6837f4ff4dfe2a731e5eefa95c0f58778e00c5d | [
"MIT",
"BSD-3-Clause"
] | 29 | 2019-04-22T02:43:41.000Z | 2022-03-19T01:56:21.000Z | #pragma once
#include <pog/grammar.h>
#include <pog/token.h>
#include <pog/tokenizer.h>
namespace pog {
template <typename ValueT>
class TokenBuilder
{
public:
using GrammarType = Grammar<ValueT>;
using SymbolType = Symbol<ValueT>;
using TokenType = Token<ValueT>;
using TokenizerType = Tokenizer<ValueT>;
TokenBuilder(GrammarType* grammar, TokenizerType* tokenizer) : _grammar(grammar), _tokenizer(tokenizer), _pattern("$"),
_symbol_name(), _precedence(), _action(), _fullword(false), _end_token(true), _in_states{std::string{TokenizerType::DefaultState}}, _enter_state() {}
TokenBuilder(GrammarType* grammar, TokenizerType* tokenizer, const std::string& pattern) : _grammar(grammar), _tokenizer(tokenizer), _pattern(pattern),
_symbol_name(), _precedence(), _action(), _fullword(false), _end_token(false), _in_states{std::string{TokenizerType::DefaultState}}, _enter_state() {}
void done()
{
TokenType* token;
if (!_end_token)
{
auto* symbol = !_symbol_name.empty() ? _grammar->add_symbol(SymbolKind::Terminal, _symbol_name) : nullptr;
token = _tokenizer->add_token(_fullword ? fmt::format("{}(\\b|$)", _pattern) : _pattern, symbol, std::move(_in_states));
if (symbol && _precedence)
{
const auto& prec = _precedence.value();
symbol->set_precedence(prec.level, prec.assoc);
}
if(symbol && _description.size() != 0)
symbol->set_description(_description);
if (_enter_state)
token->set_transition_to_state(_enter_state.value());
}
else
{
token = _tokenizer->get_end_token();
for (auto&& state : _in_states)
token->add_active_in_state(std::move(state));
}
if (_action)
token->set_action(std::move(_action));
}
TokenBuilder& symbol(const std::string& symbol_name)
{
_symbol_name = symbol_name;
return *this;
}
TokenBuilder& precedence(std::uint32_t level, Associativity assoc)
{
_precedence = Precedence{level, assoc};
return *this;
}
TokenBuilder& description(const std::string& text)
{
_description = text;
return *this;
}
template <typename CallbackT>
TokenBuilder& action(CallbackT&& action)
{
_action = std::forward<CallbackT>(action);
return *this;
}
TokenBuilder& fullword()
{
_fullword = true;
return *this;
}
template <typename... Args>
TokenBuilder& states(Args&&... args)
{
_in_states = {std::forward<Args>(args)...};
return *this;
}
TokenBuilder& enter_state(const std::string& state)
{
_enter_state = state;
return *this;
}
private:
GrammarType* _grammar;
TokenizerType* _tokenizer;
std::string _description;
std::string _pattern;
std::string _symbol_name;
std::optional<Precedence> _precedence;
typename TokenType::CallbackType _action;
bool _fullword;
bool _end_token;
std::vector<std::string> _in_states;
std::optional<std::string> _enter_state;
};
} // namespace pog
| 25.132743 | 152 | 0.711268 | [
"vector"
] |
6afeab04e3ae9dcf00b176fdb58fe452f2396119 | 2,294 | c | C | src/ui/components/show_logo.c | conte91/bitbox02-firmware | 8a3b311583c33e70fd8a99e2247004d8eaf406df | [
"Apache-2.0"
] | null | null | null | src/ui/components/show_logo.c | conte91/bitbox02-firmware | 8a3b311583c33e70fd8a99e2247004d8eaf406df | [
"Apache-2.0"
] | null | null | null | src/ui/components/show_logo.c | conte91/bitbox02-firmware | 8a3b311583c33e70fd8a99e2247004d8eaf406df | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 Shift Cryptosecurity AG
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "show_logo.h"
#include "image.h"
#include "ui_images.h"
#include <stdint.h>
#include <string.h>
#include <hardfault.h>
#include <screen.h>
#include <ui/ui_util.h>
/**
* The component data.
*/
typedef struct {
uint16_t screen_count;
} orientation_data_t;
static void _render(component_t* component)
{
ui_util_component_render_subcomponents(component);
}
/********************************** Component Functions **********************************/
/**
* Collects all component functions.
*/
static component_functions_t _component_functions = {
.cleanup = ui_util_component_cleanup,
.render = _render,
.on_event = ui_util_on_event_noop,
};
/********************************** Create Instance **********************************/
component_t* show_logo_create(void)
{
component_t* show_logo = malloc(sizeof(component_t));
if (!show_logo) {
Abort("Error: malloc show_logo");
}
orientation_data_t* data = malloc(sizeof(orientation_data_t));
if (!data) {
Abort("Error: malloc show_logo data");
}
memset(data, 0, sizeof(orientation_data_t));
memset(show_logo, 0, sizeof(*show_logo));
data->screen_count = 0;
show_logo->data = data;
show_logo->f = &_component_functions;
show_logo->dimension.width = SCREEN_WIDTH;
show_logo->dimension.height = SCREEN_HEIGHT;
show_logo->position.top = 0;
show_logo->position.left = 0;
component_t* bb2_logo = image_create(
IMAGE_BB2_LOGO,
sizeof(IMAGE_BB2_LOGO),
IMAGE_BB2_LOGO_W,
IMAGE_BB2_LOGO_H,
CENTER,
show_logo);
ui_util_add_sub_component(show_logo, bb2_logo);
return show_logo;
}
| 26.988235 | 91 | 0.66129 | [
"render"
] |
ed0693564ddccbbf11f3ef0f0c3dce84dabcb7f5 | 17,608 | c | C | Optimization/LevmarAndroid/jni/Thirdparty/clapack/TESTING/LIN/sdrvrfp.c | faipaz/Algorithms | 738991d5e4372ef6ba8e489ea867d92ea406b729 | [
"MIT"
] | 48 | 2015-01-28T00:09:49.000Z | 2021-12-09T11:38:59.000Z | Optimization/LevmarAndroid/jni/Thirdparty/clapack/TESTING/LIN/sdrvrfp.c | faipaz/Algorithms | 738991d5e4372ef6ba8e489ea867d92ea406b729 | [
"MIT"
] | 8 | 2017-05-30T16:58:39.000Z | 2022-02-22T16:51:34.000Z | ExternalCode/lapack/TESTING/LIN/sdrvrfp.c | daniel-anavaino/tinkercell | 7896a7f809a0373ab3c848d25e3691d10a648437 | [
"BSD-3-Clause"
] | 12 | 2015-01-21T12:54:46.000Z | 2022-01-20T03:44:26.000Z | /* sdrvrfp.f -- translated by f2c (version 20061008).
You must link the resulting object file with libf2c:
on Microsoft Windows system, link with libf2c.lib;
on Linux or Unix systems, link with .../path/to/libf2c.a -lm
or, if you install libf2c.a in a standard place, with -lf2c -lm
-- in that order, at the end of the command line, as in
cc *.o -lf2c -lm
Source for libf2c is in /netlib/f2c/libf2c.zip, e.g.,
http://www.netlib.org/f2c/libf2c.zip
*/
#include "f2c.h"
#include "blaswrap.h"
/* Common Block Declarations */
struct {
char srnamt[32];
} srnamc_;
#define srnamc_1 srnamc_
/* Table of constant values */
static integer c__0 = 0;
static integer c_n1 = -1;
static integer c__1 = 1;
/* Subroutine */ int sdrvrfp_(integer *nout, integer *nn, integer *nval,
integer *nns, integer *nsval, integer *nnt, integer *ntval, real *
thresh, real *a, real *asav, real *afac, real *ainv, real *b, real *
bsav, real *xact, real *x, real *arf, real *arfinv, real *
s_work_slatms__, real *s_work_spot01__, real *s_temp_spot02__, real *
s_temp_spot03__, real *s_work_slansy__, real *s_work_spot02__, real *
s_work_spot03__)
{
/* Initialized data */
static integer iseedy[4] = { 1988,1989,1990,1991 };
static char uplos[1*2] = "U" "L";
static char forms[1*2] = "N" "T";
/* Format strings */
static char fmt_9999[] = "(1x,a6,\002, UPLO='\002,a1,\002', N =\002,i5"
",\002, type \002,i1,\002, test(\002,i1,\002)=\002,g12.5)";
/* System generated locals */
integer i__1, i__2, i__3, i__4, i__5, i__6, i__7;
/* Builtin functions */
/* Subroutine */ int s_copy(char *, char *, ftnlen, ftnlen);
integer s_wsfe(cilist *), do_fio(integer *, char *, ftnlen), e_wsfe(void);
/* Local variables */
integer i__, k, n, kl, ku, nt, lda, ldb, iin, iis, iit, ioff, mode, info,
imat;
char dist[1];
integer nrhs;
char uplo[1];
integer nrun, nfail, iseed[4];
char cform[1];
extern /* Subroutine */ int sget04_(integer *, integer *, real *, integer
*, real *, integer *, real *, real *);
integer iform;
real anorm;
char ctype[1];
extern /* Subroutine */ int spot01_(char *, integer *, real *, integer *,
real *, integer *, real *, real *);
integer iuplo, nerrs, izero;
extern /* Subroutine */ int spot02_(char *, integer *, integer *, real *,
integer *, real *, integer *, real *, integer *, real *, real *), spot03_(char *, integer *, real *, integer *, real *,
integer *, real *, integer *, real *, real *, real *);
logical zerot;
extern /* Subroutine */ int slatb4_(char *, integer *, integer *, integer
*, char *, integer *, integer *, real *, integer *, real *, char *
), aladhd_(integer *, char *),
alaerh_(char *, char *, integer *, integer *, char *, integer *,
integer *, integer *, integer *, integer *, integer *, integer *,
integer *, integer *);
real rcondc;
extern /* Subroutine */ int alasvm_(char *, integer *, integer *, integer
*, integer *);
real cndnum, ainvnm;
extern /* Subroutine */ int slacpy_(char *, integer *, integer *, real *,
integer *, real *, integer *), slarhs_(char *, char *,
char *, char *, integer *, integer *, integer *, integer *,
integer *, real *, integer *, real *, integer *, real *, integer *
, integer *, integer *), slatms_(
integer *, integer *, char *, integer *, char *, real *, integer *
, real *, real *, integer *, integer *, char *, real *, integer *,
real *, integer *), spftrf_(char *, char
*, integer *, real *, integer *), spftri_(char *,
char *, integer *, real *, integer *);
extern doublereal slansy_(char *, char *, integer *, real *, integer *,
real *);
extern /* Subroutine */ int spotrf_(char *, integer *, real *, integer *,
integer *);
real result[4];
extern /* Subroutine */ int spftrs_(char *, char *, integer *, integer *,
real *, real *, integer *, integer *), spotri_(
char *, integer *, real *, integer *, integer *), stfttr_(
char *, char *, integer *, real *, real *, integer *, integer *), strttf_(char *, char *, integer *, real *,
integer *, real *, integer *);
/* Fortran I/O blocks */
static cilist io___37 = { 0, 0, 0, fmt_9999, 0 };
/* -- LAPACK test routine (version 3.2.0) -- */
/* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */
/* November 2008 */
/* .. Scalar Arguments .. */
/* .. */
/* .. Array Arguments .. */
/* .. */
/* Purpose */
/* ======= */
/* SDRVRFP tests the LAPACK RFP routines: */
/* SPFTRF, SPFTRS, and SPFTRI. */
/* This testing routine follow the same tests as DDRVPO (test for the full */
/* format Symmetric Positive Definite solver). */
/* The tests are performed in Full Format, convertion back and forth from */
/* full format to RFP format are performed using the routines STRTTF and */
/* STFTTR. */
/* First, a specific matrix A of size N is created. There is nine types of */
/* different matrixes possible. */
/* 1. Diagonal 6. Random, CNDNUM = sqrt(0.1/EPS) */
/* 2. Random, CNDNUM = 2 7. Random, CNDNUM = 0.1/EPS */
/* *3. First row and column zero 8. Scaled near underflow */
/* *4. Last row and column zero 9. Scaled near overflow */
/* *5. Middle row and column zero */
/* (* - tests error exits from SPFTRF, no test ratios are computed) */
/* A solution XACT of size N-by-NRHS is created and the associated right */
/* hand side B as well. Then SPFTRF is called to compute L (or U), the */
/* Cholesky factor of A. Then L (or U) is used to solve the linear system */
/* of equations AX = B. This gives X. Then L (or U) is used to compute the */
/* inverse of A, AINV. The following four tests are then performed: */
/* (1) norm( L*L' - A ) / ( N * norm(A) * EPS ) or */
/* norm( U'*U - A ) / ( N * norm(A) * EPS ), */
/* (2) norm(B - A*X) / ( norm(A) * norm(X) * EPS ), */
/* (3) norm( I - A*AINV ) / ( N * norm(A) * norm(AINV) * EPS ), */
/* (4) ( norm(X-XACT) * RCOND ) / ( norm(XACT) * EPS ), */
/* where EPS is the machine precision, RCOND the condition number of A, and */
/* norm( . ) the 1-norm for (1,2,3) and the inf-norm for (4). */
/* Errors occur when INFO parameter is not as expected. Failures occur when */
/* a test ratios is greater than THRES. */
/* Arguments */
/* ========= */
/* NOUT (input) INTEGER */
/* The unit number for output. */
/* NN (input) INTEGER */
/* The number of values of N contained in the vector NVAL. */
/* NVAL (input) INTEGER array, dimension (NN) */
/* The values of the matrix dimension N. */
/* NNS (input) INTEGER */
/* The number of values of NRHS contained in the vector NSVAL. */
/* NSVAL (input) INTEGER array, dimension (NNS) */
/* The values of the number of right-hand sides NRHS. */
/* NNT (input) INTEGER */
/* The number of values of MATRIX TYPE contained in the vector NTVAL. */
/* NTVAL (input) INTEGER array, dimension (NNT) */
/* The values of matrix type (between 0 and 9 for PO/PP/PF matrices). */
/* THRESH (input) REAL */
/* The threshold value for the test ratios. A result is */
/* included in the output file if RESULT >= THRESH. To have */
/* every test ratio printed, use THRESH = 0. */
/* A (workspace) REAL array, dimension (NMAX*NMAX) */
/* ASAV (workspace) REAL array, dimension (NMAX*NMAX) */
/* AFAC (workspace) REAL array, dimension (NMAX*NMAX) */
/* AINV (workspace) REAL array, dimension (NMAX*NMAX) */
/* B (workspace) REAL array, dimension (NMAX*MAXRHS) */
/* BSAV (workspace) REAL array, dimension (NMAX*MAXRHS) */
/* XACT (workspace) REAL array, dimension (NMAX*MAXRHS) */
/* X (workspace) REAL array, dimension (NMAX*MAXRHS) */
/* ARF (workspace) REAL array, dimension ((NMAX*(NMAX+1))/2) */
/* ARFINV (workspace) REAL array, dimension ((NMAX*(NMAX+1))/2) */
/* S_WORK_SLATMS (workspace) REAL array, dimension ( 3*NMAX ) */
/* S_WORK_SPOT01 (workspace) REAL array, dimension ( NMAX ) */
/* S_TEMP_SPOT02 (workspace) REAL array, dimension ( NMAX*MAXRHS ) */
/* S_TEMP_SPOT03 (workspace) REAL array, dimension ( NMAX*NMAX ) */
/* S_WORK_SLATMS (workspace) REAL array, dimension ( NMAX ) */
/* S_WORK_SLANSY (workspace) REAL array, dimension ( NMAX ) */
/* S_WORK_SPOT02 (workspace) REAL array, dimension ( NMAX ) */
/* S_WORK_SPOT03 (workspace) REAL array, dimension ( NMAX ) */
/* ===================================================================== */
/* .. Parameters .. */
/* .. */
/* .. Local Scalars .. */
/* .. */
/* .. Local Arrays .. */
/* .. */
/* .. External Functions .. */
/* .. */
/* .. External Subroutines .. */
/* .. */
/* .. Scalars in Common .. */
/* .. */
/* .. Common blocks .. */
/* .. */
/* .. Data statements .. */
/* Parameter adjustments */
--nval;
--nsval;
--ntval;
--a;
--asav;
--afac;
--ainv;
--b;
--bsav;
--xact;
--x;
--arf;
--arfinv;
--s_work_slatms__;
--s_work_spot01__;
--s_temp_spot02__;
--s_temp_spot03__;
--s_work_slansy__;
--s_work_spot02__;
--s_work_spot03__;
/* Function Body */
/* .. */
/* .. Executable Statements .. */
/* Initialize constants and the random number seed. */
nrun = 0;
nfail = 0;
nerrs = 0;
for (i__ = 1; i__ <= 4; ++i__) {
iseed[i__ - 1] = iseedy[i__ - 1];
/* L10: */
}
i__1 = *nn;
for (iin = 1; iin <= i__1; ++iin) {
n = nval[iin];
lda = max(n,1);
ldb = max(n,1);
i__2 = *nns;
for (iis = 1; iis <= i__2; ++iis) {
nrhs = nsval[iis];
i__3 = *nnt;
for (iit = 1; iit <= i__3; ++iit) {
imat = ntval[iit];
/* If N.EQ.0, only consider the first type */
if (n == 0 && iit > 1) {
goto L120;
}
/* Skip types 3, 4, or 5 if the matrix size is too small. */
if (imat == 4 && n <= 1) {
goto L120;
}
if (imat == 5 && n <= 2) {
goto L120;
}
/* Do first for UPLO = 'U', then for UPLO = 'L' */
for (iuplo = 1; iuplo <= 2; ++iuplo) {
*(unsigned char *)uplo = *(unsigned char *)&uplos[iuplo -
1];
/* Do first for CFORM = 'N', then for CFORM = 'C' */
for (iform = 1; iform <= 2; ++iform) {
*(unsigned char *)cform = *(unsigned char *)&forms[
iform - 1];
/* Set up parameters with SLATB4 and generate a test */
/* matrix with SLATMS. */
slatb4_("SPO", &imat, &n, &n, ctype, &kl, &ku, &anorm,
&mode, &cndnum, dist);
s_copy(srnamc_1.srnamt, "SLATMS", (ftnlen)32, (ftnlen)
6);
slatms_(&n, &n, dist, iseed, ctype, &s_work_slatms__[
1], &mode, &cndnum, &anorm, &kl, &ku, uplo, &
a[1], &lda, &s_work_slatms__[1], &info);
/* Check error code from SLATMS. */
if (info != 0) {
alaerh_("SPF", "SLATMS", &info, &c__0, uplo, &n, &
n, &c_n1, &c_n1, &c_n1, &iit, &nfail, &
nerrs, nout);
goto L100;
}
/* For types 3-5, zero one row and column of the matrix to */
/* test that INFO is returned correctly. */
zerot = imat >= 3 && imat <= 5;
if (zerot) {
if (iit == 3) {
izero = 1;
} else if (iit == 4) {
izero = n;
} else {
izero = n / 2 + 1;
}
ioff = (izero - 1) * lda;
/* Set row and column IZERO of A to 0. */
if (iuplo == 1) {
i__4 = izero - 1;
for (i__ = 1; i__ <= i__4; ++i__) {
a[ioff + i__] = 0.f;
/* L20: */
}
ioff += izero;
i__4 = n;
for (i__ = izero; i__ <= i__4; ++i__) {
a[ioff] = 0.f;
ioff += lda;
/* L30: */
}
} else {
ioff = izero;
i__4 = izero - 1;
for (i__ = 1; i__ <= i__4; ++i__) {
a[ioff] = 0.f;
ioff += lda;
/* L40: */
}
ioff -= izero;
i__4 = n;
for (i__ = izero; i__ <= i__4; ++i__) {
a[ioff + i__] = 0.f;
/* L50: */
}
}
} else {
izero = 0;
}
/* Save a copy of the matrix A in ASAV. */
slacpy_(uplo, &n, &n, &a[1], &lda, &asav[1], &lda);
/* Compute the condition number of A (RCONDC). */
if (zerot) {
rcondc = 0.f;
} else {
/* Compute the 1-norm of A. */
anorm = slansy_("1", uplo, &n, &a[1], &lda, &
s_work_slansy__[1]);
/* Factor the matrix A. */
spotrf_(uplo, &n, &a[1], &lda, &info);
/* Form the inverse of A. */
spotri_(uplo, &n, &a[1], &lda, &info);
/* Compute the 1-norm condition number of A. */
ainvnm = slansy_("1", uplo, &n, &a[1], &lda, &
s_work_slansy__[1]);
rcondc = 1.f / anorm / ainvnm;
/* Restore the matrix A. */
slacpy_(uplo, &n, &n, &asav[1], &lda, &a[1], &lda);
}
/* Form an exact solution and set the right hand side. */
s_copy(srnamc_1.srnamt, "SLARHS", (ftnlen)32, (ftnlen)
6);
slarhs_("SPO", "N", uplo, " ", &n, &n, &kl, &ku, &
nrhs, &a[1], &lda, &xact[1], &lda, &b[1], &
lda, iseed, &info);
slacpy_("Full", &n, &nrhs, &b[1], &lda, &bsav[1], &
lda);
/* Compute the L*L' or U'*U factorization of the */
/* matrix and solve the system. */
slacpy_(uplo, &n, &n, &a[1], &lda, &afac[1], &lda);
slacpy_("Full", &n, &nrhs, &b[1], &ldb, &x[1], &ldb);
s_copy(srnamc_1.srnamt, "STRTTF", (ftnlen)32, (ftnlen)
6);
strttf_(cform, uplo, &n, &afac[1], &lda, &arf[1], &
info);
s_copy(srnamc_1.srnamt, "SPFTRF", (ftnlen)32, (ftnlen)
6);
spftrf_(cform, uplo, &n, &arf[1], &info);
/* Check error code from SPFTRF. */
if (info != izero) {
/* LANGOU: there is a small hick here: IZERO should */
/* always be INFO however if INFO is ZERO, ALAERH does not */
/* complain. */
alaerh_("SPF", "SPFSV ", &info, &izero, uplo, &n,
&n, &c_n1, &c_n1, &nrhs, &iit, &nfail, &
nerrs, nout);
goto L100;
}
/* Skip the tests if INFO is not 0. */
if (info != 0) {
goto L100;
}
s_copy(srnamc_1.srnamt, "SPFTRS", (ftnlen)32, (ftnlen)
6);
spftrs_(cform, uplo, &n, &nrhs, &arf[1], &x[1], &ldb,
&info);
s_copy(srnamc_1.srnamt, "STFTTR", (ftnlen)32, (ftnlen)
6);
stfttr_(cform, uplo, &n, &arf[1], &afac[1], &lda, &
info);
/* Reconstruct matrix from factors and compute */
/* residual. */
slacpy_(uplo, &n, &n, &afac[1], &lda, &asav[1], &lda);
spot01_(uplo, &n, &a[1], &lda, &afac[1], &lda, &
s_work_spot01__[1], result);
slacpy_(uplo, &n, &n, &asav[1], &lda, &afac[1], &lda);
/* Form the inverse and compute the residual. */
if (n % 2 == 0) {
i__4 = n + 1;
i__5 = n / 2;
i__6 = n + 1;
i__7 = n + 1;
slacpy_("A", &i__4, &i__5, &arf[1], &i__6, &
arfinv[1], &i__7);
} else {
i__4 = (n + 1) / 2;
slacpy_("A", &n, &i__4, &arf[1], &n, &arfinv[1], &
n);
}
s_copy(srnamc_1.srnamt, "SPFTRI", (ftnlen)32, (ftnlen)
6);
spftri_(cform, uplo, &n, &arfinv[1], &info);
s_copy(srnamc_1.srnamt, "STFTTR", (ftnlen)32, (ftnlen)
6);
stfttr_(cform, uplo, &n, &arfinv[1], &ainv[1], &lda, &
info);
/* Check error code from SPFTRI. */
if (info != 0) {
alaerh_("SPO", "SPFTRI", &info, &c__0, uplo, &n, &
n, &c_n1, &c_n1, &c_n1, &imat, &nfail, &
nerrs, nout);
}
spot03_(uplo, &n, &a[1], &lda, &ainv[1], &lda, &
s_temp_spot03__[1], &lda, &s_work_spot03__[1],
&rcondc, &result[1]);
/* Compute residual of the computed solution. */
slacpy_("Full", &n, &nrhs, &b[1], &lda, &
s_temp_spot02__[1], &lda);
spot02_(uplo, &n, &nrhs, &a[1], &lda, &x[1], &lda, &
s_temp_spot02__[1], &lda, &s_work_spot02__[1],
&result[2]);
/* Check solution from generated exact solution. */
sget04_(&n, &nrhs, &x[1], &lda, &xact[1], &lda, &
rcondc, &result[3]);
nt = 4;
/* Print information about the tests that did not */
/* pass the threshold. */
i__4 = nt;
for (k = 1; k <= i__4; ++k) {
if (result[k - 1] >= *thresh) {
if (nfail == 0 && nerrs == 0) {
aladhd_(nout, "SPF");
}
io___37.ciunit = *nout;
s_wsfe(&io___37);
do_fio(&c__1, "SPFSV ", (ftnlen)6);
do_fio(&c__1, uplo, (ftnlen)1);
do_fio(&c__1, (char *)&n, (ftnlen)sizeof(
integer));
do_fio(&c__1, (char *)&iit, (ftnlen)sizeof(
integer));
do_fio(&c__1, (char *)&k, (ftnlen)sizeof(
integer));
do_fio(&c__1, (char *)&result[k - 1], (ftnlen)
sizeof(real));
e_wsfe();
++nfail;
}
/* L60: */
}
nrun += nt;
L100:
;
}
/* L110: */
}
L120:
;
}
/* L980: */
}
/* L130: */
}
/* Print a summary of the results. */
alasvm_("SPF", nout, &nfail, &nrun, &nerrs);
return 0;
/* End of SDRVRFP */
} /* sdrvrfp_ */
| 30.202401 | 125 | 0.520218 | [
"object",
"vector"
] |
ed0ad73cdc0d3eef9e5b19e65809d2e4e50fdc2b | 1,428 | h | C | Samples/Physics/GelatinBlob/GelatinBlobWindow.h | vehsakul/gtl | 498bb20947e9ff21c08dd5a884ac3dc6f8313bb9 | [
"BSL-1.0"
] | null | null | null | Samples/Physics/GelatinBlob/GelatinBlobWindow.h | vehsakul/gtl | 498bb20947e9ff21c08dd5a884ac3dc6f8313bb9 | [
"BSL-1.0"
] | null | null | null | Samples/Physics/GelatinBlob/GelatinBlobWindow.h | vehsakul/gtl | 498bb20947e9ff21c08dd5a884ac3dc6f8313bb9 | [
"BSL-1.0"
] | null | null | null | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2016
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// File Version: 3.1.1 (2016/07/10)
#pragma once
#include <GTEngine.h>
#include "PhysicsModule.h"
using namespace gte;
//#define GELATIN_BLOB_SINGLE_STEP
class GelatinBlobWindow : public Window3
{
public:
GelatinBlobWindow(Parameters& parameters);
virtual void OnIdle() override;
virtual bool OnCharPress(unsigned char key, int x, int y) override;
private:
bool SetEnvironment();
void CreateScene();
void CreateIcosahedron();
void CreateSprings();
void CreateSegments();
void PhysicsTick();
void GraphicsTick();
// The vertex layout for the icosahedron.
struct Vertex
{
Vector3<float> position;
Vector2<float> tcoord;
};
// The scene graph.
std::shared_ptr<BlendState> mBlendState;
std::shared_ptr<DepthStencilState> mDepthReadNoWriteState;
std::shared_ptr<RasterizerState> mNoCullSolidState;
std::shared_ptr<RasterizerState> mNoCullWireState;
std::shared_ptr<Node> mScene, mSegmentRoot;
std::shared_ptr<Visual> mIcosahedron;
std::vector<std::shared_ptr<Visual>> mSegments;
// The physics system.
std::unique_ptr<PhysicsModule> mModule;
Timer mMotionTimer;
};
| 26.943396 | 71 | 0.715686 | [
"vector"
] |
ed0e3990f06b827b5504bd7c6de77294164d52da | 5,918 | h | C | drm/include/tencentcloud/drm/v20181115/model/CreateLicenseRequest.h | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | drm/include/tencentcloud/drm/v20181115/model/CreateLicenseRequest.h | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | drm/include/tencentcloud/drm/v20181115/model/CreateLicenseRequest.h | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 TENCENTCLOUD_DRM_V20181115_MODEL_CREATELICENSEREQUEST_H_
#define TENCENTCLOUD_DRM_V20181115_MODEL_CREATELICENSEREQUEST_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/AbstractModel.h>
#include <tencentcloud/drm/v20181115/model/PlaybackPolicy.h>
namespace TencentCloud
{
namespace Drm
{
namespace V20181115
{
namespace Model
{
/**
* CreateLicense请求参数结构体
*/
class CreateLicenseRequest : public AbstractModel
{
public:
CreateLicenseRequest();
~CreateLicenseRequest() = default;
std::string ToJsonString() const;
/**
* 获取DRM方案类型,接口取值:WIDEVINE,FAIRPLAY。
* @return DrmType DRM方案类型,接口取值:WIDEVINE,FAIRPLAY。
*/
std::string GetDrmType() const;
/**
* 设置DRM方案类型,接口取值:WIDEVINE,FAIRPLAY。
* @param DrmType DRM方案类型,接口取值:WIDEVINE,FAIRPLAY。
*/
void SetDrmType(const std::string& _drmType);
/**
* 判断参数 DrmType 是否已赋值
* @return DrmType 是否已赋值
*/
bool DrmTypeHasBeenSet() const;
/**
* 获取Base64编码的终端设备License Request数据。
* @return LicenseRequest Base64编码的终端设备License Request数据。
*/
std::string GetLicenseRequest() const;
/**
* 设置Base64编码的终端设备License Request数据。
* @param LicenseRequest Base64编码的终端设备License Request数据。
*/
void SetLicenseRequest(const std::string& _licenseRequest);
/**
* 判断参数 LicenseRequest 是否已赋值
* @return LicenseRequest 是否已赋值
*/
bool LicenseRequestHasBeenSet() const;
/**
* 获取内容类型,接口取值:VodVideo,LiveVideo。
* @return ContentType 内容类型,接口取值:VodVideo,LiveVideo。
*/
std::string GetContentType() const;
/**
* 设置内容类型,接口取值:VodVideo,LiveVideo。
* @param ContentType 内容类型,接口取值:VodVideo,LiveVideo。
*/
void SetContentType(const std::string& _contentType);
/**
* 判断参数 ContentType 是否已赋值
* @return ContentType 是否已赋值
*/
bool ContentTypeHasBeenSet() const;
/**
* 获取授权播放的Track列表。
该值为空时,默认授权所有track播放。
* @return Tracks 授权播放的Track列表。
该值为空时,默认授权所有track播放。
*/
std::vector<std::string> GetTracks() const;
/**
* 设置授权播放的Track列表。
该值为空时,默认授权所有track播放。
* @param Tracks 授权播放的Track列表。
该值为空时,默认授权所有track播放。
*/
void SetTracks(const std::vector<std::string>& _tracks);
/**
* 判断参数 Tracks 是否已赋值
* @return Tracks 是否已赋值
*/
bool TracksHasBeenSet() const;
/**
* 获取播放策略参数。
* @return PlaybackPolicy 播放策略参数。
*/
PlaybackPolicy GetPlaybackPolicy() const;
/**
* 设置播放策略参数。
* @param PlaybackPolicy 播放策略参数。
*/
void SetPlaybackPolicy(const PlaybackPolicy& _playbackPolicy);
/**
* 判断参数 PlaybackPolicy 是否已赋值
* @return PlaybackPolicy 是否已赋值
*/
bool PlaybackPolicyHasBeenSet() const;
private:
/**
* DRM方案类型,接口取值:WIDEVINE,FAIRPLAY。
*/
std::string m_drmType;
bool m_drmTypeHasBeenSet;
/**
* Base64编码的终端设备License Request数据。
*/
std::string m_licenseRequest;
bool m_licenseRequestHasBeenSet;
/**
* 内容类型,接口取值:VodVideo,LiveVideo。
*/
std::string m_contentType;
bool m_contentTypeHasBeenSet;
/**
* 授权播放的Track列表。
该值为空时,默认授权所有track播放。
*/
std::vector<std::string> m_tracks;
bool m_tracksHasBeenSet;
/**
* 播放策略参数。
*/
PlaybackPolicy m_playbackPolicy;
bool m_playbackPolicyHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_DRM_V20181115_MODEL_CREATELICENSEREQUEST_H_
| 32.877778 | 83 | 0.464684 | [
"vector",
"model"
] |
ed1891a271b183c0852428ea9ab98aff3df7bd7e | 1,940 | h | C | src/ArrowFunctions.h | Bears-R-Us/arkouda | 7033e530c1acc9ce2c8e05ecf0454928ce1011f4 | [
"MIT"
] | 51 | 2021-05-15T01:35:20.000Z | 2022-03-31T00:41:17.000Z | src/ArrowFunctions.h | Bears-R-Us/arkouda | 7033e530c1acc9ce2c8e05ecf0454928ce1011f4 | [
"MIT"
] | 321 | 2021-05-12T16:02:45.000Z | 2022-03-31T17:10:27.000Z | src/ArrowFunctions.h | bmcdonald3/arkouda | 5b7c2221d470f6e986fa9dad7fd9e7234fa9deef | [
"MIT"
] | 13 | 2021-06-03T13:44:21.000Z | 2022-03-31T17:38:36.000Z | #include <stdint.h>
// Wrap functions in C extern if compiling C++ object file
#ifdef __cplusplus
#include <iostream>
#include <arrow/api.h>
#include <arrow/io/api.h>
#include <parquet/arrow/reader.h>
#include <parquet/arrow/writer.h>
#include <parquet/column_reader.h>
extern "C" {
#endif
#define ARROWINT64 0
#define ARROWINT32 1
#define ARROWTIMESTAMP ARROWINT64
#define ARROWUNDEFINED -1
#define ARROWERROR -1
// Each C++ function contains the actual implementation of the
// functionality, and there is a corresponding C function that
// Chapel can call into through C interoperability, since there
// is no C++ interoperability supported in Chapel today.
int64_t c_getNumRows(const char*, char** errMsg);
int64_t cpp_getNumRows(const char*, char** errMsg);
int c_readColumnByName(const char* filename, void* chpl_arr,
const char* colname, int64_t numElems, int64_t batchSize,
char** errMsg);
int cpp_readColumnByName(const char* filename, void* chpl_arr,
const char* colname, int64_t numElems, int64_t batchSize,
char** errMsg);
int c_getType(const char* filename, const char* colname, char** errMsg);
int cpp_getType(const char* filename, const char* colname, char** errMsg);
int cpp_writeColumnToParquet(const char* filename, void* chpl_arr,
int64_t colnum, const char* dsetname, int64_t numelems,
int64_t rowGroupSize, char** errMsg);
int c_writeColumnToParquet(const char* filename, void* chpl_arr,
int64_t colnum, const char* dsetname, int64_t numelems,
int64_t rowGroupSize, char** errMsg);
const char* c_getVersionInfo(void);
const char* cpp_getVersionInfo(void);
void c_free_string(void* ptr);
void cpp_free_string(void* ptr);
#ifdef __cplusplus
}
#endif
| 36.603774 | 86 | 0.67268 | [
"object"
] |
ed2193a6463f57e1dad1e36b56fcd45ffd0a14a8 | 14,661 | h | C | AprilTagTrackers/Localization.h | funnbot/April-Tag-VR-FullBody-Tracker | 8720cab49f5241446d9383134fd9507b70c431c0 | [
"MIT"
] | null | null | null | AprilTagTrackers/Localization.h | funnbot/April-Tag-VR-FullBody-Tracker | 8720cab49f5241446d9383134fd9507b70c431c0 | [
"MIT"
] | null | null | null | AprilTagTrackers/Localization.h | funnbot/April-Tag-VR-FullBody-Tracker | 8720cab49f5241446d9383134fd9507b70c431c0 | [
"MIT"
] | null | null | null | #pragma once
#include "Debug.h"
#include "GUI/U8String.h"
#include "Serializable.h"
#include <algorithm>
#include <filesystem>
#include <iterator>
#include <string_view>
#include <vector>
// temporary alias, undefined at end of file,
#define T(a_key) REFLECTABLE_FIELD(U8String, a_key)
class Localization : public FS::Serializable<Localization>
{
public:
static inline const FS::Path localesDir = std::filesystem::absolute("locales");
// Keep synced
static constexpr std::array<std::string_view, 2> LANG_CODE_MAP{
"en",
"zh-CN"};
static constexpr std::array<U8StringView, LANG_CODE_MAP.size()> LANG_NAME_MAP{
"English",
"Chinese (PRC)"};
static FS::Path GetLangPath(const std::string& langCode)
{
return std::filesystem::absolute(localesDir) / (langCode + ".yaml");
}
Localization()
: FS::Serializable<Localization>()
{
}
bool LoadLang(const std::string& langCode)
{
// English is loaded by default
if (langCode == "en") return true;
SetPath(GetLangPath(langCode));
return Load();
}
// TODO: Make the github workflow create these "to be translated" localization files.
// Could create an automatic pr for them?
/// Save the updated localization, the default english will be stored in the new keys.
/// Some random language will be loaded after this is called, but its a developer function,
/// so don't really care, call LoadLang() afterwards to fix.
void UpdateAllLangs()
{
for (const auto& langCode : LANG_CODE_MAP)
{
if (langCode == "en") continue;
SetPath(GetLangPath(std::string(langCode)));
// Load existing translations if they exist
Load();
// Create or overwrite the language file, with new untranslated keys.
Save();
}
}
struct Word
{
REFLECTABLE_BEGIN;
T(Yes) = "Yes";
T(No) = "No";
T(On) = "On";
T(Off) = "Off";
T(Error) = "Error";
T(Warning) = "Warning";
T(Info) = "Info";
T(Connected) = "Connected";
T(Disconnected) = "Disconnected";
REFLECTABLE_END;
};
struct StatusBar
{
REFLECTABLE_BEGIN;
T(CAMERA) = "Camera: ";
T(DRIVER) = "SteamVR Driver: ";
T(TRACKER) = "Tracker Running: ";
REFLECTABLE_END;
};
struct Calib
{
REFLECTABLE_BEGIN;
T(X) = "X (cm):";
T(Y) = "Y (cm):";
T(Z) = "Z (cm):";
T(PITCH) = "Pitch (°):";
T(YAW) = "Yaw (°):";
T(ROLL) = "Roll (°):";
T(SCALE) = "Scale (%):";
REFLECTABLE_END;
};
// !! Due to how reflection works, can't define a class within another reflection list,
// !! so define subclasses above this line, though using them as fields is fine.
REFLECTABLE_BEGIN;
FS_COMMENT("Put all strings in \"double quotes\".");
// TODO: Group names in structs, instead of long ids (stored in sub-objects in yaml)
T(APP_TITLE) = "Juices VR Marker Tracking";
REFLECTABLE_FIELD(Word, word);
REFLECTABLE_FIELD(StatusBar, status);
REFLECTABLE_FIELD(Calib, calib);
T(WINDOW_TITLE) = "Set title bar [requires app restart]";
T(WINDOW_TITLE_TOOLTIP) = "Set a custom title name for the camera\n *requires restarting*";
T(TAB_CAMERA) = "Camera";
T(TAB_PARAMS) = "Params";
T(TAB_LICENSE) = "License";
T(CAMERA_START_CAMERA) = "1. Start/Stop camera";
T(CAMERA_CALIBRATE_CAMERA) = "2. Calibrate camera";
T(CAMERA_CALIBRATE_TRACKERS) = "3. Calibrate trackers";
T(CAMERA_START_STEAMVR) = "4. Start up SteamVR!";
T(CAMERA_CONNECT) = "5. Connect to SteamVR";
T(CAMERA_START_DETECTION) = "6. Start/Stop";
T(CAMERA_PREVIEW_CAMERA) = "Preview camera";
T(CAMERA_PREVIEW_CALIBRATION) = "Preview calibration";
T(CAMERA_CALIBRATION_MODE) = "Calibration mode";
T(CAMERA_MULTICAM_CALIB) = "Refine calibration using second camera";
T(CAMERA_LOCK_HEIGHT) = "Lock camera height";
T(CAMERA_CALIBRATION_INSTRUCTION) =
R"(Disable SteamVR home to see the camera.
Use your left trigger to grab the camera and move it into position, then use grip to grab trackers and move those into position.
Uncheck Calibration mode when done!)";
T(CAMERA_DISABLE_OUT) = "Disable out window";
T(CAMERA_DISABLE_OPENVR_API) = "Disable OpenVR API use";
T(PARAMS_CAMERA_TOOLTIP_API_1) = "0: No preference\n\nCamera backends:";
T(PARAMS_CAMERA_TOOLTIP_API_2) = "Stream backends:";
T(PARAMS_LANGUAGE) = "Language";
T(PARAMS_CAMERA) = "CAMERA PARAMETERS";
T(PARAMS_CAMERA_NAME_ID) = "Ip or ID of camera";
T(PARAMS_CAMERA_TOOLTIP_ID) = "Will be a number 0-10 for USB cameras and\nhttp://<ip here>:8080/video for IP webcam)";
T(PARAMS_CAMERA_NAME_API) = "Camera API preference";
T(PARAMS_CAMERA_NAME_ROT_CLOCKWISE) = "Rotate camera clockwise";
T(PARAMS_CAMERA_TOOLTIP_ROT_CLOCKWISE) = "Rotate the camera 90°. Use both to rotate image 180°";
T(PARAMS_CAMERA_NAME_MIRROR) = "Mirror camera";
T(PARAMS_CAMERA_TOOLTIP_MIRROR) = "Mirror the camera horizontaly";
T(PARAMS_CAMERA_NAME_WIDTH) = "Camera width in pixels";
T(PARAMS_CAMERA_TOOLTIP_WIDTH) = "Width and height should be fine on 0, but change it to the camera resolution in case camera doesn't work correctly.";
T(PARAMS_CAMERA_NAME_HEIGHT) = "Camera height in pixels";
T(PARAMS_CAMERA_TOOLTIP_HEIGHT) = "Width and height should be fine on 0, but change it to the camera resolution in case camera doesn't work correctly.";
T(PARAMS_CAMERA_NAME_FPS) = "Camera FPS";
T(PARAMS_CAMERA_TOOLTIP_FPS) = "Set the fps of the camera";
T(PARAMS_CAMERA_NAME_SETTINGS) = "Open camera settings";
T(PARAMS_CAMERA_TOOLTIP_SETTINGS) = "Should open settings of your camera. Only works with Camera API preference DirectShow (700)";
T(PARAMS_CAMERA_NAME_3_OPTIONS) = "Enable last 3 camera options";
T(PARAMS_CAMERA_TOOLTIP_3_OPTIONS) = "Experimental. Checking this will enable the bottom three options, which will otherwise not work. Will also try to disable autofocus.";
T(PARAMS_CAMERA_NAME_AUTOEXP) = "Camera autoexposure";
T(PARAMS_CAMERA_TOOLTIP_AUTOEXP) = "Experimental. Will try to set camera autoexposure. Usualy 1 for enable and 0 for disable, but can be something dumb as 0.75 and 0.25,";
T(PARAMS_CAMERA_NAME_EXP) = "Camera exposure";
T(PARAMS_CAMERA_TOOLTIP_EXP) = "Experimental. Will try to set camera expousre. Can be on a scale of 0-255, or in exponentials of 2 ( -8 for 4ms exposure)";
T(PARAMS_CAMERA_NAME_GAIN) = "Camera gain";
T(PARAMS_CAMERA_TOOLTIP_GAIN) = "Experimental. Will try to set gain. Probably on a scale of 0-255, but could be diffrent based on the camera.";
T(PARAMS_TRACKER) = "TRACKER PARAMETERS";
T(PARAMS_TRACKER_NAME_NUM_TRACKERS) = "Number of trackers";
T(PARAMS_TRACKER_TOOLTIP_NUM_TRACKERS) = "Set to 3 for full body. 2 will not work in vrchat!";
T(PARAMS_TRACKER_NAME_MARKER_SIZE) = "Size of markers in cm";
T(PARAMS_TRACKER_TOOLTIP_MARKER_SIZE) = "Measure the white square on markers and input it here";
T(PARAMS_TRACKER_NAME_QUAD_DECIMATE) = "Quad decimate";
T(PARAMS_TRACKER_TOOLTIP_QUAD_DECIMATE) = "Can be 1, 1.5, 2, 3, 4. Higher values will increase FPS, but reduce maximum range of detections";
T(PARAMS_TRACKER_NAME_SEARCH_WINDOW) = "Search window";
T(PARAMS_TRACKER_TOOLTIP_SEARCH_WINDOW) = "Size of the search window. Smaller window will speed up detection, but having it too small will cause detection to fail if tracker moves too far in one frame.";
T(PARAMS_TRACKER_NAME_MARKER_LIBRARY) = "Marker library";
T(PARAMS_TRACKER_TOOLTIP_MARKER_LIBRARY) = "Marker library to use. Leave at ApriltagStandard unless you know what you are doing.";
T(PARAMS_TRACKER_NAME_USE_CENTERS) = "Use centers of trackers";
T(PARAMS_TRACKER_TOOLTIP_USE_CENTERS) = "Experimental. Instead of having position of tracker detected at the main marker, it will be the center of all markers in the tracker.";
T(PARAMS_TRACKER_NAME_IGNORE_0) = "Ignore tracker 0";
T(PARAMS_TRACKER_TOOLTIP_IGNORE_0) = "If you want to replace the hip tracker with a vive tracker/owotrack, check this option. Keep number of trackers on 3.";
T(PARAMS_SMOOTHING) = "SMOOTHING PARAMETERS";
T(PARAMS_SMOOTHING_NAME_WINDOW) = "Smoothing time window";
T(PARAMS_SMOOTHING_TOOLTIP_WINDOW) = "Values in this time window will be used for interpolation. The higher it is, the less shaking there will be, but it will increase delay. 0.2-0.5 are usualy good values";
T(PARAMS_SMOOTHING_NAME_ADDITIONAL) = "Additional smoothing";
T(PARAMS_SMOOTHING_TOOLTIP_ADDITIONAL) = "Extra smoothing applied to tracker position. Should mimic the old style of smoothing in previous versions. 0 for no smoothing, 1 for very slow movement.";
T(PARAMS_SMOOTHING_NAME_DEPTH) = "Depth smoothing";
T(PARAMS_SMOOTHING_TOOLTIP_DEPTH) = "Experimental. Additional smoothing applied to the depth estimation, as it has higher error. Cam help remove shaking with multiple cameras.";
T(PARAMS_SMOOTHING_NAME_CAM_LATENCY) = "Camera latency";
T(PARAMS_SMOOTHING_TOOLTIP_CAM_LATENCY) = "Represents camera latency in seconds. Should counter any delay when using an IP camera. Usualy lower than 0.1.";
T(PARAMS_HOVER_HELP) = "Hover over text for help!";
T(PARAMS_SAVE) = "Save";
T(PARAMS_NOTE_LOW_SMOOTHING) = "NOTE: Smoothing time window is extremely low, which may cause problems. \n\nIf you get any problems with tracking, try to increase it.";
T(PARAMS_NOTE_QUAD_NONSTANDARD) = "NOTE: Quad Decimate is not a standard value. \n\nKeep it at 1, 1.5, 2, 3 or 4, or else detection may not work.";
T(PARAMS_NOTE_NO_DSHOW_CAMSETTINGS) = "NOTE: Camera settings parameter is on, but camera API preference is not 700 \n\nOpening camera parameters only work when camera API is set to DirectShow, or 700.";
T(PARAMS_NOTE_LATENCY_GREATER_SMOOTHING) = "NOTE: Camera latency should never be higher than smoothing time window or tracking isnt going to work. \n\nYou probably dont want it any higher than 0.1, and smoothing window probably shouldnt be under 0.2 unless you use high speed cameras.";
T(PARAMS_NOTE_HIGH_SMOOTHING) = "NOTE: Smoothing time window is over 1 second, which will cause very slow movement! \n\nYou probably want to update it to something like 0.5.";
T(PARAMS_NOTE_2TRACKERS_IGNORE0) = "Number of trackers is 2 and ignore tracker 0 is on. This will result in only 1 tracker spawning in SteamVR. \nIf you wish to use both feet trackers, keep number of trackers at 3.";
T(PARAMS_NOTE_LANGUAGECHANGE) = "Language has been changed! Please restart application to apply.";
T(PARAMS_SAVED_MSG) = "Parameters saved!";
T(PARAMS_WRONG_VALUES) = "Please enter appropriate values. Parameters were not saved.";
T(TRACKER_CAMERA_START_ERROR) =
R"(Could not start camera.Make sure you entered the correct ID or IP of your camera in the params.
"For USB cameras, it will be a number, usually 0,1,2... try a few until it works.
"For IP webcam, the address will be in the format http://<ip here>:8080/video)";
T(TRACKER_CAMERA_ERROR) = "Camera error";
T(TRACKER_CAMERA_PREVIEW) = "Preview";
T(TRACKER_CAMERA_NOTRUNNING) = "Camera not running";
T(TRACKER_CAMERA_CALIBRATION_INSTRUCTIONS) =
R"(Camera calibration started!
Place the printed Charuco calibration board on a flat surface, or display it on a (non-curved) monitor. The camera will take a picture every second - take pictures of the board from as many different angles and distances as you can.
Make sure that the board is seen nicely and isn't blurred. Move the camera around slowly.
Purple dots = great
Green dots = okay
Yellow dots = bad
The grid should be fairly flat, fairly stable (can still shake a couple of pixels) and take over the whole image.
The dots should be spread across the whole image
Press OK to save calibration when done.)";
T(TRACKER_CAMERA_CALIBRATION_COMPLETE) = "Calibration complete.";
T(TRACKER_CAMERA_CALIBRATION_NOTDONE) = "Calibration has not been completed as too few images have been taken.";
T(TRACKER_CAMERA_NOTCALIBRATED) = "Camera not calibrated";
T(TRACKER_TRACKER_CALIBRATION_INSTRUCTIONS) =
R"(Tracker calibration started!
Before calibrating, set the number of trackers and marker size parameters (measure the white square). Make sure the trackers are completely rigid and cannot bend,
neither the markers or at the connections between markers - use images on github for reference. Wear your trackers, then calibrate them by moving them to the camera closer than 30cm.
Green: This marker is calibrated and can be used to calibrate other markers.
Blue: This marker is not part of any used trackers. You probably have to increase number of trackers in params.
Purple: This marker is too far from the camera to be calibrated. Move it closer than 30cm.
Red: This marker cannot be calibrated as no green markers are seen. Rotate the tracker until a green marker is seen along this one.
Yellow: The marker is being calibrated. Hold it still for a second.
When all the markers on all trackers are shown as green, press OK to finish calibration.)";
T(TRACKER_TRACKER_NOTCALIBRATED) = "Trackers not calibrated";
T(TRACKER_STEAMVR_NOTCONNECTED) = "Not connected to SteamVR";
T(TRACKER_CALIBRATION_SOMETHINGWRONG) = "Something went wrong. Try again.";
T(CONNECT_SOMETHINGWRONG) = "Something went wrong. Try again.";
T(TRACKER_DETECTION_SOMETHINGWRONG) = "Something went wrong when estimating tracker pose. Try again! \n"
"If the problem persists, try to recalibrate camera and trackers.";
T(CONNECT_ALREADYCONNECTED) = "Already connected. Restart connection?";
T(CONNECT_CLIENT_ERROR) = "Error when connecting to SteamVR as a client! Make sure your HMD is connected. \nError code: ";
T(CONNECT_BINDINGS_ERROR) = "Could not find bindings file att_actions.json.";
T(CONNECT_DRIVER_ERROR) =
R"(Could not connect to SteamVR driver. If error code is 2, make sure SteamVR is running and the apriltagtrackers driver is installed and enabled in settings.
You may also have to run bin/ApriltagTrackers.exe as administrator, if error code is not 2.
Error code: )";
T(CONNECT_DRIVER_MISSMATCH_1) = "Driver version and ATT version do not match! \n\nDriver version: ";
T(CONNECT_DRIVER_MISSMATCH_2) = "\nExpected driver version: ";
REFLECTABLE_END;
};
#undef T
| 52.548387 | 290 | 0.71639 | [
"vector"
] |
ed250a1f2b6aed25b936082e80d33f27a37f1a5b | 1,313 | h | C | Source/Renderer/Mesh.h | pgrabas/MoonGlare | 25807680700697023d04830402af168f624ffb35 | [
"MIT"
] | 1 | 2018-03-18T16:29:16.000Z | 2018-03-18T16:29:16.000Z | Source/Renderer/Mesh.h | pgrabas/MoonGlare | 25807680700697023d04830402af168f624ffb35 | [
"MIT"
] | null | null | null | Source/Renderer/Mesh.h | pgrabas/MoonGlare | 25807680700697023d04830402af168f624ffb35 | [
"MIT"
] | null | null | null | #pragma once
namespace MoonGlare::Renderer {
struct alignas(16) Mesh {
bool valid;
uint8_t __padding[3];
uint16_t elementMode; //TODO: is this needed, is GL_TRIANGLES required? (no?)
uint16_t indexElementType;
uint16_t baseVertex;
uint16_t baseIndex;
uint32_t numIndices;
};
static_assert(sizeof(Mesh) == 16);
static_assert(std::is_pod_v<Mesh>);
struct MeshSource {
std::vector<glm::fvec3> verticles;
std::vector<glm::fvec2> UV0;
std::vector<glm::fvec3> normals;
std::vector<glm::fvec3> tangents;
std::vector<uint32_t> index;
static constexpr uint8_t InvalidBoneIndex = 0xFF;
static glm::u8vec4 InvalidBoneIndexSlot() { return glm::u8vec4(0xFF); };
std::vector<glm::u8vec4> vertexBones;
std::vector<glm::fvec4> vertexBoneWeights;
std::vector<std::string> boneNames;
std::vector<glm::mat4> boneOffsetMatrices;
emath::fvec3 halfBoundingBox;
float boundingRadius;
void UpdateBoundary() {
boundingRadius = 0;
halfBoundingBox = emath::fvec3(0, 0, 0);
for (auto &v : verticles) {
boundingRadius = std::max(boundingRadius, glm::length(v));
for (int j = 0; j < 3; ++j)
halfBoundingBox[j] = std::max(halfBoundingBox[j], abs(v[j]));
}
}
};
}
| 27.354167 | 92 | 0.642041 | [
"mesh",
"vector"
] |
ed2da4ffcdbd65731de57f93bcae258304c158a4 | 2,456 | h | C | MeshView.h | funkey/sg_gui | 33b6b26e428709b6685644aedcebb439fb0e86b4 | [
"MIT"
] | null | null | null | MeshView.h | funkey/sg_gui | 33b6b26e428709b6685644aedcebb439fb0e86b4 | [
"MIT"
] | null | null | null | MeshView.h | funkey/sg_gui | 33b6b26e428709b6685644aedcebb439fb0e86b4 | [
"MIT"
] | null | null | null | #ifndef SG_GUI_MESH_VIEW_H__
#define SG_GUI_MESH_VIEW_H__
#include <scopegraph/Agent.h>
#include <imageprocessing/ExplicitVolume.h>
#include "GuiSignals.h"
#include "SegmentSignals.h"
#include "ViewSignals.h"
#include "KeySignals.h"
#include "RecordableView.h"
#include "Meshes.h"
#include <future>
#include <thread>
namespace sg_gui {
/**
* A marching cubes adaptor that binarizes an explicit volume by reporting 1 for
* a given label and 0 otherwise.
*/
template <typename EV>
class ExplicitVolumeLabelAdaptor {
public:
typedef typename EV::value_type value_type;
ExplicitVolumeLabelAdaptor(const EV& ev, value_type label) :
_ev(ev),
_label(label) {}
const util::box<float,3>& getBoundingBox() const { return _ev.getBoundingBox(); }
float operator()(float x, float y, float z) const {
if (!getBoundingBox().contains(x, y, z))
return 0;
unsigned int dx, dy, dz;
_ev.getDiscreteCoordinates(x, y, z, dx, dy, dz);
return (_ev(dx, dy, dz) == _label);
}
private:
const EV& _ev;
value_type _label;
};
class MeshView :
public sg::Agent<
MeshView,
sg::Accepts<
ShowSegment,
HideSegment,
DrawOpaque,
DrawTranslucent,
QuerySize,
ChangeAlpha,
SetAlphaPlane,
KeyDown
>,
sg::Provides<
ContentChanged
>
>,
public RecordableView {
public:
MeshView(std::shared_ptr<ExplicitVolume<uint64_t>> labels);
void setOffset(util::point<float, 3> offset);
void onSignal(DrawOpaque& signal);
void onSignal(DrawTranslucent& signal);
void onSignal(QuerySize& signal);
void onSignal(ChangeAlpha& signal);
void onSignal(SetAlphaPlane& signal);
void onSignal(ShowSegment& signal);
void onSignal(HideSegment& signal);
void onSignal(KeyDown& signal);
private:
void notifyMeshExtracted(std::shared_ptr<sg_gui::Mesh> mesh, uint64_t label);
void exportMeshes();
void updateRecording();
void setVertexAlpha(const Point3d& p, float r, float g, float b);
std::shared_ptr<ExplicitVolume<uint64_t>> _labels;
std::shared_ptr<Meshes> _meshes;
std::map<uint64_t, std::shared_ptr<sg_gui::Mesh>> _meshCache;
std::vector<std::future<std::shared_ptr<sg_gui::Mesh>>> _highresMeshFutures;
float _minCubeSize;
double _alpha;
util::plane<float, 3> _alphaPlane;
double _alphaFalloff;
bool _haveAlphaPlane;
util::point<float, 3> _offset;
unsigned int _numThreads;
unsigned int _maxNumThreads;
};
} // namespace sg_gui
#endif // SG_GUI_MESH_VIEW_H__
| 19.03876 | 82 | 0.721906 | [
"mesh",
"vector"
] |
ed42a28e49cfafea0db2e872a0fcfe92ce6fc2e8 | 21,251 | c | C | src/lang.c | brodieG/validate | 188872e15e53ce3c353a29d5e475e871a00821ec | [
"PSF-2.0"
] | 65 | 2017-07-10T06:22:57.000Z | 2022-03-10T08:51:46.000Z | src/lang.c | brodieG/vetr | 188872e15e53ce3c353a29d5e475e871a00821ec | [
"PSF-2.0"
] | 92 | 2017-04-26T01:35:13.000Z | 2020-11-26T15:46:02.000Z | src/lang.c | brodieG/validate | 188872e15e53ce3c353a29d5e475e871a00821ec | [
"PSF-2.0"
] | 3 | 2017-07-26T14:36:45.000Z | 2020-05-13T16:07:27.000Z | /*
Copyright (C) 2020 Brodie Gaslam
This file is part of "vetr - Trust, but Verify"
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.
Go to <https://www.r-project.org/Licenses/GPL-2> for a copy of the license.
*/
#include "alike.h"
/*
Initialize return object
*/
/*
Moves pointer on language object to skip any `(` calls since those are
already accounted for in parsing and as such don't add anything.
Returns a list/vector with a pointer to the updated lanaguage object position
and an integer indicating how many parentheses were skipped
*/
SEXP ALIKEC_skip_paren(SEXP lang) {
int i = 0;
SEXP res = PROTECT(allocVector(VECSXP, 2));
if(TYPEOF(lang) == LANGSXP) {
while(
CAR(lang) == ALIKEC_SYM_paren_open && CDR(CDR(lang)) == R_NilValue
) {
lang = CADR(lang);
i++;
if(i < 0) {
// nocov start
error(
"Internal Error: %s; contact maintainer.",
"exceeded language recursion depth when skipping parens"
);
// nocov end
}
} }
SET_VECTOR_ELT(res, 0, lang);
SET_VECTOR_ELT(res, 1, ScalarInteger(i));
UNPROTECT(1);
return(res);
}
// - Anonymize Formula ---------------------------------------------------------
/* Look up symbol in hash table, if already present, return the anonymized
version of the symbol. If not, add to the hash table.
symb the symbol to lookup
hash the hash table
varnum used to generate the anonymized variable name
*/
const char * ALIKEC_symb_abstract(
SEXP symb, pfHashTable * hash, size_t * varnum, struct VALC_settings set
) {
const char * symb_chr = CHAR(PRINTNAME(symb));
// really shouldn't have to do this, but can't be bothered re-defining the
// hash library
const char * symb_abs = pfHashFind(hash, (char *) symb_chr);
if(symb_abs == NULL) {
symb_abs = CSR_smprintf4(
set.nchar_max, "a%s", CSR_len_as_chr(*varnum), "", "", ""
);
pfHashSet(hash, (char *) symb_chr, symb_abs);
(*varnum)++;
}
return symb_abs;
}
/*
Try to find function in env and return function if it exists, R_NilValue
otherwise
@param call the function we will ultimately match
@param env an environment to start the lookup
*/
SEXP ALIKEC_get_fun(SEXP call, SEXP env) {
SEXP fun = CAR(call);
switch(TYPEOF(fun)) {
case CLOSXP:
return fun;
break;
case SYMSXP:
{
// Assuming no GC happens in next couple of steps
SEXP fun_def = ALIKEC_findFun(fun, env);
if(TYPEOF(fun_def) == CLOSXP) return fun_def;
}
break;
}
return R_NilValue;
}
/*
@param match_call a preconstructed call to retrieve the function; needed because
can't figure out a way to create preconstructed call in init without
sub-components getting GCed
*/
SEXP ALIKEC_match_call(
SEXP call, SEXP match_call, SEXP env
) {
SEXP fun = PROTECT(ALIKEC_get_fun(call, env));
if(fun == R_NilValue) {
UNPROTECT(1);
return call;
}
// remember, match_call is pre-defined as: match.call(def, quote(call)), also,
// in theory should never be SHARED since it is a SEXP created in C code only
// for internal use.
if (MAYBE_SHARED(match_call)) PROTECT(match_call = duplicate(match_call));
else PROTECT(R_NilValue);
SETCADR(match_call, fun);
SETCADR(CADDR(match_call), call);
int tmp = 0;
int * err =& tmp;
SEXP res = PROTECT(R_tryEvalSilent(match_call, env, err));
UNPROTECT(3);
if(* err) return call; else return res;
}
/*
Handle language object comparison
Note that we always pass cur_par instead of current so that we can modify the
original call (mostly by using `match.call` on it)
*/
struct ALIKEC_res ALIKEC_lang_obj_compare(
SEXP target, SEXP cur_par, pfHashTable * tar_hash,
pfHashTable * cur_hash, pfHashTable * rev_hash, size_t * tar_varnum,
size_t * cur_varnum, int formula, SEXP match_call, SEXP match_env,
struct VALC_settings set, struct ALIKEC_rec_track rec
) {
SEXP current = CAR(cur_par);
struct ALIKEC_res res = ALIKEC_res_init();
res.dat.rec = rec;
// Skip parens and increment recursion; not we don't track recursion level
// for target
SEXP cur_skip_paren = PROTECT(ALIKEC_skip_paren(current));
SEXP tar_skip_paren = PROTECT(ALIKEC_skip_paren(target));
// Need to reset all variables so we work on the paren less version
current = VECTOR_ELT(cur_skip_paren, 0);
SEXP cur_par_dup = PROTECT(duplicate(cur_par));
SETCAR(cur_par_dup, current);
int i, i_max = asInteger(VECTOR_ELT(cur_skip_paren, 1));
PROTECT(res.wrap); // Dummy PROTECT
for(i = 0; i < i_max; i++) {
res.dat.rec = ALIKEC_rec_inc(res.dat.rec);
}
target = VECTOR_ELT(tar_skip_paren, 0);
SEXPTYPE tsc_type = TYPEOF(target), csc_type = TYPEOF(current);
res.success = 0; // assume fail until shown otherwise
if(target == R_NilValue) {// NULL matches anything
res.success = 1;
} else if(tsc_type == SYMSXP && csc_type == SYMSXP) {
const char * tar_abs = ALIKEC_symb_abstract(
target, tar_hash, tar_varnum, set
);
const char * cur_abs = ALIKEC_symb_abstract(
current, cur_hash, cur_varnum, set
);
// reverse hash to get what symbol should be in case of error
const char * rev_symb = pfHashFind(rev_hash, tar_abs);
const char * csc_text = CHAR(PRINTNAME(current));
if(rev_symb == NULL) {
rev_symb = (char *) csc_text;
pfHashSet(rev_hash, cur_abs, rev_symb);
}
if(strcmp(tar_abs, cur_abs)) {
res.success = 0;
if(*tar_varnum > *cur_varnum) {
res.dat.strings.tar_pre = "not be";
res.dat.strings.target[0] = "`%s`";
res.dat.strings.target[1] = csc_text;
res.dat.strings.current[1] = ""; // gcc-10
} else {
res.dat.strings.target[0] = "`%s`";
res.dat.strings.target[1] = rev_symb;
res.dat.strings.current[0] = "`%s`";
res.dat.strings.current[1] = csc_text;
}
} else res.success = 1;
} else if (tsc_type == LANGSXP && csc_type != LANGSXP) {
res.success = 0;
res.dat.strings.target[0] = "a call to `%s`";
res.dat.strings.target[1] = ALIKEC_deparse_chr(CAR(target), -1, set);
res.dat.strings.current[0] = "\"%s\"";
res.dat.strings.current[1] = type2char(csc_type);
} else if (tsc_type != LANGSXP && csc_type == LANGSXP) {
res.success = 0;
res.dat.strings.target[0] = "\"%s\"";
res.dat.strings.target[1] = type2char(tsc_type);
res.dat.strings.current[0] = "\"%s\"";
res.dat.strings.current[1] = type2char(csc_type);
} else if (tsc_type == LANGSXP) {
// Note how we pass cur_par and not current so we can modify cur_par
// this should be changed since we don't use that feature any more
UNPROTECT(1);
res = ALIKEC_lang_alike_rec(
target, cur_par_dup, tar_hash, cur_hash, rev_hash, tar_varnum,
cur_varnum, formula, match_call, match_env, set, res.dat.rec
);
PROTECT(res.wrap);
} else if(tsc_type == SYMSXP || csc_type == SYMSXP) {
res.success = 0;
res.dat.strings.target[0] = "\"%s\"";
res.dat.strings.target[1] = type2char(tsc_type);
res.dat.strings.current[0] = "\"%s\"";
res.dat.strings.current[1] = type2char(csc_type);
} else if (formula && !R_compute_identical(target, current, 16)) {
// Maybe this shouldn't be "identical", but too much of a pain in the butt
// to do an all.equals type comparison
// could have constant vs. language here, right?
res.success = 0;
res.dat.strings.tar_pre = "have";
res.dat.strings.target[1] = "identical constant values";
res.dat.strings.current[1] = ""; // gcc-10
} else res.success = 1;
// Deal with index implications of skiping parens, note + 2 because we need
// +1 for zero index, and then another +1 to reference contents of parens
if(!res.success) {
for(i = 0; i < i_max; i++) {
res.dat.rec = ALIKEC_rec_ind_num(res.dat.rec, i + 2);
res.dat.rec = ALIKEC_rec_dec(res.dat.rec);
}
if(res.wrap == R_NilValue) res.wrap = allocVector(VECSXP, 2);
}
UNPROTECT(4);
return res;
}
/*
Creates a copy of the call mapping objects to a deterministic set of names
based on the order in which they appear in the call
Here we use a hash table to identify whether a symbol already showed up or not.
This is probably faster if langauge object has 25 or more elements, so may
eventually want to add logic that choses path based on how many elements.
If return value is zero length string then comparison succeeded, otherwise
return value is error message. Note that we also return information by modifying
the `cur_par` argument by reference. We either mark the token the error message
refers to by wrapping it in ``{}``, or blow it away to indicate we don't want
the final error message to try to point out where the error occurred (this is
typically the case when the error is not specific to a particular part of the
call).
*/
struct ALIKEC_res ALIKEC_lang_alike_rec(
SEXP target, SEXP cur_par, pfHashTable * tar_hash, pfHashTable * cur_hash,
pfHashTable * rev_hash, size_t * tar_varnum, size_t * cur_varnum, int formula,
SEXP match_call, SEXP match_env, struct VALC_settings set,
struct ALIKEC_rec_track rec
) {
SEXP current = CAR(cur_par);
// If not language object, run comparison
struct ALIKEC_res res = ALIKEC_res_init();
res.dat.rec = rec;
if(TYPEOF(target) != LANGSXP || TYPEOF(current) != LANGSXP) {
res = ALIKEC_lang_obj_compare(
target, cur_par, tar_hash, cur_hash, rev_hash, tar_varnum,
cur_varnum, formula, match_call, match_env, set, res.dat.rec
);
} else {
// If language object, then recurse
res.dat.rec = ALIKEC_rec_inc(res.dat.rec);
SEXP tar_fun = CAR(target), cur_fun = CAR(current);
// Actual fun call must match exactly, unless NULL
if(tar_fun != R_NilValue && !R_compute_identical(tar_fun, cur_fun, 16)) {
res.success = 0;
res.dat.rec = ALIKEC_rec_ind_num(res.dat.rec, 1);
res.dat.strings.target[0] = "a call to `%s`";
res.dat.strings.target[1] = ALIKEC_deparse_chr(CAR(target), -1, set);
res.dat.strings.current[0] = "a call to `%s`";
res.dat.strings.current[1] = ALIKEC_deparse_chr(CAR(current), -1, set);
} else if (CDR(target) != R_NilValue) {
// Zero length calls match anything, so only come here if target is not
// Nil
// Match the calls before comparison; small inefficiency below since we
// know that target and current must be the same fun; we shouldn't need
// to retrieve it twice as we do now
int use_names = 1;
if(match_env != R_NilValue && set.lang_mode != 1) {
target = PROTECT(ALIKEC_match_call(target, match_call, match_env));
current = PROTECT(ALIKEC_match_call(current, match_call, match_env));
SETCAR(cur_par, current); // ensures original call is matched
// Can't be sure that names will match up with call as originally
// submitted
use_names = 0;
} else {
PROTECT(PROTECT(R_NilValue)); // stack balance
}
SEXP tar_sub, cur_sub, cur_sub_tag, tar_sub_tag,
prev_tag = R_UnboundValue;
R_xlen_t arg_num;
for(
tar_sub = CDR(target), cur_sub = CDR(current), arg_num = 0;
tar_sub != R_NilValue && cur_sub != R_NilValue;
tar_sub = CDR(tar_sub), cur_sub = CDR(cur_sub), prev_tag = cur_sub_tag,
arg_num++
) {
if(arg_num > R_XLEN_T_MAX - 1) {
// nocov start
error(
"Internal Error: %s; contact maintainer.",
"exceeded allowable call length"
);
// nocov end
}
// Check tags are compatible; NULL tag in target allows any tag in
// current
cur_sub_tag = TAG(cur_sub);
tar_sub_tag = TAG(tar_sub);
int update_rec_ind = 0;
if(tar_sub_tag != R_NilValue && tar_sub_tag != cur_sub_tag) {
char * prev_tag_msg = "as first argument";
if(prev_tag != R_UnboundValue) {
if(prev_tag == R_NilValue) {
prev_tag_msg = CSR_smprintf4(
set.nchar_max, "after argument %s", CSR_len_as_chr(arg_num),
"", "", ""
);
} else {
prev_tag_msg = CSR_smprintf4(
set.nchar_max, "after argument `%s`", CHAR(PRINTNAME(prev_tag)),
"", "", ""
);} }
res.success = 0;
res.dat.strings.tar_pre = "have";
res.dat.strings.target[0] = "argument `%s` %s";
res.dat.strings.target[1] = CHAR(PRINTNAME(TAG(tar_sub)));
res.dat.strings.target[2] = prev_tag_msg;
res.dat.strings.cur_pre = "has";
if(TAG(cur_sub) == R_NilValue) {
res.dat.strings.current[1] = "unnamed argument";
} else {
res.dat.strings.current[0] = "`%s`";
res.dat.strings.current[1] = CHAR(PRINTNAME(TAG(cur_sub)));
}
} else {
// Note that `lang_obj_compare` kicks off recursion as well, and
// skips parens
SEXP tar_sub_car = CAR(tar_sub);
res = ALIKEC_lang_obj_compare(
tar_sub_car, cur_sub, tar_hash, cur_hash, rev_hash,
tar_varnum, cur_varnum, formula, match_call, match_env, set,
res.dat.rec
);
update_rec_ind = 1;
}
// Update recursion indices and exit loop; keep in mind that this is a
// call so first element is fun, hence `arg_num + 2`
if(!res.success) {
if(update_rec_ind) {
if(cur_sub_tag != R_NilValue && use_names)
res.dat.rec =
ALIKEC_rec_ind_chr(res.dat.rec, CHAR(PRINTNAME(cur_sub_tag)));
else
res.dat.rec =
ALIKEC_rec_ind_num(res.dat.rec, arg_num + 2);
}
break;
}
}
if(res.success) {
// Make sure that we compared all items; missing R_NilValue here means
// one of the calls has more items
R_xlen_t tar_len, cur_len;
tar_len = cur_len = arg_num;
if(tar_sub != R_NilValue || cur_sub != R_NilValue) {
while(tar_sub != R_NilValue) {
tar_len++;
tar_sub = CDR(tar_sub);
}
while(cur_sub != R_NilValue) {
cur_len++;
cur_sub = CDR(cur_sub);
}
res.success = 0;
res.dat.strings.tar_pre = "have";
res.dat.strings.target[0] = "%s arguments";
res.dat.strings.target[1] = CSR_len_as_chr(tar_len);
res.dat.strings.cur_pre = "has";
res.dat.strings.current[1] = CSR_len_as_chr(cur_len);
}
}
target = current = R_NilValue;
UNPROTECT(2);
}
res.dat.rec = ALIKEC_rec_dec(res.dat.rec);
}
return res;
}
/*
Compare language objects.
This is a semi internal function used by the internal language comparison
mechanism as well as the external testing functions.
Determine whether objects should be compared as calls or as formulas; the main
difference in treatment is that calls are match-called if possible, and also
that for calls constants need not be the same
Return a list (vector) with the status, error message, the matched language
object, the original language object, and index within the langauge object of
the problem if there is one (relative to the matched object)
*/
SEXP ALIKEC_lang_alike_core(
SEXP target, SEXP current, struct VALC_settings set
) {
SEXP match_env = set.env;
SEXPTYPE tar_type = TYPEOF(target), cur_type = TYPEOF(current);
int tar_is_lang =
tar_type == LANGSXP || tar_type == SYMSXP || tar_type == NILSXP;
int cur_is_lang =
cur_type == LANGSXP || cur_type == SYMSXP || cur_type == NILSXP;
if(!(tar_is_lang && cur_is_lang))
error("Arguments must be LANGSXP, SYMSXP, or R_NilValue");
if(TYPEOF(match_env) != ENVSXP && match_env != R_NilValue)
error("Argument `match.call.env` must be an environment or NULL");
/*
Create persistent objects for use throught recursion; these are the hash
tables that are used to keep track of names as they show up as we recurse
through the language objects
*/
pfHashTable * tar_hash = pfHashCreate(NULL);
pfHashTable * cur_hash = pfHashCreate(NULL);
pfHashTable * rev_hash = pfHashCreate(NULL);
size_t tartmp = 0, curtmp=0;
size_t * tar_varnum = &tartmp;
size_t * cur_varnum = &curtmp;
// Can't figure out how to do this on init; cost ~60ns
SEXP match_call = PROTECT(
list3(
ALIKEC_SYM_matchcall, R_NilValue,
list2(R_QuoteSymbol, R_NilValue)
) );
SET_TYPEOF(match_call, LANGSXP);
SET_TYPEOF(CADDR(match_call), LANGSXP);
int formula = 0;
// Determine if it is a formular or not
SEXP class = PROTECT(getAttrib(target, R_ClassSymbol));
if(
class != R_NilValue && TYPEOF(class) == STRSXP &&
!strcmp("formula", CHAR(STRING_ELT(class, XLENGTH(class) - 1))) &&
CAR(target) == ALIKEC_SYM_tilde
) {
formula = 1;
}
UNPROTECT(1);
// Check if alike; originally we would modify a copy of current, which is
// why we send curr_cpy_par
SEXP curr_cpy_par = PROTECT(list1(duplicate(current)));
struct ALIKEC_rec_track rec = ALIKEC_rec_track_init();
struct ALIKEC_res res = ALIKEC_lang_alike_rec(
target, curr_cpy_par, tar_hash, cur_hash, rev_hash, tar_varnum, cur_varnum,
formula, match_call, match_env, set, rec
);
// Save our results in a SEXP to simplify testing
const char * names[6] = {
"success", "message", "call.match", "call.ind", "call.ind.sub.par",
"call.orig"
};
SEXP res_fin = PROTECT(allocVector(VECSXP, 6));
SEXP res_names = PROTECT(allocVector(STRSXP, 6));
for(int i = 0; i < 6; i++) SET_STRING_ELT(res_names, i, mkChar(names[i]));
setAttrib(res_fin, R_NamesSymbol, res_names);
SET_VECTOR_ELT(res_fin, 0, ScalarLogical(res.success));
if(!res.success) {
SEXP rec_ind = PROTECT(ALIKEC_rec_ind_as_lang(res.dat.rec));
SEXP res_msg = PROTECT(allocVector(VECSXP, 2));
SEXP res_msg_names = PROTECT(allocVector(STRSXP, 2));
SET_VECTOR_ELT(res_msg, 0, ALIKEC_res_strings_to_SEXP(res.dat.strings));
if(res.wrap == R_NilValue) {
res.wrap = PROTECT(allocVector(VECSXP, 2));
} else PROTECT(R_NilValue);
SET_VECTOR_ELT(res_msg, 1, res.wrap);
SET_STRING_ELT(res_msg_names, 0, mkChar("message"));
SET_STRING_ELT(res_msg_names, 1, mkChar("wrap"));
setAttrib(res_msg, R_NamesSymbol, res_msg_names);
SET_VECTOR_ELT(res_fin, 1, res_msg);
UNPROTECT(3);
SET_VECTOR_ELT(res_fin, 2, CAR(curr_cpy_par));
SET_VECTOR_ELT(res_fin, 3, VECTOR_ELT(rec_ind, 0));
SET_VECTOR_ELT(res_fin, 4, VECTOR_ELT(rec_ind, 1));
SET_VECTOR_ELT(res_fin, 5, current);
UNPROTECT(1);
}
UNPROTECT(4);
return res_fin;
}
/*
Translate result into res_sub for use by alike
Probalby some inefficiency in the C -> SEXP -> C translations going on; this
is happening mostly for legacy reason so should probably clean up to stick to
C at some point. One of the changes (amongst others) is that we no longer
care about recording the call / language that caused the problem since we're
refering directly to the original object
*/
struct ALIKEC_res ALIKEC_lang_alike_internal(
SEXP target, SEXP current, struct VALC_settings set
) {
SEXP lang_res = PROTECT(ALIKEC_lang_alike_core(target, current, set));
struct ALIKEC_res res = ALIKEC_res_init();
if(asInteger(VECTOR_ELT(lang_res, 0))) {
PROTECT(res.wrap); // stack balance
} else {
res.success = 0;
SEXP message = PROTECT(VECTOR_ELT(lang_res, 1));
SEXP msg_txt = VECTOR_ELT(message, 0);
res.dat.strings.tar_pre = CHAR(STRING_ELT(msg_txt, 0));
res.dat.strings.target[1] = CHAR(STRING_ELT(msg_txt, 1));
res.dat.strings.cur_pre = CHAR(STRING_ELT(msg_txt, 2));
res.dat.strings.current[1] = CHAR(STRING_ELT(msg_txt, 3));
// Deal with wrap
SEXP lang_ind = VECTOR_ELT(lang_res, 3);
SEXP lang_ind_sub = VECTOR_ELT(lang_res, 4);
SEXP wrap = VECTOR_ELT(message, 1);
SET_VECTOR_ELT(wrap, 0, lang_ind);
SET_VECTOR_ELT(wrap, 1, lang_ind_sub);
res.wrap = wrap;
}
UNPROTECT(2);
return res;
}
/*
For testing purposes
*/
SEXP ALIKEC_lang_alike_ext(
SEXP target, SEXP current, SEXP match_env
) {
struct VALC_settings set = VALC_settings_init();
set.env = match_env;
return ALIKEC_lang_alike_core(target, current, set);
}
SEXP ALIKEC_lang_alike_chr_ext(
SEXP target, SEXP current, SEXP match_env
) {
struct VALC_settings set = VALC_settings_init();
set.env = match_env;
struct ALIKEC_res res = ALIKEC_lang_alike_internal(target, current, set);
PROTECT(res.wrap);
SEXP res_str;
if(!res.success) {
res_str = PROTECT(ALIKEC_res_strings_to_SEXP(res.dat.strings));
} else {
res_str = PROTECT(mkString(""));
}
UNPROTECT(2);
return res_str;
}
| 34.275806 | 81 | 0.659451 | [
"object",
"vector"
] |
ed48949702472c189717339ce7360831a830a78c | 3,068 | h | C | tools/clang/test/ARCMT/Common.h | nettrino/IntFlow | 0400aef5da2c154268d8b020e393c950435395b3 | [
"Unlicense"
] | 16 | 2015-09-08T08:49:11.000Z | 2019-07-20T14:46:20.000Z | src/llvm/tools/clang/test/ARCMT/Common.h | jeltz/rust-debian-package | 07eaa3658867408248c555b1b3a593c012b4f931 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 1 | 2019-02-10T08:27:48.000Z | 2019-02-10T08:27:48.000Z | src/llvm/tools/clang/test/ARCMT/Common.h | jeltz/rust-debian-package | 07eaa3658867408248c555b1b3a593c012b4f931 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 7 | 2016-05-26T17:31:46.000Z | 2020-11-04T06:39:23.000Z | #if __has_feature(objc_arr)
#define NS_AUTOMATED_REFCOUNT_UNAVAILABLE __attribute__((unavailable("not available in automatic reference counting mode")))
#else
#define NS_AUTOMATED_REFCOUNT_UNAVAILABLE
#endif
#define NS_RETURNS_RETAINED __attribute__((ns_returns_retained))
#define CF_CONSUMED __attribute__((cf_consumed))
#define CF_RETURNS_RETAINED __attribute__((cf_returns_retained))
#define NS_INLINE static __inline__ __attribute__((always_inline))
#define nil ((void*) 0)
typedef int BOOL;
typedef unsigned NSUInteger;
typedef int int32_t;
typedef unsigned char uint8_t;
typedef int32_t UChar32;
typedef unsigned char UChar;
typedef struct _NSZone NSZone;
typedef const void * CFTypeRef;
CFTypeRef CFRetain(CFTypeRef cf);
CFTypeRef CFMakeCollectable(CFTypeRef cf) NS_AUTOMATED_REFCOUNT_UNAVAILABLE;
NS_INLINE NS_RETURNS_RETAINED id NSMakeCollectable(CFTypeRef CF_CONSUMED cf) NS_AUTOMATED_REFCOUNT_UNAVAILABLE;
@protocol NSObject
- (BOOL)isEqual:(id)object;
- (NSZone *)zone NS_AUTOMATED_REFCOUNT_UNAVAILABLE;
- (id)retain NS_AUTOMATED_REFCOUNT_UNAVAILABLE;
- (NSUInteger)retainCount NS_AUTOMATED_REFCOUNT_UNAVAILABLE;
- (oneway void)release NS_AUTOMATED_REFCOUNT_UNAVAILABLE;
- (id)autorelease NS_AUTOMATED_REFCOUNT_UNAVAILABLE;
@end
@interface NSObject <NSObject> {}
- (id)init;
+ (id)new;
+ (id)alloc;
- (void)dealloc;
- (void)finalize;
- (id)copy;
- (id)mutableCopy;
@end
NS_AUTOMATED_REFCOUNT_UNAVAILABLE
@interface NSAutoreleasePool : NSObject {
@private
void *_token;
void *_reserved3;
void *_reserved2;
void *_reserved;
}
+ (void)addObject:(id)anObject;
- (void)addObject:(id)anObject;
- (void)drain;
@end
typedef const void* objc_objectptr_t;
extern __attribute__((ns_returns_retained)) id objc_retainedObject(objc_objectptr_t __attribute__((cf_consumed)) pointer);
extern __attribute__((ns_returns_not_retained)) id objc_unretainedObject(objc_objectptr_t pointer);
extern objc_objectptr_t objc_unretainedPointer(id object);
#define dispatch_retain(object) ({ dispatch_object_t _o = (object); _dispatch_object_validate(_o); (void)[_o retain]; })
#define dispatch_release(object) ({ dispatch_object_t _o = (object); _dispatch_object_validate(_o); [_o release]; })
#define xpc_retain(object) ({ xpc_object_t _o = (object); _xpc_object_validate(_o); [_o retain]; })
#define xpc_release(object) ({ xpc_object_t _o = (object); _xpc_object_validate(_o); [_o release]; })
typedef id dispatch_object_t;
typedef id xpc_object_t;
void _dispatch_object_validate(dispatch_object_t object);
void _xpc_object_validate(xpc_object_t object);
#if __has_feature(objc_arc)
NS_INLINE CF_RETURNS_RETAINED CFTypeRef CFBridgingRetain(id X) {
return (__bridge_retained CFTypeRef)X;
}
NS_INLINE id CFBridgingRelease(CFTypeRef CF_CONSUMED X) {
return (__bridge_transfer id)X;
}
#else
NS_INLINE CF_RETURNS_RETAINED CFTypeRef CFBridgingRetain(id X) {
return X ? CFRetain((CFTypeRef)X) : NULL;
}
NS_INLINE id CFBridgingRelease(CFTypeRef CF_CONSUMED X) {
return [(id)CFMakeCollectable(X) autorelease];
}
#endif
| 29.219048 | 124 | 0.794329 | [
"object"
] |
ed4d10deafcf5e3eb5dd56a502623383733b90fc | 19,338 | h | C | aws-cpp-sdk-route53/include/aws/route53/model/CreateHostedZoneRequest.h | ambasta/aws-sdk-cpp | c81192e00b572b76d175d84dff77185bd17ae1ac | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-route53/include/aws/route53/model/CreateHostedZoneRequest.h | ambasta/aws-sdk-cpp | c81192e00b572b76d175d84dff77185bd17ae1ac | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-route53/include/aws/route53/model/CreateHostedZoneRequest.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/route53/Route53_EXPORTS.h>
#include <aws/route53/Route53Request.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/route53/model/VPC.h>
#include <aws/route53/model/HostedZoneConfig.h>
namespace Aws
{
namespace Route53
{
namespace Model
{
/**
* <p>A complex type containing the hosted zone request information.</p>
*/
class AWS_ROUTE53_API CreateHostedZoneRequest : public Route53Request
{
public:
CreateHostedZoneRequest();
Aws::String SerializePayload() const override;
/**
* <p>The name of the domain. For resource record types that include a domain name,
* specify a fully qualified domain name, for example, <i>www.example.com</i>. The
* trailing dot is optional; Amazon Route 53 assumes that the domain name is fully
* qualified. This means that Amazon Route 53 treats <i>www.example.com</i>
* (without a trailing dot) and <i>www.example.com.</i> (with a trailing dot) as
* identical.</p> <p>If you're creating a public hosted zone, this is the name you
* have registered with your DNS registrar. If your domain name is registered with
* a registrar other than Amazon Route 53, change the name servers for your domain
* to the set of <code>NameServers</code> that <code>CreateHostedZone</code>
* returns in the DelegationSet element.</p>
*/
inline const Aws::String& GetName() const{ return m_name; }
/**
* <p>The name of the domain. For resource record types that include a domain name,
* specify a fully qualified domain name, for example, <i>www.example.com</i>. The
* trailing dot is optional; Amazon Route 53 assumes that the domain name is fully
* qualified. This means that Amazon Route 53 treats <i>www.example.com</i>
* (without a trailing dot) and <i>www.example.com.</i> (with a trailing dot) as
* identical.</p> <p>If you're creating a public hosted zone, this is the name you
* have registered with your DNS registrar. If your domain name is registered with
* a registrar other than Amazon Route 53, change the name servers for your domain
* to the set of <code>NameServers</code> that <code>CreateHostedZone</code>
* returns in the DelegationSet element.</p>
*/
inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; }
/**
* <p>The name of the domain. For resource record types that include a domain name,
* specify a fully qualified domain name, for example, <i>www.example.com</i>. The
* trailing dot is optional; Amazon Route 53 assumes that the domain name is fully
* qualified. This means that Amazon Route 53 treats <i>www.example.com</i>
* (without a trailing dot) and <i>www.example.com.</i> (with a trailing dot) as
* identical.</p> <p>If you're creating a public hosted zone, this is the name you
* have registered with your DNS registrar. If your domain name is registered with
* a registrar other than Amazon Route 53, change the name servers for your domain
* to the set of <code>NameServers</code> that <code>CreateHostedZone</code>
* returns in the DelegationSet element.</p>
*/
inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = value; }
/**
* <p>The name of the domain. For resource record types that include a domain name,
* specify a fully qualified domain name, for example, <i>www.example.com</i>. The
* trailing dot is optional; Amazon Route 53 assumes that the domain name is fully
* qualified. This means that Amazon Route 53 treats <i>www.example.com</i>
* (without a trailing dot) and <i>www.example.com.</i> (with a trailing dot) as
* identical.</p> <p>If you're creating a public hosted zone, this is the name you
* have registered with your DNS registrar. If your domain name is registered with
* a registrar other than Amazon Route 53, change the name servers for your domain
* to the set of <code>NameServers</code> that <code>CreateHostedZone</code>
* returns in the DelegationSet element.</p>
*/
inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); }
/**
* <p>The name of the domain. For resource record types that include a domain name,
* specify a fully qualified domain name, for example, <i>www.example.com</i>. The
* trailing dot is optional; Amazon Route 53 assumes that the domain name is fully
* qualified. This means that Amazon Route 53 treats <i>www.example.com</i>
* (without a trailing dot) and <i>www.example.com.</i> (with a trailing dot) as
* identical.</p> <p>If you're creating a public hosted zone, this is the name you
* have registered with your DNS registrar. If your domain name is registered with
* a registrar other than Amazon Route 53, change the name servers for your domain
* to the set of <code>NameServers</code> that <code>CreateHostedZone</code>
* returns in the DelegationSet element.</p>
*/
inline CreateHostedZoneRequest& WithName(const Aws::String& value) { SetName(value); return *this;}
/**
* <p>The name of the domain. For resource record types that include a domain name,
* specify a fully qualified domain name, for example, <i>www.example.com</i>. The
* trailing dot is optional; Amazon Route 53 assumes that the domain name is fully
* qualified. This means that Amazon Route 53 treats <i>www.example.com</i>
* (without a trailing dot) and <i>www.example.com.</i> (with a trailing dot) as
* identical.</p> <p>If you're creating a public hosted zone, this is the name you
* have registered with your DNS registrar. If your domain name is registered with
* a registrar other than Amazon Route 53, change the name servers for your domain
* to the set of <code>NameServers</code> that <code>CreateHostedZone</code>
* returns in the DelegationSet element.</p>
*/
inline CreateHostedZoneRequest& WithName(Aws::String&& value) { SetName(value); return *this;}
/**
* <p>The name of the domain. For resource record types that include a domain name,
* specify a fully qualified domain name, for example, <i>www.example.com</i>. The
* trailing dot is optional; Amazon Route 53 assumes that the domain name is fully
* qualified. This means that Amazon Route 53 treats <i>www.example.com</i>
* (without a trailing dot) and <i>www.example.com.</i> (with a trailing dot) as
* identical.</p> <p>If you're creating a public hosted zone, this is the name you
* have registered with your DNS registrar. If your domain name is registered with
* a registrar other than Amazon Route 53, change the name servers for your domain
* to the set of <code>NameServers</code> that <code>CreateHostedZone</code>
* returns in the DelegationSet element.</p>
*/
inline CreateHostedZoneRequest& WithName(const char* value) { SetName(value); return *this;}
/**
* <p>The VPC that you want your hosted zone to be associated with. By providing
* this parameter, your newly created hosted cannot be resolved anywhere other than
* the given VPC.</p>
*/
inline const VPC& GetVPC() const{ return m_vPC; }
/**
* <p>The VPC that you want your hosted zone to be associated with. By providing
* this parameter, your newly created hosted cannot be resolved anywhere other than
* the given VPC.</p>
*/
inline void SetVPC(const VPC& value) { m_vPCHasBeenSet = true; m_vPC = value; }
/**
* <p>The VPC that you want your hosted zone to be associated with. By providing
* this parameter, your newly created hosted cannot be resolved anywhere other than
* the given VPC.</p>
*/
inline void SetVPC(VPC&& value) { m_vPCHasBeenSet = true; m_vPC = value; }
/**
* <p>The VPC that you want your hosted zone to be associated with. By providing
* this parameter, your newly created hosted cannot be resolved anywhere other than
* the given VPC.</p>
*/
inline CreateHostedZoneRequest& WithVPC(const VPC& value) { SetVPC(value); return *this;}
/**
* <p>The VPC that you want your hosted zone to be associated with. By providing
* this parameter, your newly created hosted cannot be resolved anywhere other than
* the given VPC.</p>
*/
inline CreateHostedZoneRequest& WithVPC(VPC&& value) { SetVPC(value); return *this;}
/**
* <p>A unique string that identifies the request and that allows failed
* <code>CreateHostedZone</code> requests to be retried without the risk of
* executing the operation twice. You must use a unique
* <code>CallerReference</code> string every time you create a hosted zone.
* <code>CallerReference</code> can be any unique string, for example, a date/time
* stamp.</p>
*/
inline const Aws::String& GetCallerReference() const{ return m_callerReference; }
/**
* <p>A unique string that identifies the request and that allows failed
* <code>CreateHostedZone</code> requests to be retried without the risk of
* executing the operation twice. You must use a unique
* <code>CallerReference</code> string every time you create a hosted zone.
* <code>CallerReference</code> can be any unique string, for example, a date/time
* stamp.</p>
*/
inline void SetCallerReference(const Aws::String& value) { m_callerReferenceHasBeenSet = true; m_callerReference = value; }
/**
* <p>A unique string that identifies the request and that allows failed
* <code>CreateHostedZone</code> requests to be retried without the risk of
* executing the operation twice. You must use a unique
* <code>CallerReference</code> string every time you create a hosted zone.
* <code>CallerReference</code> can be any unique string, for example, a date/time
* stamp.</p>
*/
inline void SetCallerReference(Aws::String&& value) { m_callerReferenceHasBeenSet = true; m_callerReference = value; }
/**
* <p>A unique string that identifies the request and that allows failed
* <code>CreateHostedZone</code> requests to be retried without the risk of
* executing the operation twice. You must use a unique
* <code>CallerReference</code> string every time you create a hosted zone.
* <code>CallerReference</code> can be any unique string, for example, a date/time
* stamp.</p>
*/
inline void SetCallerReference(const char* value) { m_callerReferenceHasBeenSet = true; m_callerReference.assign(value); }
/**
* <p>A unique string that identifies the request and that allows failed
* <code>CreateHostedZone</code> requests to be retried without the risk of
* executing the operation twice. You must use a unique
* <code>CallerReference</code> string every time you create a hosted zone.
* <code>CallerReference</code> can be any unique string, for example, a date/time
* stamp.</p>
*/
inline CreateHostedZoneRequest& WithCallerReference(const Aws::String& value) { SetCallerReference(value); return *this;}
/**
* <p>A unique string that identifies the request and that allows failed
* <code>CreateHostedZone</code> requests to be retried without the risk of
* executing the operation twice. You must use a unique
* <code>CallerReference</code> string every time you create a hosted zone.
* <code>CallerReference</code> can be any unique string, for example, a date/time
* stamp.</p>
*/
inline CreateHostedZoneRequest& WithCallerReference(Aws::String&& value) { SetCallerReference(value); return *this;}
/**
* <p>A unique string that identifies the request and that allows failed
* <code>CreateHostedZone</code> requests to be retried without the risk of
* executing the operation twice. You must use a unique
* <code>CallerReference</code> string every time you create a hosted zone.
* <code>CallerReference</code> can be any unique string, for example, a date/time
* stamp.</p>
*/
inline CreateHostedZoneRequest& WithCallerReference(const char* value) { SetCallerReference(value); return *this;}
/**
* <p> (Optional) A complex type that contains an optional comment about your
* hosted zone. If you don't want to specify a comment, omit both the
* <code>HostedZoneConfig</code> and <code>Comment</code> elements.</p>
*/
inline const HostedZoneConfig& GetHostedZoneConfig() const{ return m_hostedZoneConfig; }
/**
* <p> (Optional) A complex type that contains an optional comment about your
* hosted zone. If you don't want to specify a comment, omit both the
* <code>HostedZoneConfig</code> and <code>Comment</code> elements.</p>
*/
inline void SetHostedZoneConfig(const HostedZoneConfig& value) { m_hostedZoneConfigHasBeenSet = true; m_hostedZoneConfig = value; }
/**
* <p> (Optional) A complex type that contains an optional comment about your
* hosted zone. If you don't want to specify a comment, omit both the
* <code>HostedZoneConfig</code> and <code>Comment</code> elements.</p>
*/
inline void SetHostedZoneConfig(HostedZoneConfig&& value) { m_hostedZoneConfigHasBeenSet = true; m_hostedZoneConfig = value; }
/**
* <p> (Optional) A complex type that contains an optional comment about your
* hosted zone. If you don't want to specify a comment, omit both the
* <code>HostedZoneConfig</code> and <code>Comment</code> elements.</p>
*/
inline CreateHostedZoneRequest& WithHostedZoneConfig(const HostedZoneConfig& value) { SetHostedZoneConfig(value); return *this;}
/**
* <p> (Optional) A complex type that contains an optional comment about your
* hosted zone. If you don't want to specify a comment, omit both the
* <code>HostedZoneConfig</code> and <code>Comment</code> elements.</p>
*/
inline CreateHostedZoneRequest& WithHostedZoneConfig(HostedZoneConfig&& value) { SetHostedZoneConfig(value); return *this;}
/**
* <p>If you want to associate a reusable delegation set with this hosted zone, the
* ID that Amazon Route 53 assigned to the reusable delegation set when you created
* it. For more information about reusable delegation sets, see
* <a>CreateReusableDelegationSet</a>.</p> <dl> <dt>Type</dt> <dd> <p>String</p>
* </dd> <dt>Default</dt> <dd> <p>None</p> </dd> <dt>Parent</dt> <dd> <p>
* <code>CreatedHostedZoneRequest</code> </p> </dd> </dl>
*/
inline const Aws::String& GetDelegationSetId() const{ return m_delegationSetId; }
/**
* <p>If you want to associate a reusable delegation set with this hosted zone, the
* ID that Amazon Route 53 assigned to the reusable delegation set when you created
* it. For more information about reusable delegation sets, see
* <a>CreateReusableDelegationSet</a>.</p> <dl> <dt>Type</dt> <dd> <p>String</p>
* </dd> <dt>Default</dt> <dd> <p>None</p> </dd> <dt>Parent</dt> <dd> <p>
* <code>CreatedHostedZoneRequest</code> </p> </dd> </dl>
*/
inline void SetDelegationSetId(const Aws::String& value) { m_delegationSetIdHasBeenSet = true; m_delegationSetId = value; }
/**
* <p>If you want to associate a reusable delegation set with this hosted zone, the
* ID that Amazon Route 53 assigned to the reusable delegation set when you created
* it. For more information about reusable delegation sets, see
* <a>CreateReusableDelegationSet</a>.</p> <dl> <dt>Type</dt> <dd> <p>String</p>
* </dd> <dt>Default</dt> <dd> <p>None</p> </dd> <dt>Parent</dt> <dd> <p>
* <code>CreatedHostedZoneRequest</code> </p> </dd> </dl>
*/
inline void SetDelegationSetId(Aws::String&& value) { m_delegationSetIdHasBeenSet = true; m_delegationSetId = value; }
/**
* <p>If you want to associate a reusable delegation set with this hosted zone, the
* ID that Amazon Route 53 assigned to the reusable delegation set when you created
* it. For more information about reusable delegation sets, see
* <a>CreateReusableDelegationSet</a>.</p> <dl> <dt>Type</dt> <dd> <p>String</p>
* </dd> <dt>Default</dt> <dd> <p>None</p> </dd> <dt>Parent</dt> <dd> <p>
* <code>CreatedHostedZoneRequest</code> </p> </dd> </dl>
*/
inline void SetDelegationSetId(const char* value) { m_delegationSetIdHasBeenSet = true; m_delegationSetId.assign(value); }
/**
* <p>If you want to associate a reusable delegation set with this hosted zone, the
* ID that Amazon Route 53 assigned to the reusable delegation set when you created
* it. For more information about reusable delegation sets, see
* <a>CreateReusableDelegationSet</a>.</p> <dl> <dt>Type</dt> <dd> <p>String</p>
* </dd> <dt>Default</dt> <dd> <p>None</p> </dd> <dt>Parent</dt> <dd> <p>
* <code>CreatedHostedZoneRequest</code> </p> </dd> </dl>
*/
inline CreateHostedZoneRequest& WithDelegationSetId(const Aws::String& value) { SetDelegationSetId(value); return *this;}
/**
* <p>If you want to associate a reusable delegation set with this hosted zone, the
* ID that Amazon Route 53 assigned to the reusable delegation set when you created
* it. For more information about reusable delegation sets, see
* <a>CreateReusableDelegationSet</a>.</p> <dl> <dt>Type</dt> <dd> <p>String</p>
* </dd> <dt>Default</dt> <dd> <p>None</p> </dd> <dt>Parent</dt> <dd> <p>
* <code>CreatedHostedZoneRequest</code> </p> </dd> </dl>
*/
inline CreateHostedZoneRequest& WithDelegationSetId(Aws::String&& value) { SetDelegationSetId(value); return *this;}
/**
* <p>If you want to associate a reusable delegation set with this hosted zone, the
* ID that Amazon Route 53 assigned to the reusable delegation set when you created
* it. For more information about reusable delegation sets, see
* <a>CreateReusableDelegationSet</a>.</p> <dl> <dt>Type</dt> <dd> <p>String</p>
* </dd> <dt>Default</dt> <dd> <p>None</p> </dd> <dt>Parent</dt> <dd> <p>
* <code>CreatedHostedZoneRequest</code> </p> </dd> </dl>
*/
inline CreateHostedZoneRequest& WithDelegationSetId(const char* value) { SetDelegationSetId(value); return *this;}
private:
Aws::String m_name;
bool m_nameHasBeenSet;
VPC m_vPC;
bool m_vPCHasBeenSet;
Aws::String m_callerReference;
bool m_callerReferenceHasBeenSet;
HostedZoneConfig m_hostedZoneConfig;
bool m_hostedZoneConfigHasBeenSet;
Aws::String m_delegationSetId;
bool m_delegationSetIdHasBeenSet;
};
} // namespace Model
} // namespace Route53
} // namespace Aws
| 53.41989 | 135 | 0.691126 | [
"model"
] |
ed6a9f14a40eed06727eb94ebe1aa083b21fb4c4 | 2,101 | h | C | include/GCApplication.h | Robertwyq/Grab_Cut | 1eafa8dc84fcecb9be0a0b4c12cb7df58cb61fbc | [
"Unlicense"
] | 2 | 2020-03-12T03:28:42.000Z | 2020-03-12T10:47:01.000Z | include/GCApplication.h | Robertwyq/Grab_Cut | 1eafa8dc84fcecb9be0a0b4c12cb7df58cb61fbc | [
"Unlicense"
] | null | null | null | include/GCApplication.h | Robertwyq/Grab_Cut | 1eafa8dc84fcecb9be0a0b4c12cb7df58cb61fbc | [
"Unlicense"
] | null | null | null | //
// Created by Robert on 2019/6/5.
//
#ifndef GRAB_CUT_GCAPPLICATION_H
#define GRAB_CUT_GCAPPLICATION_H
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "GrabCut.h"
#include <iostream>
#include "BorderMatting.h"
using namespace std;
using namespace cv;
const Scalar BLUE = Scalar(255,0,0); // Background
const Scalar GREEN = Scalar(0,255,0);//Foreground
const Scalar LIGHTBLUE = Scalar(255,255,160);//ProbBackground
const Scalar PINK = Scalar(230,130,255); //ProbBackground
const Scalar RED = Scalar(0,0,255);//color of Rectangle
const int BGD_KEY = CV_EVENT_FLAG_CTRLKEY;// When press "CTRL" key,the value of flags return.
const int FGD_KEY = CV_EVENT_FLAG_SHIFTKEY;// When press "SHIFT" key, the value of flags return.
//Copy the value of comMask to binMask
static void getBinMask( const Mat& comMask, Mat& binMask )
{
if( comMask.empty() || comMask.type()!=CV_8UC1 )
CV_Error( CV_StsBadArg, "comMask is empty or has incorrect type (not CV_8UC1)" );
if( binMask.empty() || binMask.rows!=comMask.rows || binMask.cols!=comMask.cols )
binMask.create( comMask.size(), CV_8UC1 );
binMask = comMask & 1;
}
class GCApplication {
public:
enum{ NOT_SET = 0, IN_PROCESS = 1, SET = 2 };
static const int radius = 5;
static const int thickness = -1;
void reset();
void setImageAndWinName( const Mat& _image, const string& _winName );
void showImage() const;
void mouseClick( int event, int x, int y, int flags, void* param );
int nextIter();
int getIterCount() const { return iterCount; }
BorderMatting bm;
void BoardMatting();
void showOriginalImage();
private:
void setRectInMask();
void setLblsInMask( int flags, Point p, bool isPr );
const string* winName;
const Mat* image;
Mat mask;
Mat bgdModel, fgdModel;
uchar rectState, lblsState, prLblsState;
bool isInitialized;
Rect rect;
vector<Point> fgdPixelVector, bgdPixelVector, prFgdPixelVector, prBgdPixelVector;
int iterCount;
GrabCut2D gc;
};
#endif //GRAB_CUT_GCAPPLICATION_H
| 29.180556 | 96 | 0.705378 | [
"vector"
] |
ed6ba610f9e140a7c94980b9d4f57f534474b8d7 | 3,249 | h | C | rst/task_runner/polling_task_runner.h | sabbakumov/rst | c0257ab1fb17dea7b022cc4955f715d80a9b32f6 | [
"BSD-2-Clause"
] | 4 | 2016-12-15T13:06:36.000Z | 2022-01-10T16:34:00.000Z | rst/task_runner/polling_task_runner.h | sabbakumov/rst | c0257ab1fb17dea7b022cc4955f715d80a9b32f6 | [
"BSD-2-Clause"
] | 103 | 2019-01-24T18:06:35.000Z | 2021-11-02T13:33:34.000Z | rst/task_runner/polling_task_runner.h | sabbakumov/rst | c0257ab1fb17dea7b022cc4955f715d80a9b32f6 | [
"BSD-2-Clause"
] | 4 | 2018-04-24T06:59:59.000Z | 2022-02-04T18:10:03.000Z | // Copyright (c) 2019, Sergey Abbakumov
// 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.
#ifndef RST_TASK_RUNNER_POLLING_TASK_RUNNER_H_
#define RST_TASK_RUNNER_POLLING_TASK_RUNNER_H_
#include <chrono>
#include <cstdint>
#include <functional>
#include <mutex>
#include <vector>
#include "rst/macros/macros.h"
#include "rst/macros/thread_annotations.h"
#include "rst/task_runner/item.h"
#include "rst/task_runner/iteration_item.h"
#include "rst/task_runner/task_runner.h"
namespace rst {
// Task runner that is supposed to run tasks on the same thread.
//
// Example:
//
// std::function<std::chrono::nanoseconds()> time_function = ...;
// rst::PollingTaskRunner task_runner(std::move(time_function));
// for (;; task_runner.RunPendingTasks()) {
// ...
// std::function<void()> task = ...;
// task_runner.PostTask(std::move(task));
// ...
// }
//
class PollingTaskRunner : public TaskRunner {
public:
// Takes |time_function| that returns current time.
explicit PollingTaskRunner(
std::function<std::chrono::nanoseconds()>&& time_function);
~PollingTaskRunner() override;
// Runs all pending tasks in interval (-inf, time_function_()].
void RunPendingTasks();
private:
// TaskRunner:
void PostDelayedTaskWithIterations(std::function<void()>&& task,
std::chrono::nanoseconds delay,
size_t iterations) override;
std::mutex mutex_;
// Returns current time.
const std::function<std::chrono::nanoseconds()> time_function_;
// Used to not to allocate memory on every RunPendingTasks() call.
std::vector<internal::IterationItem> pending_tasks_;
// Priority queue of tasks.
std::vector<internal::Item> queue_ RST_GUARDED_BY(mutex_);
// Increasing task counter.
uint64_t task_id_ RST_GUARDED_BY(mutex_) = 0;
RST_DISALLOW_COPY_AND_ASSIGN(PollingTaskRunner);
};
} // namespace rst
#endif // RST_TASK_RUNNER_POLLING_TASK_RUNNER_H_
| 36.505618 | 73 | 0.730071 | [
"vector"
] |
ed6eb139647c123a8f49e1262063b11a0d13d888 | 1,433 | h | C | libs/gl_utils/computeshader.h | danniesim/cpp_volume_rendering | 242c8917aea0a58c9851c2ae3e6c1555db51912e | [
"MIT"
] | 10 | 2020-05-15T23:50:19.000Z | 2022-02-17T09:54:44.000Z | libs/gl_utils/computeshader.h | danniesim/cpp_volume_rendering | 242c8917aea0a58c9851c2ae3e6c1555db51912e | [
"MIT"
] | 1 | 2022-01-25T02:36:59.000Z | 2022-01-26T11:41:38.000Z | libs/gl_utils/computeshader.h | danniesim/cpp_volume_rendering | 242c8917aea0a58c9851c2ae3e6c1555db51912e | [
"MIT"
] | 3 | 2021-11-01T10:32:46.000Z | 2021-12-28T16:40:10.000Z | /**
* OpenGL General Purpose Compute Shader Class
* - Reload support
*
* About glBindImageTexture and glBindTexture:
* . https://stackoverflow.com/questions/37136813/what-is-the-difference-between-glbindimagetexture-and-glbindtexture
*
* Leonardo Quatrin Campagnolo
* . campagnolo.lq@gmail.com
**/
#ifndef GL_UTILS_COMPUTE_SHADER_H
#define GL_UTILS_COMPUTE_SHADER_H
#include <GL/glew.h>
#include "shader.h"
#include <iostream>
#include <string>
#include "texture3d.h"
namespace gl
{
class ComputeShader : public Shader
{
public:
ComputeShader ();
~ComputeShader ();
virtual bool LoadAndLink ();
virtual bool Reload ();
void SetShaderFile (std::string filename);
void AddShaderFile (std::string filepath);
void RecomputeNumberOfGroups (GLuint w, GLuint h, GLuint d, GLuint t_x = 8, GLuint t_y = 8, GLuint t_z = 8);
void Dispatch ();
// Bind a gl::Texture3D using 'glBindImageTexture'. layered must be true.
void BindImageTexture (gl::Texture3D* tex, GLuint unit, GLint level, GLenum access,
GLenum format, GLboolean layered = GL_TRUE, GLint layer = 0);
protected:
private:
std::vector<std::string> vec_compute_shader_names;
std::vector<GLuint> vec_compute_shader_ids;
void CompileShader (GLuint shader_id, std::string filename);
GLuint num_groups_x;
GLuint num_groups_y;
GLuint num_groups_z;
};
}
#endif | 23.883333 | 117 | 0.704117 | [
"vector"
] |
ed74697841a12d245e20c07bf744fd64a2085a14 | 3,940 | h | C | ds/security/gina/snapins/ade/stdafx.h | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | ds/security/gina/snapins/ade/stdafx.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | ds/security/gina/snapins/ade/stdafx.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //+--------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1994 - 1998.
//
// File: stdafx.h
//
// Contents: include file for standard system include files, or project
// specific include files that are used frequently, but are
// changed infrequently
//
// History: 03-14-1998 stevebl Commented
//
//---------------------------------------------------------------------------
#include <afxwin.h>
#include <afxdisp.h>
#include <atlbase.h>
//You may derive a class from CComModule and use it if you want to override
//something, but do not change the name of _Module
extern CComModule _Module;
#ifdef DBG
//
// ATL's implementation of Release always returns 0 unless _DEBUG is
// defined. The debug version of OLE.DLL asserts Release() != 0 in certain
// circumstances. I don't want to define _DEBUG because it brings in a
// whole lot of baggage from MMC that I don't want to deal with, but I do
// want to avoid this assertion in OLE, so on debug builds, I'll go ahead
// and define _DEBUG for the appropriate ATL header file but I'll undefine
// it again right afterward. This is a little flakey but it is relatively
// safe and it achieves the desired goal.
//
// - SteveBl
//
#define _DEBUG
#endif
#include <atlcom.h>
#ifdef DBG
#undef _DEBUG
#endif
#pragma comment(lib, "mmc")
#include <mmc.h>
#include "afxtempl.h"
const long UNINITIALIZED = -1;
// Sample folder types
enum FOLDER_TYPES
{
STATIC = 0x8000,
};
/////////////////////////////////////////////////////////////////////////////
// Helper functions
template<class TYPE>
inline void SAFE_RELEASE(TYPE*& pObj)
{
if (pObj != NULL)
{
pObj->Release();
pObj = NULL;
}
else
{
TRACE(_T("Release called on NULL interface ptr\n"));
}
}
extern const CLSID CLSID_Snapin; // In-Proc server GUID
extern const GUID cNodeType; // Main NodeType GUID on numeric format
extern const wchar_t* cszNodeType; // Main NodeType GUID on string format
// New Clipboard format that has the Type and Cookie
extern const wchar_t* SNAPIN_INTERNAL;
struct INTERNAL
{
INTERNAL() { m_type = CCT_UNINITIALIZED; m_cookie = -1;};
~INTERNAL() {}
DATA_OBJECT_TYPES m_type; // What context is the data object.
MMC_COOKIE m_cookie; // What object the cookie represents
CString m_string;
INTERNAL & operator=(const INTERNAL& rhs)
{
if (&rhs == this)
return *this;
m_type = rhs.m_type;
m_cookie = rhs.m_cookie;
m_string = rhs.m_string;
return *this;
}
BOOL operator==(const INTERNAL& rhs)
{
return rhs.m_string == m_string;
}
};
// Debug instance counter
#ifdef _DEBUG
inline void DbgInstanceRemaining(char * pszClassName, int cInstRem)
{
char buf[100];
(void) StringCchPrintfA(buf,
sizeof(buf)/sizeof(buf[0]),
"%s has %d instances left over.",
pszClassName,
cInstRem);
::MessageBoxA(NULL, buf, "Memory Leak!!!", MB_OK);
}
#define DEBUG_DECLARE_INSTANCE_COUNTER(cls) extern int s_cInst_##cls = 0;
#define DEBUG_INCREMENT_INSTANCE_COUNTER(cls) ++(s_cInst_##cls);
#define DEBUG_DECREMENT_INSTANCE_COUNTER(cls) --(s_cInst_##cls);
#define DEBUG_VERIFY_INSTANCE_COUNT(cls) \
extern int s_cInst_##cls; \
if (s_cInst_##cls) DbgInstanceRemaining(#cls, s_cInst_##cls);
#else
#define DEBUG_DECLARE_INSTANCE_COUNTER(cls)
#define DEBUG_INCREMENT_INSTANCE_COUNTER(cls)
#define DEBUG_DECREMENT_INSTANCE_COUNTER(cls)
#define DEBUG_VERIFY_INSTANCE_COUNT(cls)
#endif
| 29.402985 | 83 | 0.593655 | [
"object"
] |
4bb7e4d95b5fded4ed5b72d69b2e05bdbd583793 | 3,012 | h | C | src/PopupCommand.h | TheFoundry-Modo/VDBVoxel | 8321e6531e638ff7a7d34812f9b61e21b20ce9ff | [
"Apache-2.0"
] | 5 | 2016-02-19T22:41:21.000Z | 2020-02-29T21:14:07.000Z | src/PopupCommand.h | TheFoundry-Modo/VDBVoxel | 8321e6531e638ff7a7d34812f9b61e21b20ce9ff | [
"Apache-2.0"
] | null | null | null | src/PopupCommand.h | TheFoundry-Modo/VDBVoxel | 8321e6531e638ff7a7d34812f9b61e21b20ce9ff | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2015 The Foundry Visionmongers 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
*
* Neither the name of The Foundry nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 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 POPUPCOMMAND_H
#define POPUPCOMMAND_H
#include <lx_plugin.hpp>
#include <lxu_command.hpp>
#include <lx_command.hpp>
#include <lx_io.hpp>
#include <lx_seltypes.hpp>
#include <lxu_select.hpp>
#include <lxu_message.hpp>
#include <lx_channelui.hpp>
#include "common.h"
#define FEATURE_POPUP_SERVER_NAME "feature.popup"
#define ARG_FEATURENAME "featurename"
#define ARGi_FEATURENAME 0
#define POPUP_COMMAND_NOTIFIER "popup.command.notifier"
using std::string;
using std::vector;
/*
* Pop up menu command for selecting a valid feature of VDB voxel data.
* A feature maps to a grid in OpenVDBItem.
*/
class CCommandSetFeature
: public CLxBasicCommand
{
public:
static void
initialize ()
{
CLxGenericPolymorph *srv;
srv =new CLxPolymorph <CCommandSetFeature>;
srv->AddInterface (new CLxIfc_Command <CCommandSetFeature>);
srv->AddInterface (new CLxIfc_Attributes <CCommandSetFeature>);
srv->AddInterface (new CLxIfc_AttributesUI <CCommandSetFeature>);
thisModule.AddServer (FEATURE_POPUP_SERVER_NAME, srv);
}
CCommandSetFeature ();
int
basic_CmdFlags () LXx_OVERRIDE;
bool
basic_Enable (
CLxUser_Message &msg) LXx_OVERRIDE;
bool
basic_Notifier (
int index,
std::string &name,
std::string &args) LXx_OVERRIDE;
CLxDynamicUIValue *
atrui_UIValue (
unsigned int index) LXx_OVERRIDE;
LxResult
cmd_Query (
unsigned int index,
ILxUnknownID vaQuery)LXx_OVERRIDE;
void
cmd_Execute (
unsigned flags) LXx_OVERRIDE;
protected:
class CFeatureNamePopup
: public CLxUIListPopup
{
public:
CCommandSetFeature *cmd;
CFeatureNamePopup (
CCommandSetFeature* val) : cmd (val){}
void
UpdateLists () { cmd->GetNameList (user_list);}
};
void
GetNameList (
vector<string> &list);
void
InitRead (
CLxUser_Item &item);
bool
isCurrentType ();
/*
* The item selection type we're interested in is our own.
*/
CLxItemSelectionType m_sel_geni;
/*
* We use a common channel read, and assume that all the items processed
* in the selection are from the same scene. When we set the read object
* we record the channel indicies.
*/
CLxUser_ChannelRead m_read_chan;
int m_idx_name;
};
#endif | 22.646617 | 74 | 0.738712 | [
"object",
"vector"
] |
4bbbb92920dd84acfb9fc0eaf9d8a255eee4d493 | 2,471 | h | C | src/server_main/engine/world/island.h | snowmeltarcade/projectfarm | 6a35330f63bff06465c4ee1a0fbc5277c0d22982 | [
"MIT"
] | null | null | null | src/server_main/engine/world/island.h | snowmeltarcade/projectfarm | 6a35330f63bff06465c4ee1a0fbc5277c0d22982 | [
"MIT"
] | 7 | 2021-05-30T21:52:39.000Z | 2021-06-25T22:35:28.000Z | src/server_main/engine/world/island.h | snowmeltarcade/projectfarm | 6a35330f63bff06465c4ee1a0fbc5277c0d22982 | [
"MIT"
] | null | null | null | #ifndef PROJECTFARM_ISLAND_H
#define PROJECTFARM_ISLAND_H
#include <cstdint>
#include <vector>
#include <fstream>
#include <nlohmann/json.hpp>
#include "plots.h"
#include "world_change_log_entry.h"
#include "time/consume_timer.h"
#include "time/timer.h"
#include "action_tile.h"
namespace projectfarm::engine::world
{
class Island final : public shared::time::ConsumeTimer
{
public:
Island() = default;
~Island() override = default;
[[nodiscard]] bool LoadFromJson(const nlohmann::json& json, const std::shared_ptr<Plots>& plots);
[[nodiscard]] bool LoadFromBinary(std::ifstream& fs, const std::shared_ptr<Plots>& plots) noexcept;
void Shutdown() noexcept;
[[nodiscard]] uint32_t GetHeightInTiles() const noexcept
{
return this->_heightInTiles;
}
[[nodiscard]] const std::vector<WorldChangeLogEntry>& GetChangeLog() const noexcept
{
return this->_changeLog;
}
[[nodiscard]] uint16_t GetPlotIndexAtWorldPosition(float x, float y) const noexcept;
[[nodiscard]] std::pair<int32_t, int32_t> GetTileIndexesFromWorldPosition(float x, float y) const noexcept;
[[nodiscard]] std::pair<float, float> GetWorldPositionFromTileCoordinate(uint32_t x, uint32_t y) const noexcept;
[[nodiscard]] const std::vector<ActionTile>& GetActionTiles() const noexcept
{
return this->_actionTiles;
}
[[nodiscard]] std::vector<ActionTile> GetActionTilesByProperty(const std::string& name, const std::string& value) noexcept;
[[nodiscard]] std::string GetPropertyValueForTile(const std::string& key, uint32_t x, uint32_t y) const noexcept;
private:
float _positionX {0.0f};
float _positionY {0.0f};
uint32_t _widthInTiles {0};
uint32_t _heightInTiles {0};
float _tileWidthInMeters {0.0f};
float _tileHeightInMeters {0.0f};
float _widthInMeters {0.0f};
float _heightInMeters {0.0f};
std::shared_ptr<Plots> _plots;
std::vector<WorldChangeLogEntry> _changeLog;
std::vector<std::vector<std::vector<uint16_t>>> _layers;
[[nodiscard]] bool LoadLayerFromJson(const nlohmann::json& json);
[[nodiscard]] bool LoadLayerFromBinary(std::ifstream& fs) noexcept;
void LoadActionTiles(std::ifstream& fs) noexcept;
std::vector<ActionTile> _actionTiles;
};
}
#endif
| 30.8875 | 131 | 0.665722 | [
"vector"
] |
4bcbab1b6cc68aeb555b30b857ea4bcbd55c27ab | 5,185 | h | C | libtensor/gen_block_tensor/impl/gen_block_tensor_impl.h | maxscheurer/libtensor | 288ed0596b24356d187d2fa40c05b0dacd00b413 | [
"BSL-1.0"
] | 33 | 2016-02-08T06:05:17.000Z | 2021-11-17T01:23:11.000Z | libtensor/gen_block_tensor/impl/gen_block_tensor_impl.h | maxscheurer/libtensor | 288ed0596b24356d187d2fa40c05b0dacd00b413 | [
"BSL-1.0"
] | 11 | 2020-12-04T20:26:12.000Z | 2021-12-03T08:07:09.000Z | libtensor/gen_block_tensor/impl/gen_block_tensor_impl.h | maxscheurer/libtensor | 288ed0596b24356d187d2fa40c05b0dacd00b413 | [
"BSL-1.0"
] | 12 | 2016-05-19T18:09:38.000Z | 2021-02-24T17:35:21.000Z | #ifndef LIBTENSOR_GEN_BLOCK_TENSOR_IMPL_H
#define LIBTENSOR_GEN_BLOCK_TENSOR_IMPL_H
#include <libutil/threads/auto_lock.h>
#include <libtensor/core/short_orbit.h>
#include "../gen_block_tensor.h"
namespace libtensor {
template<size_t N, typename BtTraits>
const char gen_block_tensor<N, BtTraits>::k_clazz[] =
"gen_block_tensor<N, BtTraits>";
template<size_t N, typename BtTraits>
gen_block_tensor<N, BtTraits>::gen_block_tensor(
const block_index_space<N> &bis) :
m_bis(bis),
m_bidims(bis.get_block_index_dims()),
m_symmetry(m_bis),
m_map(m_bis) {
}
template<size_t N, typename BtTraits>
gen_block_tensor<N, BtTraits>::~gen_block_tensor() {
}
template<size_t N, typename BtTraits>
const block_index_space<N> &gen_block_tensor<N, BtTraits>::get_bis() const {
return m_bis;
}
template<size_t N, typename BtTraits>
const typename gen_block_tensor<N, BtTraits>::symmetry_type&
gen_block_tensor<N, BtTraits>::on_req_const_symmetry() {
return m_symmetry;
}
template<size_t N, typename BtTraits>
typename gen_block_tensor<N, BtTraits>::symmetry_type&
gen_block_tensor<N, BtTraits>::on_req_symmetry() {
static const char method[] = "on_req_symmetry()";
libutil::auto_lock<libutil::mutex> lock(m_lock);
if(is_immutable()) {
throw immut_violation(g_ns, k_clazz, method, __FILE__, __LINE__,
"symmetry");
}
return m_symmetry;
}
template<size_t N, typename BtTraits>
typename gen_block_tensor<N, BtTraits>::rd_block_type&
gen_block_tensor<N, BtTraits>::on_req_const_block(const index<N> &idx) {
return get_block(idx, false);
}
template<size_t N, typename BtTraits>
void gen_block_tensor<N, BtTraits>::on_ret_const_block(const index<N> &idx) {
on_ret_block(idx);
}
template<size_t N, typename BtTraits>
typename gen_block_tensor<N, BtTraits>::wr_block_type&
gen_block_tensor<N, BtTraits>::on_req_block(const index<N> &idx) {
return get_block(idx, true);
}
template<size_t N, typename BtTraits>
void gen_block_tensor<N, BtTraits>::on_ret_block(const index<N> &idx) {
}
template<size_t N, typename BtTraits>
bool gen_block_tensor<N, BtTraits>::on_req_is_zero_block(const index<N> &idx) {
static const char method[] = "on_req_is_zero_block(const index<N>&)";
libutil::auto_lock<libutil::mutex> lock(m_lock);
if(!check_canonical_block(idx)) {
throw symmetry_violation(g_ns, k_clazz, method, __FILE__, __LINE__,
"Index does not correspond to a canonical block.");
}
return !m_map.contains(idx);
}
template<size_t N, typename BtTraits>
void gen_block_tensor<N, BtTraits>::on_req_nonzero_blocks(
std::vector<size_t> &nzlst) {
libutil::auto_lock<libutil::mutex> lock(m_lock);
m_map.get_all(nzlst);
}
template<size_t N, typename BtTraits>
void gen_block_tensor<N, BtTraits>::on_req_zero_block(const index<N> &idx) {
static const char method[] = "on_req_zero_block(const index<N>&)";
libutil::auto_lock<libutil::mutex> lock(m_lock);
if(is_immutable()) {
throw immut_violation(g_ns, k_clazz, method, __FILE__, __LINE__,
"Immutable object cannot be modified.");
}
if(!check_canonical_block(idx)) {
throw symmetry_violation(g_ns, k_clazz, method, __FILE__, __LINE__,
"Index does not correspond to a canonical block.");
}
m_map.remove(idx);
}
template<size_t N, typename BtTraits>
void gen_block_tensor<N, BtTraits>::on_req_zero_all_blocks() {
static const char method[] = "on_req_zero_all_blocks()";
libutil::auto_lock<libutil::mutex> lock(m_lock);
if(is_immutable()) {
throw immut_violation(g_ns, k_clazz, method, __FILE__, __LINE__,
"Immutable object cannot be modified.");
}
m_map.clear();
}
template<size_t N, typename BtTraits>
void gen_block_tensor<N, BtTraits>::on_set_immutable() {
libutil::auto_lock<libutil::mutex> lock(m_lock);
m_map.set_immutable();
}
template<size_t N, typename BtTraits>
bool gen_block_tensor<N, BtTraits>::check_canonical_block(
const index<N> &idx) {
#ifndef LIBTENSOR_DEBUG
// This check is fast, but not very robust. Disable it in the debug mode.
if(m_map.contains(idx)) return true;
#endif // LIBTENSOR_DEBUG
short_orbit<N, element_type> o(m_symmetry, idx, true);
return o.is_allowed() && o.get_cindex().equals(idx);
}
template<size_t N, typename BtTraits>
typename gen_block_tensor<N, BtTraits>::block_type&
gen_block_tensor<N, BtTraits>::get_block(const index<N> &idx, bool create) {
static const char method[] = "get_block(const index<N>&, bool)";
libutil::auto_lock<libutil::mutex> lock(m_lock);
if(!check_canonical_block(idx)) {
throw symmetry_violation(g_ns, k_clazz, method, __FILE__, __LINE__,
"Index does not correspond to a canonical block.");
}
if(!m_map.contains(idx)) {
if(create) {
m_map.create(idx);
} else {
throw symmetry_violation(g_ns, k_clazz, method, __FILE__, __LINE__,
"Block does not exist.");
}
}
return m_map.get(idx);
}
} // namespace libtensor
#endif // LIBTENSOR_GEN_BLOCK_TENSOR_IMPL_H
| 24.927885 | 79 | 0.706268 | [
"object",
"vector"
] |
4bd0bf1197a61420896b51c9ea8ff0d9c9df5f01 | 2,229 | h | C | Source/OCHamcrest.h | pivotalforks/OCHamcrest | ee0d886fc879e6d0c7c406b99d723eff2e577146 | [
"BSD-3-Clause"
] | 1 | 2015-11-09T00:07:51.000Z | 2015-11-09T00:07:51.000Z | Source/OCHamcrest.h | pivotalforks/OCHamcrest | ee0d886fc879e6d0c7c406b99d723eff2e577146 | [
"BSD-3-Clause"
] | null | null | null | Source/OCHamcrest.h | pivotalforks/OCHamcrest | ee0d886fc879e6d0c7c406b99d723eff2e577146 | [
"BSD-3-Clause"
] | null | null | null | //
// OCHamcrest - OCHamcrest.h
// Copyright 2011 hamcrest.org. See LICENSE.txt
//
// Created by: Jon Reid
//
/**
@defgroup library Matcher Library
Library of Matcher implementations
*/
/**
@defgroup core_matchers Core Matchers
Fundamental matchers of objects and values, and composite matchers
@ingroup library
*/
#import "HCAllOf.h"
#import "HCAnyOf.h"
#import "HCDescribedAs.h"
#import "HCIs.h"
#import "HCIsAnything.h"
#import "HCIsEqual.h"
#import "HCIsInstanceOf.h"
#import "HCIsNil.h"
#import "HCIsNot.h"
#import "HCIsSame.h"
/**
@defgroup collection_matchers Collection Matchers
Matchers of collections
@ingroup library
*/
#import "HCHasCount.h"
#import "HCIsCollectionContaining.h"
#import "HCIsCollectionContainingInAnyOrder.h"
#import "HCIsCollectionContainingInOrder.h"
#import "HCIsCollectionOnlyContaining.h"
#import "HCIsDictionaryContaining.h"
#import "HCIsDictionaryContainingEntries.h"
#import "HCIsDictionaryContainingKey.h"
#import "HCIsDictionaryContainingValue.h"
#import "HCIsEmptyCollection.h"
#import "HCIsIn.h"
/**
@defgroup number_matchers Number Matchers
Matchers that perform numeric comparisons
@ingroup library
*/
#import "HCIsCloseTo.h"
#import "HCOrderingComparison.h"
/**
@defgroup primitive_number_matchers Primitive Number Matchers
Matchers for testing equality against primitive numeric types
@ingroup number_matchers
*/
#import "HCIsEqualToNumber.h"
/**
@defgroup object_matchers Object Matchers
Matchers that inspect objects
@ingroup library
*/
#import "HCHasDescription.h"
/**
@defgroup text_matchers Text Matchers
Matchers that perform text comparisons
@ingroup library
*/
#import "HCIsEqualIgnoringCase.h"
#import "HCIsEqualIgnoringWhiteSpace.h"
#import "HCStringContains.h"
#import "HCStringEndsWith.h"
#import "HCStringStartsWith.h"
/**
@defgroup integration Unit Test Integration
*/
#import "HCAssertThat.h"
/**
@defgroup integration_numeric Unit Tests of Primitive Numbers
Unit test integration for primitive numbers
@ingroup integration
*/
#import "HCNumberAssert.h"
/**
@defgroup core Core API
*/
/**
@defgroup helpers Helpers
Utilities for writing Matchers
@ingroup core
*/
| 19.051282 | 67 | 0.756393 | [
"object"
] |
4bd2aed7b85e31008a44a031378cce0a02b0bbae | 624 | h | C | gameboard.h | l45lu/BB7K | b549eedb29265e6c7a8f52f8c44ba65dedf24179 | [
"MIT"
] | null | null | null | gameboard.h | l45lu/BB7K | b549eedb29265e6c7a8f52f8c44ba65dedf24179 | [
"MIT"
] | null | null | null | gameboard.h | l45lu/BB7K | b549eedb29265e6c7a8f52f8c44ba65dedf24179 | [
"MIT"
] | null | null | null | //
// gameboard.hpp
// bbk7000
//
// Created by Ethan Xie on 2015-11-26.
// Copyright © 2015 Ethan Xie. All rights reserved.
//
#ifndef GAMEBOARD_H
#define GAMEBOARD_H
#include "player.h"
#include "building.h"
#include <vector>
class Gameboard{
public:
int numPlayers;
Building *map[40];
std::vector <Player*> LandingPlayer;
Gameboard();
~Gameboard();
void addPlayer(Player *np);
void removePlayer(Player *np);
Player *getPlayer(char name);
Player *getnPlayer(std::string name);
Building *getBuilding(std::string name);
int getpositioninlp(std::string name);
};
#endif
| 17.828571 | 52 | 0.669872 | [
"vector"
] |
4bdb95698ebf2f3e6b102526e6cf7a4188c0a001 | 2,557 | h | C | Classes/NSNotificationCenter+ZYExtension.h | Eyshen/ios-zy-common | eea7631797b7898b5c4948bf2d8ed14d91697057 | [
"MIT"
] | null | null | null | Classes/NSNotificationCenter+ZYExtension.h | Eyshen/ios-zy-common | eea7631797b7898b5c4948bf2d8ed14d91697057 | [
"MIT"
] | null | null | null | Classes/NSNotificationCenter+ZYExtension.h | Eyshen/ios-zy-common | eea7631797b7898b5c4948bf2d8ed14d91697057 | [
"MIT"
] | null | null | null | //
// NSNotificationCenter+ZYExtension.h
//
// _______________ __
// /\______ / \ \ / /
// \/___ / / \ \ / /
// / / / \ \/ /
// / / / \/ /
// / / /______ / /
// / /__________\ / /
// /_____________/ \/
//
// Created by Eason.zhangyi on 16/1/4.
// Copyright © 2016年 ZY. All rights reserved.
//
#import <Foundation/Foundation.h>
//POST
#define ZY_NOTIFY_POST(notification) [NSNotificationCenter zy_postNotificationOnMainThread:notification]
#define ZY_NOTIFY_POST_WAIT(notification,wait) [NSNotificationCenter zy_postNotificationOnMainThread:notification waitUntilDone:wait]
#define ZY_NOTIFY_POST_NAME_OBJECT(name,object) [NSNotificationCenter zy_postNotificationOnMainThreadWithName:name object:object]
#define ZY_NOTIFY_POST_NAME_OBJECT_USERINFO(name,object,userInfo) [NSNotificationCenter zy_postNotificationOnMainThreadWithName:name object:object userInfo:userInfo]
#define ZY_NOTIFY_POST_NAME_OBJECT_USERINFO_WAIT(name,object,userInfo,wait) [NSNotificationCenter zy_postNotificationOnMainThreadWithName:name object:object userInfo:userInfo waitUntilDone:wait]
//REMOVE
#define ZY_NOTIFY_REMOVE(observer) [[NSNotificationCenter defaultCenter] removeObserver:observer]
#define ZY_NOTIFY_REMOVE_NAME_OBJECT(observer,name,object) [[NSNotificationCenter defaultCenter] removeObserver:observer name:name object:object]
//ADD
#define ZY_NOTIFY_ADD_OBSERVER(observer,selector,name,object) [[NSNotificationCenter defaultCenter] addObserver:observer selector:selector name:name object:object]
@interface NSNotificationCenter (ZYExtension)
+(void) zy_postNotificationOnMainThread:(NSNotification *)notification;
+(void) zy_postNotificationOnMainThread:(NSNotification *)notification
waitUntilDone:(BOOL)wait;
+(void) zy_postNotificationOnMainThreadWithName:(NSString *)name
object:(id)object;
+(void) zy_postNotificationOnMainThreadWithName:(NSString *)name
object:(id)object
userInfo:(NSDictionary *)userInfo;
+(void) zy_postNotificationOnMainThreadWithName:(NSString *)name
object:(id)object
userInfo:(NSDictionary *)userInfo
waitUntilDone:(BOOL)wait;
@end
| 46.490909 | 194 | 0.653109 | [
"object"
] |
4bdf5b41facebcee3a5c264904c038c31fb330da | 2,553 | h | C | numba/capsulethunk.h | auderson/numba | 3d67c9850ab56457f418cf40af6245fd9c337705 | [
"BSD-2-Clause"
] | 6,620 | 2015-01-04T08:51:04.000Z | 2022-03-31T12:52:18.000Z | numba/capsulethunk.h | auderson/numba | 3d67c9850ab56457f418cf40af6245fd9c337705 | [
"BSD-2-Clause"
] | 6,457 | 2015-01-04T03:18:41.000Z | 2022-03-31T17:38:42.000Z | numba/capsulethunk.h | auderson/numba | 3d67c9850ab56457f418cf40af6245fd9c337705 | [
"BSD-2-Clause"
] | 930 | 2015-01-25T02:33:03.000Z | 2022-03-30T14:10:32.000Z | /**
This is a modified version of capsulethunk.h for use in llvmpy
**/
#ifndef __CAPSULETHUNK_H
#define __CAPSULETHUNK_H
#if ( (PY_VERSION_HEX < 0x02070000) \
|| ((PY_VERSION_HEX >= 0x03000000) \
&& (PY_VERSION_HEX < 0x03010000)) )
//#define Assert(X) do_assert(!!(X), #X, __FILE__, __LINE__)
#define Assert(X)
static
void do_assert(int cond, const char * msg, const char *file, unsigned line){
if (!cond) {
fprintf(stderr, "Assertion failed %s:%d\n%s\n", file, line, msg);
exit(1);
}
}
typedef void (*PyCapsule_Destructor)(PyObject *);
struct FakePyCapsule_Desc {
const char *name;
void *context;
PyCapsule_Destructor dtor;
PyObject *parent;
FakePyCapsule_Desc() : name(0), context(0), dtor(0) {}
};
static
FakePyCapsule_Desc* get_pycobj_desc(PyObject *p){
void *desc = ((PyCObject*)p)->desc;
Assert(desc && "No desc in PyCObject");
return static_cast<FakePyCapsule_Desc*>(desc);
}
static
void pycobject_pycapsule_dtor(void *p, void *desc){
Assert(desc);
Assert(p);
FakePyCapsule_Desc *fpc_desc = static_cast<FakePyCapsule_Desc*>(desc);
Assert(fpc_desc->parent);
Assert(PyCObject_Check(fpc_desc->parent));
fpc_desc->dtor(static_cast<PyObject*>(fpc_desc->parent));
delete fpc_desc;
}
static
PyObject* PyCapsule_New(void* ptr, const char *name, PyCapsule_Destructor dtor)
{
FakePyCapsule_Desc *desc = new FakePyCapsule_Desc;
desc->name = name;
desc->context = NULL;
desc->dtor = dtor;
PyObject *p = PyCObject_FromVoidPtrAndDesc(ptr, desc,
pycobject_pycapsule_dtor);
desc->parent = p;
return p;
}
static
int PyCapsule_CheckExact(PyObject *p)
{
return PyCObject_Check(p);
}
static
void* PyCapsule_GetPointer(PyObject *p, const char *name)
{
Assert(PyCapsule_CheckExact(p));
if (strcmp(get_pycobj_desc(p)->name, name) != 0) {
PyErr_SetString(PyExc_ValueError, "Invalid PyCapsule object");
}
return PyCObject_AsVoidPtr(p);
}
static
void* PyCapsule_GetContext(PyObject *p)
{
Assert(p);
Assert(PyCapsule_CheckExact(p));
return get_pycobj_desc(p)->context;
}
static
int PyCapsule_SetContext(PyObject *p, void *context)
{
Assert(PyCapsule_CheckExact(p));
get_pycobj_desc(p)->context = context;
return 0;
}
static
const char * PyCapsule_GetName(PyObject *p)
{
// Assert(PyCapsule_CheckExact(p));
return get_pycobj_desc(p)->name;
}
#endif /* #if PY_VERSION_HEX < 0x02070000 */
#endif /* __CAPSULETHUNK_H */
| 23.422018 | 79 | 0.675676 | [
"object"
] |
4bdfd7060b2eb05eb8a11d38c9cdc4c5381a9152 | 797 | h | C | Population.h | s059ff/genetic-network-programming-python-package | 4fc6bf92787bcec738853496f7001c788f75f87b | [
"Unlicense"
] | 4 | 2018-06-30T17:48:39.000Z | 2021-07-16T13:12:47.000Z | Population.h | s059ff/genetic-network-programming-python-package | 4fc6bf92787bcec738853496f7001c788f75f87b | [
"Unlicense"
] | null | null | null | Population.h | s059ff/genetic-network-programming-python-package | 4fc6bf92787bcec738853496f7001c788f75f87b | [
"Unlicense"
] | 3 | 2018-06-12T02:30:53.000Z | 2020-03-26T15:23:06.000Z | #pragma once
#include <random>
#include <vector>
#include "GNPConfig.h"
#include "GNPTypes.h"
#include "Genome.h"
namespace gnp
{
// すべての遺伝子を表します。
class Population
{
public:
// このクラスのインスタンスを初期化します。
Population(const GNPConfig &config);
// 全個体に対して遺伝子操作を行い、世代を更新します。
void run(const GNPConfig &config);
// 指定されたファイルに個体群を保存します。
void serialize(const char *path, const GNPConfig &config) const;
// 指定されたファイルから個体群を復元します。
void deserialize(const char *path, const GNPConfig &config);
bool equal_to(const Population &other) const;
bool not_equal_to(const Population &other) const;
public:
// 遺伝子の集合。
std::vector<Genome> genomes;
private:
#ifndef _OPENMP
randomizer_t randomizer;
#else
std::vector<randomizer_t> randomizers;
#endif
};
}
| 18.113636 | 68 | 0.702635 | [
"vector"
] |
4bdff25c41ec2c22218908cb7b851ecec4db8734 | 2,616 | h | C | navigation_2d/nav2d_karto/OpenKarto/source/OpenKarto/TypeCasts.h | swsachith/tb3_rescue_bot | cd2bb81bede9f740c3316783474d68ae7e0b480a | [
"Apache-2.0"
] | 1 | 2021-05-17T11:13:01.000Z | 2021-05-17T11:13:01.000Z | src/nav2d_karto/OpenKarto/source/OpenKarto/TypeCasts.h | pplankton/MRSLAM | 0a16489a2cbd0c2d1511b506c540446cc670bde8 | [
"MIT"
] | null | null | null | src/nav2d_karto/OpenKarto/source/OpenKarto/TypeCasts.h | pplankton/MRSLAM | 0a16489a2cbd0c2d1511b506c540446cc670bde8 | [
"MIT"
] | 2 | 2018-11-16T16:14:18.000Z | 2018-11-27T22:55:07.000Z | /*
* Copyright (C) 2006-2011, SRI International (R)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __OpenKarto_TypeCasts_h__
#define __OpenKarto_TypeCasts_h__
#include <OpenKarto/Sensor.h>
#include <OpenKarto/SensorData.h>
#include <OpenKarto/Objects.h>
#include <OpenKarto/OccupancyGrid.h>
namespace karto
{
///** \addtogroup OpenKarto */
//@{
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
KARTO_TYPECHECKCAST(Sensor)
KARTO_TYPECHECKCAST(SensorData)
KARTO_TYPECHECKCAST(LaserRangeFinder)
KARTO_TYPECHECKCAST(Drive)
KARTO_TYPECHECKCAST(DrivePose)
KARTO_TYPECHECKCAST(LocalizedRangeScan)
KARTO_TYPECHECKCAST(LocalizedPointScan)
KARTO_TYPECHECKCAST(ModuleParameters)
KARTO_TYPECHECKCAST(DatasetInfo)
KARTO_TYPECHECKCAST(OccupancyGrid)
/**
* Determines whether a given object is a laser scan object
* @param pObject object in question
* @return whether the given object is a laser scan object
*/
inline kt_bool IsLocalizedLaserScan(Object* pObject)
{
return IsLocalizedRangeScan(pObject) || IsLocalizedPointScan(pObject);
}
#ifdef WIN32
#define EXPORT_KARTO_LIST(declspec, T) \
template class declspec karto::List<T>;
EXPORT_KARTO_LIST(KARTO_EXPORT, kt_double)
EXPORT_KARTO_LIST(KARTO_EXPORT, Pose2)
EXPORT_KARTO_LIST(KARTO_EXPORT, Vector2d)
EXPORT_KARTO_LIST(KARTO_EXPORT, SmartPointer<LocalizedLaserScan>)
EXPORT_KARTO_LIST(KARTO_EXPORT, SmartPointer<CustomItem>)
EXPORT_KARTO_LIST(KARTO_EXPORT, SmartPointer<Sensor>)
EXPORT_KARTO_LIST(KARTO_EXPORT, SmartPointer<AbstractParameter>)
EXPORT_KARTO_LIST(KARTO_EXPORT, SmartPointer<Object>)
#endif
//@}
}
#endif // __OpenKarto_TypeCasts_h__
| 34.421053 | 91 | 0.674694 | [
"object"
] |
4be3b415a3136374c5511bf6fe5b3d7da2a7c393 | 935 | h | C | Source/Game/LoginScreen.h | igorsegallafa/UrhoMMO | fd389d9722f32b0dc90dff746138213471503820 | [
"MIT"
] | 8 | 2020-02-06T13:14:13.000Z | 2020-11-03T06:26:04.000Z | Source/Game/LoginScreen.h | igorsegallafa/UrhoMMO | fd389d9722f32b0dc90dff746138213471503820 | [
"MIT"
] | null | null | null | Source/Game/LoginScreen.h | igorsegallafa/UrhoMMO | fd389d9722f32b0dc90dff746138213471503820 | [
"MIT"
] | 6 | 2019-06-19T00:24:16.000Z | 2020-12-08T05:03:59.000Z | #pragma once
#include "Screen.h"
class LoginScreen : public Screen
{
URHO3D_OBJECT( LoginScreen, Screen );
public:
//! Constructor.
LoginScreen( Context* context );
//! Deconstructor.
~LoginScreen();
//! Initialize Scene.
void Init() override;
//! Set Game Server List.
void SetWorldServerList( const Vector<String>& gameServerList );
private:
//! Create Scene.
void CreateScene();
//! Setup Viewport.
void SetupViewport();
//! Build Window.
void BuildWindow();
//! Screen Mode Handler.
void HandleScreenMode( StringHash eventType, VariantMap& eventData );
//! World Server Selected Handler.
void HandleWorldServerPressed( int serverIndex );
//! Login Button Handler.
void HandleLoginButtonPressed( StringHash eventType, VariantMap& eventData );
private:
SharedPtr<UIElement> loginWindow_;
SharedPtr<UIElement> worldServerWindow_;
}; | 22.804878 | 81 | 0.682353 | [
"vector"
] |
4be5920d9ad7daefae262fe319a256a1575f3563 | 1,701 | h | C | Dmf/Modules.Library/Dmf_NotifyUserWithEvent.h | harishsk/DMF | f2d58f500efbf2ee22c926f3a890f78e5d6278b0 | [
"MIT"
] | 130 | 2018-08-07T11:36:38.000Z | 2019-04-12T00:17:37.000Z | Dmf/Modules.Library/Dmf_NotifyUserWithEvent.h | harishsk/DMF | f2d58f500efbf2ee22c926f3a890f78e5d6278b0 | [
"MIT"
] | 12 | 2018-08-17T12:06:26.000Z | 2019-03-26T16:59:08.000Z | Dmf/Modules.Library/Dmf_NotifyUserWithEvent.h | harishsk/DMF | f2d58f500efbf2ee22c926f3a890f78e5d6278b0 | [
"MIT"
] | 21 | 2018-08-08T14:47:04.000Z | 2019-04-23T03:11:53.000Z | /*++
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT license.
Module Name:
Dmf_NotifyUserWithEvent.h
Abstract:
Companion file to Dmf_NotifyUserWithEvent.c.
Environment:
Kernel-mode Driver Framework
User-mode Driver Framework
--*/
#pragma once
// The maximum number of events that the Client Driver can create.
// Increase this value if necessary.
// Or, create multiple instances of this object, each with
// this maximum number of events.
//
#define NotifyUserWithEvent_MAXIMUM_EVENTS 4
// For Client Driver that just have a single event, allow them to use a simpler API.
//
#define NotifyUserWithEvent_DefaultIndex 0
// Client uses this structure to configure the Module specific parameters.
//
typedef struct
{
// Used for index validation.
//
ULONG MaximumEventIndex;
// The names of all events that are to be opened.
//
UNICODE_STRING EventNames[NotifyUserWithEvent_MAXIMUM_EVENTS];
} DMF_CONFIG_NotifyUserWithEvent;
// This macro declares the following functions:
// DMF_NotifyUserWithEvent_ATTRIBUTES_INIT()
// DMF_CONFIG_NotifyUserWithEvent_AND_ATTRIBUTES_INIT()
// DMF_NotifyUserWithEvent_Create()
//
DECLARE_DMF_MODULE(NotifyUserWithEvent)
// Module Methods
//
_IRQL_requires_max_(PASSIVE_LEVEL)
_Must_inspect_result_
NTSTATUS
Dmf_NotifyUserWithEvent_Notify(
_In_ DMFMODULE DmfModule
);
_IRQL_requires_max_(PASSIVE_LEVEL)
_Must_inspect_result_
NTSTATUS
Dmf_NotifyUserWithEvent_NotifyByIndex(
_In_ DMFMODULE DmfModule,
_In_ ULONG EventIndex
);
// eof: Dmf_NotifyUserWithEvent.h
//
| 23.30137 | 85 | 0.731922 | [
"object"
] |
4bedef9f8b4bd03c7ea82d08e47f385900421126 | 10,560 | h | C | include/CwAPI3D/ICwAPI3DMaterialController.h | CadworkMontreal/AxisImporter | b6e483239f02e3fa4afaed5cc52d2cca1ee256ae | [
"MIT"
] | null | null | null | include/CwAPI3D/ICwAPI3DMaterialController.h | CadworkMontreal/AxisImporter | b6e483239f02e3fa4afaed5cc52d2cca1ee256ae | [
"MIT"
] | null | null | null | include/CwAPI3D/ICwAPI3DMaterialController.h | CadworkMontreal/AxisImporter | b6e483239f02e3fa4afaed5cc52d2cca1ee256ae | [
"MIT"
] | null | null | null | /** @file
* Copyright (C) 2017 cadwork informatik AG
*
* This file is part of the CwAPI3D module for cadwork 3d.
*
* @ingroup CwAPI3D
* @since 24.0
* @author Paquet
* @date 2017-06-22
*/
#pragma once
#include "ICwAPI3DString.h"
#include "ICwAPI3DElementIDList.h"
#include "ICwAPI3DMaterialIDList.h"
namespace CwAPI3D
{
namespace Interfaces
{
/**
* @interface ICwAPI3DMaterialController
* \brief
*/
class ICwAPI3DMaterialController
{
public:
/**
* \brief Gets the last error
* \param aErrorCode error code
* \return error string
*/
virtual ICwAPI3DString* getLastError(int32_t* aErrorCode) = 0;
/**
* \brief Creates new material
* \param aName material name
* \return material ID
*/
virtual materialID createMaterial(const character* aName) = 0;
/**
* \brief Gets the material name
* \param aMaterialID material ID
* \return material name
*/
virtual ICwAPI3DString* getName(materialID aMaterialID) = 0;
/**
* \brief Sets the material name
* \param aMaterialID material ID
* \param aName material name
*/
virtual void setName(materialID aMaterialID, const character* aName) = 0;
/**
* \brief Gets the material group
* \param aMaterialID material ID
* \return material group
*/
virtual ICwAPI3DString* getGroup(materialID aMaterialID) = 0;
/**
* \brief Sets the material group
* \param aMaterialID material ID
* \param aGroup material group
*/
virtual void setGroup(materialID aMaterialID, const character* aGroup) = 0;
/**
* \brief Gets the material code
* \param aMaterialID material ID
* \return material code
*/
virtual ICwAPI3DString* getCode(materialID aMaterialID) = 0;
/**
* \brief Sets the material code
* \param aMaterialID material ID
* \param aCode material code
*/
virtual void setCode(materialID aMaterialID, const character* aCode) = 0;
/**
* \brief Gets the material modulus of elasticity 1
* \param aMaterialID material ID
* \return material modulus of elasticity 1
*/
virtual double getModulusElasticity1(materialID aMaterialID) = 0;
/**
* \brief Sets the material modulus of elasticity 1
* \param aMaterialID material ID
* \param aModulusElasticity1 material modulus of elasticity 1
*/
virtual void setModulusElasticity1(materialID aMaterialID, double aModulusElasticity1) = 0;
/**
* \brief Gets the material modulus of elasticity 2
* \param aMaterialID material ID
* \return material modulus of elasticity 2
*/
virtual double getModulusElasticity2(materialID aMaterialID) = 0;
/**
* \brief Sets the material modulus of elasticity 2
* \param aMaterialID material ID
* \param aModulusElasticity2 material modulus of elasticity 2
*/
virtual void setModulusElasticity2(materialID aMaterialID, double aModulusElasticity2) = 0;
/**
* \brief Gets the material modulus of elasticity 3
* \param aMaterialID material ID
* \return material modulus of elasticity 3
*/
virtual double getModulusElasticity3(materialID aMaterialID) = 0;
/**
* \brief Sets the material modulus of elasticity 3
* \param aMaterialID material ID
* \param aModulusElasticity3 material modulus of elasticity 3
*/
virtual void setModulusElasticity3(materialID aMaterialID, double aModulusElasticity3) = 0;
/**
* \brief Gets the material shear modulus 1
* \param aMaterialID material ID
* \return material shear modulus 1
*/
virtual double getShearModulus1(materialID aMaterialID) = 0;
/**
* \brief Sets the material shear modulus 1
* \param aMaterialID material ID
* \param aShearModulus1 material shear modulus 1
*/
virtual void setShearModulus1(materialID aMaterialID, double aShearModulus1) = 0;
/**
* \brief Gets the material shear modulus 2
* \param aMaterialID material ID
* \return material shear modulus 2
*/
virtual double getShearModulus2(materialID aMaterialID) = 0;
/**
* \brief Sets the material shear modulus 2
* \param aMaterialID material ID
* \param aShearModulus2 material shear modulus 2
*/
virtual void setShearModulus2(materialID aMaterialID, double aShearModulus2) = 0;
/**
* \brief Gets the material price
* \param aMaterialID material ID
* \return material price
*/
virtual double getPrice(materialID aMaterialID) = 0;
/**
* \brief Sets the material price
* \param aMaterialID material ID
* \param aPrice material price
*/
virtual void setPrice(materialID aMaterialID, double aPrice) = 0;
/**
* \brief Sets the material price type
* \param aMaterialID material ID
* \return material price type
*/
virtual ICwAPI3DString* getPriceType(materialID aMaterialID) = 0;
/**
* \brief Sets the material price type
* \param aMaterialID material ID
* \param aPriceType material price type
*/
virtual void setPriceType(materialID aMaterialID, const character* aPriceType) = 0;
/**
* \brief Gets the material thermal conductivity
* \param aMaterialID material ID
* \return material thermal conductivity
*/
virtual double getThermalConductivity(materialID aMaterialID) = 0;
/**
* \brief Sets the material thermal conductivity
* \param aMaterialID material ID
* \param aThermalConductivity material thermal conductivity
*/
virtual void setThermalConductivity(materialID aMaterialID, double aThermalConductivity) = 0;
/**
* \brief Gets the material heat capacity
* \param aMaterialID material ID
* \return material heat capacity
*/
virtual double getHeatCapacity(materialID aMaterialID) = 0;
/**
* \brief Sets the material heat capacity
* \param aMaterialID material ID
* \param aHeatCapacity material heat capacity
*/
virtual void setHeatCapacity(materialID aMaterialID, double aHeatCapacity) = 0;
/**
* \brief Gets the material U min
* \param aMaterialID material ID
* \return material U min
*/
virtual double getUMin(materialID aMaterialID) = 0;
/**
* \brief Sets the material U min
* \param aMaterialID material ID
* \param aUMin material U min
*/
virtual void setUMin(materialID aMaterialID, double aUMin) = 0;
/**
* \brief Gets the material U max
* \param aMaterialID material ID
* \return material U max
*/
virtual double getUMax(materialID aMaterialID) = 0;
/**
* \brief Sets the material U max
* \param aMaterialID material ID
* \param aUMax material U max
*/
virtual void setUMax(materialID aMaterialID, double aUMax) = 0;
/**
* \brief Gets the material fire resistance class
* \param aMaterialID material ID
* \return material fire resistance class
*/
virtual ICwAPI3DString* getFireResistanceClass(materialID aMaterialID) = 0;
/**
* \brief Sets the material fire resistance class
* \param aMaterialID material ID
* \param aFireResistanceClass material fire resistance class
*/
virtual void setFireResistanceClass(materialID aMaterialID, const character* aFireResistanceClass) = 0;
/**
* \brief Gets the material smoke class
* \param aMaterialID material ID
* \return material smoke class
*/
virtual ICwAPI3DString* getSmokeClass(materialID aMaterialID) = 0;
/**
* \brief Sets the material smoke class
* \param aMaterialID material ID
* \param aSmokeClass material smoke class
*/
virtual void setSmokeClass(materialID aMaterialID, const character* aSmokeClass) = 0;
/**
* \brief Gets the material drop forming class
* \param aMaterialID material ID
* \return material drop forming class
*/
virtual ICwAPI3DString* getDropFormingClass(materialID aMaterialID) = 0;
/**
* \brief Sets the material drop forming class
* \param aMaterialID material ID
* \param aDropFormingClass material drop forming class
*/
virtual void setDropFormingClass(materialID aMaterialID, const character* aDropFormingClass) = 0;
/**
* \brief Gets the material burn-off rate
* \param aMaterialID material ID
* \return material burn off rate
*/
virtual double getBurnOffRate(materialID aMaterialID) = 0;
/**
* \brief Sets the material burn-off rate
* \param aMaterialID material ID
* \param aBurnOffRate material burn off rate
*/
virtual void setBurnOffRate(materialID aMaterialID, double aBurnOffRate) = 0;
/**
* \brief Gets the material weight
* \param aMaterialID material ID
* \return material weight
*/
virtual double getWeight(materialID aMaterialID) = 0;
/**
* \brief Sets the material weight
* \param aMaterialID material ID
* \param aWeight material weight
*/
virtual void setWeight(materialID aMaterialID, double aWeight) = 0;
/**
* \brief Gets the material weight type
* \param aMaterialID material ID
* \return material weight type
*/
virtual ICwAPI3DString* getWeightType(materialID aMaterialID) = 0;
/**
* \brief Sets the material weight type
* \param aMaterialID material ID
* \param aWeightType material weight type
*/
virtual void setWeightType(materialID aMaterialID, const character* aWeightType) = 0;
/**
* \brief Gets the material with a given name
* \param aMaterialName material name
* \return material ID
*/
virtual materialID getMaterialID(const character* aMaterialName) = 0;
/**
* \brief Gets all the materials
* \return material ID list
*/
virtual ICwAPI3DMaterialIDList* getAllMaterials() = 0;
virtual void clearErrors() = 0;
};
}
}
| 35.675676 | 109 | 0.636458 | [
"3d"
] |
ef00dd910377c845598591702d0ae5769ae1f4bc | 17,108 | c | C | usr.lib/libkvm/kvm_proc.c | TheSledgeHammer/2.11BSD | fe61f0b9aaa273783cd027c7b5ec77e95ead2153 | [
"BSD-3-Clause"
] | 3 | 2021-05-04T17:09:06.000Z | 2021-10-04T07:19:26.000Z | usr.lib/libkvm/kvm_proc.c | TheSledgeHammer/2.11BSD | fe61f0b9aaa273783cd027c7b5ec77e95ead2153 | [
"BSD-3-Clause"
] | null | null | null | usr.lib/libkvm/kvm_proc.c | TheSledgeHammer/2.11BSD | fe61f0b9aaa273783cd027c7b5ec77e95ead2153 | [
"BSD-3-Clause"
] | null | null | null | /*-
* Copyright (c) 1989, 1992, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software developed by the Computer Systems
* Engineering group at Lawrence Berkeley Laboratory under DARPA contract
* BG 91-66 and contributed to Berkeley.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)kvm_proc.c 8.4 (Berkeley) 8/20/94";
#endif /* LIBC_SCCS and not lint */
/*
* Proc traversal interface for kvm. ps and w are (probably) the exclusive
* users of this code, so we've factored it out into a separate module.
* Thus, we keep this grunge out of the other kvm applications (i.e.,
* most other applications are interested only in open/close/read/nlist).
*/
#include <sys/param.h>
#include <sys/user.h>
#include <sys/proc.h>
#include <sys/exec.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/tty.h>
#include <sys/queue.h>
#include <unistd.h>
#include <nlist.h>
#include <kvm.h>
#include <vm/include/vm.h>
#include <vm/include/vm_param.h>
#include <vm/include/swap_pager.h>
#include <sys/sysctl.h>
#include <limits.h>
#include <db.h>
#include <paths.h>
#include "kvm_private.h"
static char *
kvm_readswap(kd, p, va, cnt)
kvm_t *kd;
const struct proc *p;
u_long va;
u_long *cnt;
{
register int ix;
register u_long addr, head;
register u_long offset, pagestart, sbstart, pgoff;
register off_t seekpoint;
struct vm_map_entry vme;
struct vm_object vmo;
struct pager_struct pager;
struct swpager swap;
struct swblock swb;
static char page[NBPG];
head = (u_long)&p->p_vmspace->vm_map.cl_header;
/*
* Look through the address map for the memory object
* that corresponds to the given virtual address.
* The header just has the entire valid range.
*/
addr = head;
while (1) {
if (kvm_read(kd, addr, (char *)&vme, sizeof(vme)) !=
sizeof(vme))
return (0);
if (va >= vme.start && va <= vme.end &&
vme.object.vm_object != 0)
break;
addr = (u_long)CIRCLEQ_NEXT(vme, cl_entry);
if (addr == 0 || addr == head)
return (0);
}
/*
* We found the right object -- follow shadow links.
*/
offset = va - vme.start + vme.offset;
addr = (u_long)vme.object.vm_object;
while (1) {
if (kvm_read(kd, addr, (char *)&vmo, sizeof(vmo)) !=
sizeof(vmo))
return (0);
addr = (u_long)vmo.shadow;
if (addr == 0)
break;
offset += vmo.shadow_offset;
}
if (vmo.pager == 0)
return (0);
offset += vmo.paging_offset;
/*
* Read in the pager info and make sure it's a swap device.
*/
addr = (u_long)vmo.pager;
if (kvm_read(kd, addr, (char *)&pager, sizeof(pager)) != sizeof(pager)
|| pager.pg_type != PG_SWAP)
return (0);
/*
* Read in the swap_pager private data, and compute the
* swap offset.
*/
addr = (u_long)pager.pg_data;
if (kvm_read(kd, addr, (char *)&swap, sizeof(swap)) != sizeof(swap))
return (0);
ix = offset / dbtob(swap.sw_bsize);
if (swap.sw_blocks == 0 || ix >= swap.sw_nblocks)
return (0);
addr = (u_long)&swap.sw_blocks[ix];
if (kvm_read(kd, addr, (char *)&swb, sizeof(swb)) != sizeof(swb))
return (0);
sbstart = (offset / dbtob(swap.sw_bsize)) * dbtob(swap.sw_bsize);
sbstart /= NBPG;
pagestart = offset / NBPG;
pgoff = pagestart - sbstart;
if (swb.swb_block == 0 || (swb.swb_mask & (1 << pgoff)) == 0)
return (0);
seekpoint = dbtob(swb.swb_block) + ctob(pgoff);
errno = 0;
if (lseek(kd->swfd, seekpoint, 0) == -1 && errno != 0)
return (0);
if (read(kd->swfd, page, sizeof(page)) != sizeof(page))
return (0);
offset %= NBPG;
*cnt = NBPG - offset;
return (&page[offset]);
}
#define KREAD(kd, addr, obj) \
(kvm_read(kd, addr, (char *)(obj), sizeof(*obj)) != sizeof(*obj))
/*
* Read proc's from memory file into buffer bp, which has space to hold
* at most maxcnt procs.
*/
static int
kvm_proclist(kd, what, arg, p, bp, maxcnt)
kvm_t *kd;
int what, arg;
struct proc *p;
struct kinfo_proc *bp;
int maxcnt;
{
register int cnt = 0;
struct eproc eproc;
struct pgrp pgrp;
struct session sess;
struct tty tty;
struct proc proc;
for (; cnt < maxcnt && p != 0; p = proc->p_nxt) {
if (KREAD(kd, (u_long)p, &proc)) {
_kvm_err(kd, kd->program, "can't read proc at %x", p);
return (-1);
}
if (KREAD(kd, (u_long)proc.p_cred, &eproc.e_pcred) == 0)
KREAD(kd, (u_long)eproc.e_pcred.pc_ucred, &eproc.e_ucred);
switch(what) {
case KERN_PROC_PID:
if (proc.p_pid != (pid_t)arg)
continue;
break;
case KERN_PROC_UID:
if (eproc.e_ucred.cr_uid != (uid_t)arg)
continue;
break;
case KERN_PROC_RUID:
if (eproc.e_pcred.p_ruid != (uid_t)arg)
continue;
break;
}
/*
* We're going to add another proc to the set. If this
* will overflow the buffer, assume the reason is because
* nprocs (or the proc list) is corrupt and declare an error.
*/
if (cnt >= maxcnt) {
_kvm_err(kd, kd->program, "nprocs corrupt");
return (-1);
}
/*
* gather eproc
*/
eproc.e_paddr = p;
if (KREAD(kd, (u_long)proc.p_pgrp, &pgrp)) {
_kvm_err(kd, kd->program, "can't read pgrp at %x",
proc.p_pgrp);
return (-1);
}
eproc.e_sess = pgrp.pg_session;
eproc.e_pgid = pgrp.pg_id;
eproc.e_jobc = pgrp.pg_jobc;
if (KREAD(kd, (u_long)pgrp.pg_session, &sess)) {
_kvm_err(kd, kd->program, "can't read session at %x",
pgrp.pg_session);
return (-1);
}
if ((proc.p_flag & P_CONTROLT) && sess.s_ttyp != NULL) {
if (KREAD(kd, (u_long)sess.s_ttyp, &tty)) {
_kvm_err(kd, kd->program,
"can't read tty at %x", sess.s_ttyp);
return (-1);
}
eproc.e_tdev = tty.t_dev;
eproc.e_tsess = tty.t_session;
if (tty.t_pgrp != NULL) {
if (KREAD(kd, (u_long)tty.t_pgrp, &pgrp)) {
_kvm_err(kd, kd->program,
"can't read tpgrp at &x",
tty.t_pgrp);
return (-1);
}
eproc.e_tpgid = pgrp.pg_id;
} else
eproc.e_tpgid = -1;
} else
eproc.e_tdev = NODEV;
eproc.e_flag = sess.s_ttyvp ? EPROC_CTTY : 0;
if (sess.s_leader == p)
eproc.e_flag |= EPROC_SLEADER;
if (proc.p_wmesg)
(void)kvm_read(kd, (u_long)proc.p_wmesg,
eproc.e_wmesg, WMESGLEN);
#ifdef sparc
(void)kvm_read(kd, (u_long)&proc.p_vmspace->vm_rssize,
(char *)&eproc.e_vm.vm_rssize,
sizeof(eproc.e_vm.vm_rssize));
(void)kvm_read(kd, (u_long)&proc.p_vmspace->vm_tsize,
(char *)&eproc.e_vm.vm_tsize,
3 * sizeof(eproc.e_vm.vm_rssize)); /* XXX */
#else
(void)kvm_read(kd, (u_long)proc.p_vmspace,
(char *)&eproc.e_vm, sizeof(eproc.e_vm));
#endif
eproc.e_xsize = eproc.e_xrssize = 0;
eproc.e_xccount = eproc.e_xswrss = 0;
switch (what) {
case KERN_PROC_PGRP:
if (eproc.e_pgid != (pid_t)arg)
continue;
break;
case KERN_PROC_TTY:
if ((proc.p_flag & P_CONTROLT) == 0 ||
eproc.e_tdev != (dev_t)arg)
continue;
break;
}
bcopy(&proc, &bp->kp_proc, sizeof(proc));
bcopy(&eproc, &bp->kp_eproc, sizeof(eproc));
++bp;
++cnt;
}
return (cnt);
}
/*
* Build proc info array by reading in proc list from a crash dump.
* Return number of procs read. maxcnt is the max we will read.
*/
static int
kvm_deadprocs(kd, what, arg, a_allproc, a_zombproc, maxcnt)
kvm_t *kd;
int what, arg;
u_long a_allproc;
u_long a_zombproc;
int maxcnt;
{
register struct kinfo_proc *bp = kd->procbase;
register int acnt, zcnt;
struct proc *p;
if (KREAD(kd, a_allproc, &p)) {
_kvm_err(kd, kd->program, "cannot read allproc");
return (-1);
}
acnt = kvm_proclist(kd, what, arg, p, bp, maxcnt);
if (acnt < 0)
return (acnt);
if (KREAD(kd, a_zombproc, &p)) {
_kvm_err(kd, kd->program, "cannot read zombproc");
return (-1);
}
zcnt = kvm_proclist(kd, what, arg, p, bp + acnt, maxcnt - acnt);
if (zcnt < 0)
zcnt = 0;
return (acnt + zcnt);
}
struct kinfo_proc *
kvm_getprocs(kd, op, arg, cnt)
kvm_t *kd;
int op, arg;
int *cnt;
{
int mib[4], size, st, nprocs;
if (kd->procbase != 0) {
free((void *)kd->procbase);
/*
* Clear this pointer in case this call fails. Otherwise,
* kvm_close() will free it again.
*/
kd->procbase = 0;
}
if (ISALIVE(kd)) {
size = 0;
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = op;
mib[3] = arg;
st = sysctl(mib, 4, NULL, &size, NULL, 0);
if (st == -1) {
_kvm_syserr(kd, kd->program, "kvm_getprocs");
return (0);
}
kd->procbase = (struct kinfo_proc *)_kvm_malloc(kd, size);
if (kd->procbase == 0)
return (0);
st = sysctl(mib, 4, kd->procbase, &size, NULL, 0);
if (st == -1) {
_kvm_syserr(kd, kd->program, "kvm_getprocs");
return (0);
}
if (size % sizeof(struct kinfo_proc) != 0) {
_kvm_err(kd, kd->program,
"proc size mismatch (%d total, %d chunks)",
size, sizeof(struct kinfo_proc));
return (0);
}
nprocs = size / sizeof(struct kinfo_proc);
} else {
struct nlist nl[4], *p;
nl[0].n_name = "_nprocs";
nl[1].n_name = "_allproc";
nl[2].n_name = "_zombproc";
nl[3].n_name = 0;
if (kvm_nlist(kd, nl) != 0) {
for (p = nl; p->n_type != 0; ++p)
;
_kvm_err(kd, kd->program,
"%s: no such symbol", p->n_name);
return (0);
}
if (KREAD(kd, nl[0].n_value, &nprocs)) {
_kvm_err(kd, kd->program, "can't read nprocs");
return (0);
}
size = nprocs * sizeof(struct kinfo_proc);
kd->procbase = (struct kinfo_proc *)_kvm_malloc(kd, size);
if (kd->procbase == 0)
return (0);
nprocs = kvm_deadprocs(kd, op, arg, nl[1].n_value,
nl[2].n_value, nprocs);
#ifdef notdef
size = nprocs * sizeof(struct kinfo_proc);
(void)realloc(kd->procbase, size);
#endif
}
*cnt = nprocs;
return (kd->procbase);
}
void
_kvm_freeprocs(kd)
kvm_t *kd;
{
if (kd->procbase) {
free(kd->procbase);
kd->procbase = 0;
}
}
void *
_kvm_realloc(kd, p, n)
kvm_t *kd;
void *p;
size_t n;
{
void *np = (void *)realloc(p, n);
if (np == 0)
_kvm_err(kd, kd->program, "out of memory");
return (np);
}
#ifndef MAX
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#endif
/*
* Read in an argument vector from the user address space of process p.
* addr if the user-space base address of narg null-terminated contiguous
* strings. This is used to read in both the command arguments and
* environment strings. Read at most maxcnt characters of strings.
*/
static char **
kvm_argv(kd, p, addr, narg, maxcnt)
kvm_t *kd;
struct proc *p;
register u_long addr;
register int narg;
register int maxcnt;
{
register char *cp;
register int len, cc;
register char **argv;
/*
* Check that there aren't an unreasonable number of agruments,
* and that the address is in user space.
*/
if (narg > 512 || addr < VM_MIN_ADDRESS || addr >= VM_MAXUSER_ADDRESS)
return (0);
if (kd->argv == 0) {
/*
* Try to avoid reallocs.
*/
kd->argc = MAX(narg + 1, 32);
kd->argv = (char **)_kvm_malloc(kd, kd->argc *
sizeof(*kd->argv));
if (kd->argv == 0)
return (0);
} else if (narg + 1 > kd->argc) {
kd->argc = MAX(2 * kd->argc, narg + 1);
kd->argv = (char **)_kvm_realloc(kd, kd->argv, kd->argc *
sizeof(*kd->argv));
if (kd->argv == 0)
return (0);
}
if (kd->argspc == 0) {
kd->argspc = (char *)_kvm_malloc(kd, NBPG);
if (kd->argspc == 0)
return (0);
kd->arglen = NBPG;
}
cp = kd->argspc;
argv = kd->argv;
*argv = cp;
len = 0;
/*
* Loop over pages, filling in the argument vector.
*/
while (addr < VM_MAXUSER_ADDRESS) {
cc = NBPG - (addr & PGOFSET);
if (maxcnt > 0 && cc > maxcnt - len)
cc = maxcnt - len;;
if (len + cc > kd->arglen) {
register int off;
register char **pp;
register char *op = kd->argspc;
kd->arglen *= 2;
kd->argspc = (char *)_kvm_realloc(kd, kd->argspc,
kd->arglen);
if (kd->argspc == 0)
return (0);
cp = &kd->argspc[len];
/*
* Adjust argv pointers in case realloc moved
* the string space.
*/
off = kd->argspc - op;
for (pp = kd->argv; pp < argv; ++pp)
*pp += off;
}
if (kvm_uread(kd, p, addr, cp, cc) != cc)
/* XXX */
return (0);
len += cc;
addr += cc;
if (maxcnt == 0 && len > 16 * NBPG)
/* sanity */
return (0);
while (--cc >= 0) {
if (*cp++ == 0) {
if (--narg <= 0) {
*++argv = 0;
return (kd->argv);
} else
*++argv = cp;
}
}
if (maxcnt > 0 && len >= maxcnt) {
/*
* We're stopping prematurely. Terminate the
* argv and current string.
*/
*++argv = 0;
*cp = 0;
return (kd->argv);
}
}
}
static void
ps_str_a(p, addr, n)
struct ps_strings *p;
u_long *addr;
int *n;
{
*addr = (u_long)p->ps_argvstr;
*n = p->ps_nargvstr;
}
static void
ps_str_e(p, addr, n)
struct ps_strings *p;
u_long *addr;
int *n;
{
*addr = (u_long)p->ps_envstr;
*n = p->ps_nenvstr;
}
/*
* Determine if the proc indicated by p is still active.
* This test is not 100% foolproof in theory, but chances of
* being wrong are very low.
*/
static int
proc_verify(kd, kernp, p)
kvm_t *kd;
u_long kernp;
const struct proc *p;
{
struct proc kernproc;
/*
* Just read in the whole proc. It's not that big relative
* to the cost of the read system call.
*/
if (kvm_read(kd, kernp, (char *)&kernproc, sizeof(kernproc)) !=
sizeof(kernproc))
return (0);
return (p->p_pid == kernproc.p_pid &&
(kernproc.p_stat != SZOMB || p->p_stat == SZOMB));
}
static char **
kvm_doargv(kd, kp, nchr, info)
kvm_t *kd;
const struct kinfo_proc *kp;
int nchr;
int (*info)(struct ps_strings*, u_long *, int *);
{
register const struct proc *p = &kp->kp_proc;
register char **ap;
u_long addr;
int cnt;
struct ps_strings arginfo;
/*
* Pointers are stored at the top of the user stack.
*/
if (p->p_stat == SZOMB ||
kvm_uread(kd, p, USRSTACK - sizeof(arginfo), (char *)&arginfo,
sizeof(arginfo)) != sizeof(arginfo))
return (0);
(*info)(&arginfo, &addr, &cnt);
ap = kvm_argv(kd, p, addr, cnt, nchr);
/*
* For live kernels, make sure this process didn't go away.
*/
if (ap != 0 && ISALIVE(kd) &&
!proc_verify(kd, (u_long)kp->kp_eproc.e_paddr, p))
ap = 0;
return (ap);
}
/*
* Get the command args. This code is now machine independent.
*/
char **
kvm_getargv(kd, kp, nchr)
kvm_t *kd;
const struct kinfo_proc *kp;
int nchr;
{
return (kvm_doargv(kd, kp, nchr, ps_str_a));
}
char **
kvm_getenvv(kd, kp, nchr)
kvm_t *kd;
const struct kinfo_proc *kp;
int nchr;
{
return (kvm_doargv(kd, kp, nchr, ps_str_e));
}
/*
* Read from user space. The user context is given by p.
*/
ssize_t
kvm_uread(kd, p, uva, buf, len)
kvm_t *kd;
register struct proc *p;
register u_long uva;
register char *buf;
register size_t len;
{
register char *cp;
cp = buf;
while (len > 0) {
u_long pa;
register int cc;
cc = _kvm_uvatop(kd, p, uva, &pa);
if (cc > 0) {
if (cc > len)
cc = len;
errno = 0;
if (lseek(kd->pmfd, (off_t)pa, 0) == -1 && errno != 0) {
_kvm_err(kd, 0, "invalid address (%x)", uva);
break;
}
cc = read(kd->pmfd, cp, cc);
if (cc < 0) {
_kvm_syserr(kd, 0, _PATH_MEM);
break;
} else if (cc < len) {
_kvm_err(kd, kd->program, "short read");
break;
}
} else if (ISALIVE(kd)) {
/* try swap */
register char *dp;
int cnt;
dp = kvm_readswap(kd, p, uva, &cnt);
if (dp == 0) {
_kvm_err(kd, 0, "invalid address (%x)", uva);
return (0);
}
cc = MIN(cnt, len);
bcopy(dp, cp, cc);
} else
break;
cp += cc;
uva += cc;
len -= cc;
}
return (ssize_t)(cp - buf);
}
| 24.19802 | 77 | 0.627893 | [
"object",
"vector"
] |
ef07aef87593907f8660ba962d6a43566ad27923 | 97,032 | c | C | usr/src/uts/common/os/cpu.c | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | null | null | null | usr/src/uts/common/os/cpu.c | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | null | null | null | usr/src/uts/common/os/cpu.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) 1991, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2012 by Delphix. All rights reserved.
* Copyright 2019 Joyent, Inc.
*/
/*
* Architecture-independent CPU control functions.
*/
#include <sys/types.h>
#include <sys/param.h>
#include <sys/var.h>
#include <sys/thread.h>
#include <sys/cpuvar.h>
#include <sys/cpu_event.h>
#include <sys/kstat.h>
#include <sys/uadmin.h>
#include <sys/systm.h>
#include <sys/errno.h>
#include <sys/cmn_err.h>
#include <sys/procset.h>
#include <sys/processor.h>
#include <sys/debug.h>
#include <sys/cpupart.h>
#include <sys/lgrp.h>
#include <sys/pset.h>
#include <sys/pghw.h>
#include <sys/kmem.h>
#include <sys/kmem_impl.h> /* to set per-cpu kmem_cache offset */
#include <sys/atomic.h>
#include <sys/callb.h>
#include <sys/vtrace.h>
#include <sys/cyclic.h>
#include <sys/bitmap.h>
#include <sys/nvpair.h>
#include <sys/pool_pset.h>
#include <sys/msacct.h>
#include <sys/time.h>
#include <sys/archsystm.h>
#include <sys/sdt.h>
#include <sys/smt.h>
#if defined(__x86) || defined(__amd64)
#include <sys/x86_archext.h>
#endif
#include <sys/callo.h>
extern int mp_cpu_start(cpu_t *);
extern int mp_cpu_stop(cpu_t *);
extern int mp_cpu_poweron(cpu_t *);
extern int mp_cpu_poweroff(cpu_t *);
extern int mp_cpu_configure(int);
extern int mp_cpu_unconfigure(int);
extern void mp_cpu_faulted_enter(cpu_t *);
extern void mp_cpu_faulted_exit(cpu_t *);
extern int cmp_cpu_to_chip(processorid_t cpuid);
#ifdef __sparcv9
extern char *cpu_fru_fmri(cpu_t *cp);
#endif
static void cpu_add_active_internal(cpu_t *cp);
static void cpu_remove_active(cpu_t *cp);
static void cpu_info_kstat_create(cpu_t *cp);
static void cpu_info_kstat_destroy(cpu_t *cp);
static void cpu_stats_kstat_create(cpu_t *cp);
static void cpu_stats_kstat_destroy(cpu_t *cp);
static int cpu_sys_stats_ks_update(kstat_t *ksp, int rw);
static int cpu_vm_stats_ks_update(kstat_t *ksp, int rw);
static int cpu_stat_ks_update(kstat_t *ksp, int rw);
static int cpu_state_change_hooks(int, cpu_setup_t, cpu_setup_t);
/*
* cpu_lock protects ncpus, ncpus_online, cpu_flag, cpu_list, cpu_active,
* max_cpu_seqid_ever, and dispatch queue reallocations. The lock ordering with
* respect to related locks is:
*
* cpu_lock --> thread_free_lock ---> p_lock ---> thread_lock()
*
* Warning: Certain sections of code do not use the cpu_lock when
* traversing the cpu_list (e.g. mutex_vector_enter(), clock()). Since
* all cpus are paused during modifications to this list, a solution
* to protect the list is too either disable kernel preemption while
* walking the list, *or* recheck the cpu_next pointer at each
* iteration in the loop. Note that in no cases can any cached
* copies of the cpu pointers be kept as they may become invalid.
*/
kmutex_t cpu_lock;
cpu_t *cpu_list; /* list of all CPUs */
cpu_t *clock_cpu_list; /* used by clock to walk CPUs */
cpu_t *cpu_active; /* list of active CPUs */
cpuset_t cpu_active_set; /* cached set of active CPUs */
static cpuset_t cpu_available; /* set of available CPUs */
cpuset_t cpu_seqid_inuse; /* which cpu_seqids are in use */
cpu_t **cpu_seq; /* ptrs to CPUs, indexed by seq_id */
/*
* max_ncpus keeps the max cpus the system can have. Initially
* it's NCPU, but since most archs scan the devtree for cpus
* fairly early on during boot, the real max can be known before
* ncpus is set (useful for early NCPU based allocations).
*/
int max_ncpus = NCPU;
/*
* platforms that set max_ncpus to maxiumum number of cpus that can be
* dynamically added will set boot_max_ncpus to the number of cpus found
* at device tree scan time during boot.
*/
int boot_max_ncpus = -1;
int boot_ncpus = -1;
/*
* Maximum possible CPU id. This can never be >= NCPU since NCPU is
* used to size arrays that are indexed by CPU id.
*/
processorid_t max_cpuid = NCPU - 1;
/*
* Maximum cpu_seqid was given. This number can only grow and never shrink. It
* can be used to optimize NCPU loops to avoid going through CPUs which were
* never on-line.
*/
processorid_t max_cpu_seqid_ever = 0;
int ncpus = 1;
int ncpus_online = 1;
int ncpus_intr_enabled = 1;
/*
* CPU that we're trying to offline. Protected by cpu_lock.
*/
cpu_t *cpu_inmotion;
/*
* Can be raised to suppress further weakbinding, which are instead
* satisfied by disabling preemption. Must be raised/lowered under cpu_lock,
* while individual thread weakbinding synchronization is done under thread
* lock.
*/
int weakbindingbarrier;
/*
* Variables used in pause_cpus().
*/
static volatile char safe_list[NCPU];
static struct _cpu_pause_info {
int cp_spl; /* spl saved in pause_cpus() */
volatile int cp_go; /* Go signal sent after all ready */
int cp_count; /* # of CPUs to pause */
ksema_t cp_sem; /* synch pause_cpus & cpu_pause */
kthread_id_t cp_paused;
void *(*cp_func)(void *);
} cpu_pause_info;
static kmutex_t pause_free_mutex;
static kcondvar_t pause_free_cv;
static struct cpu_sys_stats_ks_data {
kstat_named_t cpu_ticks_idle;
kstat_named_t cpu_ticks_user;
kstat_named_t cpu_ticks_kernel;
kstat_named_t cpu_ticks_wait;
kstat_named_t cpu_nsec_idle;
kstat_named_t cpu_nsec_user;
kstat_named_t cpu_nsec_kernel;
kstat_named_t cpu_nsec_dtrace;
kstat_named_t cpu_nsec_intr;
kstat_named_t cpu_load_intr;
kstat_named_t wait_ticks_io;
kstat_named_t dtrace_probes;
kstat_named_t bread;
kstat_named_t bwrite;
kstat_named_t lread;
kstat_named_t lwrite;
kstat_named_t phread;
kstat_named_t phwrite;
kstat_named_t pswitch;
kstat_named_t trap;
kstat_named_t intr;
kstat_named_t syscall;
kstat_named_t sysread;
kstat_named_t syswrite;
kstat_named_t sysfork;
kstat_named_t sysvfork;
kstat_named_t sysexec;
kstat_named_t readch;
kstat_named_t writech;
kstat_named_t rcvint;
kstat_named_t xmtint;
kstat_named_t mdmint;
kstat_named_t rawch;
kstat_named_t canch;
kstat_named_t outch;
kstat_named_t msg;
kstat_named_t sema;
kstat_named_t namei;
kstat_named_t ufsiget;
kstat_named_t ufsdirblk;
kstat_named_t ufsipage;
kstat_named_t ufsinopage;
kstat_named_t procovf;
kstat_named_t intrthread;
kstat_named_t intrblk;
kstat_named_t intrunpin;
kstat_named_t idlethread;
kstat_named_t inv_swtch;
kstat_named_t nthreads;
kstat_named_t cpumigrate;
kstat_named_t xcalls;
kstat_named_t mutex_adenters;
kstat_named_t rw_rdfails;
kstat_named_t rw_wrfails;
kstat_named_t modload;
kstat_named_t modunload;
kstat_named_t bawrite;
kstat_named_t iowait;
} cpu_sys_stats_ks_data_template = {
{ "cpu_ticks_idle", KSTAT_DATA_UINT64 },
{ "cpu_ticks_user", KSTAT_DATA_UINT64 },
{ "cpu_ticks_kernel", KSTAT_DATA_UINT64 },
{ "cpu_ticks_wait", KSTAT_DATA_UINT64 },
{ "cpu_nsec_idle", KSTAT_DATA_UINT64 },
{ "cpu_nsec_user", KSTAT_DATA_UINT64 },
{ "cpu_nsec_kernel", KSTAT_DATA_UINT64 },
{ "cpu_nsec_dtrace", KSTAT_DATA_UINT64 },
{ "cpu_nsec_intr", KSTAT_DATA_UINT64 },
{ "cpu_load_intr", KSTAT_DATA_UINT64 },
{ "wait_ticks_io", KSTAT_DATA_UINT64 },
{ "dtrace_probes", KSTAT_DATA_UINT64 },
{ "bread", KSTAT_DATA_UINT64 },
{ "bwrite", KSTAT_DATA_UINT64 },
{ "lread", KSTAT_DATA_UINT64 },
{ "lwrite", KSTAT_DATA_UINT64 },
{ "phread", KSTAT_DATA_UINT64 },
{ "phwrite", KSTAT_DATA_UINT64 },
{ "pswitch", KSTAT_DATA_UINT64 },
{ "trap", KSTAT_DATA_UINT64 },
{ "intr", KSTAT_DATA_UINT64 },
{ "syscall", KSTAT_DATA_UINT64 },
{ "sysread", KSTAT_DATA_UINT64 },
{ "syswrite", KSTAT_DATA_UINT64 },
{ "sysfork", KSTAT_DATA_UINT64 },
{ "sysvfork", KSTAT_DATA_UINT64 },
{ "sysexec", KSTAT_DATA_UINT64 },
{ "readch", KSTAT_DATA_UINT64 },
{ "writech", KSTAT_DATA_UINT64 },
{ "rcvint", KSTAT_DATA_UINT64 },
{ "xmtint", KSTAT_DATA_UINT64 },
{ "mdmint", KSTAT_DATA_UINT64 },
{ "rawch", KSTAT_DATA_UINT64 },
{ "canch", KSTAT_DATA_UINT64 },
{ "outch", KSTAT_DATA_UINT64 },
{ "msg", KSTAT_DATA_UINT64 },
{ "sema", KSTAT_DATA_UINT64 },
{ "namei", KSTAT_DATA_UINT64 },
{ "ufsiget", KSTAT_DATA_UINT64 },
{ "ufsdirblk", KSTAT_DATA_UINT64 },
{ "ufsipage", KSTAT_DATA_UINT64 },
{ "ufsinopage", KSTAT_DATA_UINT64 },
{ "procovf", KSTAT_DATA_UINT64 },
{ "intrthread", KSTAT_DATA_UINT64 },
{ "intrblk", KSTAT_DATA_UINT64 },
{ "intrunpin", KSTAT_DATA_UINT64 },
{ "idlethread", KSTAT_DATA_UINT64 },
{ "inv_swtch", KSTAT_DATA_UINT64 },
{ "nthreads", KSTAT_DATA_UINT64 },
{ "cpumigrate", KSTAT_DATA_UINT64 },
{ "xcalls", KSTAT_DATA_UINT64 },
{ "mutex_adenters", KSTAT_DATA_UINT64 },
{ "rw_rdfails", KSTAT_DATA_UINT64 },
{ "rw_wrfails", KSTAT_DATA_UINT64 },
{ "modload", KSTAT_DATA_UINT64 },
{ "modunload", KSTAT_DATA_UINT64 },
{ "bawrite", KSTAT_DATA_UINT64 },
{ "iowait", KSTAT_DATA_UINT64 },
};
static struct cpu_vm_stats_ks_data {
kstat_named_t pgrec;
kstat_named_t pgfrec;
kstat_named_t pgin;
kstat_named_t pgpgin;
kstat_named_t pgout;
kstat_named_t pgpgout;
kstat_named_t swapin;
kstat_named_t pgswapin;
kstat_named_t swapout;
kstat_named_t pgswapout;
kstat_named_t zfod;
kstat_named_t dfree;
kstat_named_t scan;
kstat_named_t rev;
kstat_named_t hat_fault;
kstat_named_t as_fault;
kstat_named_t maj_fault;
kstat_named_t cow_fault;
kstat_named_t prot_fault;
kstat_named_t softlock;
kstat_named_t kernel_asflt;
kstat_named_t pgrrun;
kstat_named_t execpgin;
kstat_named_t execpgout;
kstat_named_t execfree;
kstat_named_t anonpgin;
kstat_named_t anonpgout;
kstat_named_t anonfree;
kstat_named_t fspgin;
kstat_named_t fspgout;
kstat_named_t fsfree;
} cpu_vm_stats_ks_data_template = {
{ "pgrec", KSTAT_DATA_UINT64 },
{ "pgfrec", KSTAT_DATA_UINT64 },
{ "pgin", KSTAT_DATA_UINT64 },
{ "pgpgin", KSTAT_DATA_UINT64 },
{ "pgout", KSTAT_DATA_UINT64 },
{ "pgpgout", KSTAT_DATA_UINT64 },
{ "swapin", KSTAT_DATA_UINT64 },
{ "pgswapin", KSTAT_DATA_UINT64 },
{ "swapout", KSTAT_DATA_UINT64 },
{ "pgswapout", KSTAT_DATA_UINT64 },
{ "zfod", KSTAT_DATA_UINT64 },
{ "dfree", KSTAT_DATA_UINT64 },
{ "scan", KSTAT_DATA_UINT64 },
{ "rev", KSTAT_DATA_UINT64 },
{ "hat_fault", KSTAT_DATA_UINT64 },
{ "as_fault", KSTAT_DATA_UINT64 },
{ "maj_fault", KSTAT_DATA_UINT64 },
{ "cow_fault", KSTAT_DATA_UINT64 },
{ "prot_fault", KSTAT_DATA_UINT64 },
{ "softlock", KSTAT_DATA_UINT64 },
{ "kernel_asflt", KSTAT_DATA_UINT64 },
{ "pgrrun", KSTAT_DATA_UINT64 },
{ "execpgin", KSTAT_DATA_UINT64 },
{ "execpgout", KSTAT_DATA_UINT64 },
{ "execfree", KSTAT_DATA_UINT64 },
{ "anonpgin", KSTAT_DATA_UINT64 },
{ "anonpgout", KSTAT_DATA_UINT64 },
{ "anonfree", KSTAT_DATA_UINT64 },
{ "fspgin", KSTAT_DATA_UINT64 },
{ "fspgout", KSTAT_DATA_UINT64 },
{ "fsfree", KSTAT_DATA_UINT64 },
};
/*
* Force the specified thread to migrate to the appropriate processor.
* Called with thread lock held, returns with it dropped.
*/
static void
force_thread_migrate(kthread_id_t tp)
{
ASSERT(THREAD_LOCK_HELD(tp));
if (tp == curthread) {
THREAD_TRANSITION(tp);
CL_SETRUN(tp);
thread_unlock_nopreempt(tp);
swtch();
} else {
if (tp->t_state == TS_ONPROC) {
cpu_surrender(tp);
} else if (tp->t_state == TS_RUN) {
(void) dispdeq(tp);
setbackdq(tp);
}
thread_unlock(tp);
}
}
/*
* Set affinity for a specified CPU.
*
* Specifying a cpu_id of CPU_CURRENT, allowed _only_ when setting affinity for
* curthread, will set affinity to the CPU on which the thread is currently
* running. For other cpu_id values, the caller must ensure that the
* referenced CPU remains valid, which can be done by holding cpu_lock across
* this call.
*
* CPU affinity is guaranteed after return of thread_affinity_set(). If a
* caller setting affinity to CPU_CURRENT requires that its thread not migrate
* CPUs prior to a successful return, it should take extra precautions (such as
* their own call to kpreempt_disable) to ensure that safety.
*
* CPU_BEST can be used to pick a "best" CPU to migrate to, including
* potentially the current CPU.
*
* A CPU affinity reference count is maintained by thread_affinity_set and
* thread_affinity_clear (incrementing and decrementing it, respectively),
* maintaining CPU affinity while the count is non-zero, and allowing regions
* of code which require affinity to be nested.
*/
void
thread_affinity_set(kthread_id_t t, int cpu_id)
{
cpu_t *cp;
ASSERT(!(t == curthread && t->t_weakbound_cpu != NULL));
if (cpu_id == CPU_CURRENT) {
VERIFY3P(t, ==, curthread);
kpreempt_disable();
cp = CPU;
} else if (cpu_id == CPU_BEST) {
VERIFY3P(t, ==, curthread);
kpreempt_disable();
cp = disp_choose_best_cpu();
} else {
/*
* We should be asserting that cpu_lock is held here, but
* the NCA code doesn't acquire it. The following assert
* should be uncommented when the NCA code is fixed.
*
* ASSERT(MUTEX_HELD(&cpu_lock));
*/
VERIFY((cpu_id >= 0) && (cpu_id < NCPU));
cp = cpu[cpu_id];
/* user must provide a good cpu_id */
VERIFY(cp != NULL);
}
/*
* If there is already a hard affinity requested, and this affinity
* conflicts with that, panic.
*/
thread_lock(t);
if (t->t_affinitycnt > 0 && t->t_bound_cpu != cp) {
panic("affinity_set: setting %p but already bound to %p",
(void *)cp, (void *)t->t_bound_cpu);
}
t->t_affinitycnt++;
t->t_bound_cpu = cp;
/*
* Make sure we're running on the right CPU.
*/
if (cp != t->t_cpu || t != curthread) {
ASSERT(cpu_id != CPU_CURRENT);
force_thread_migrate(t); /* drops thread lock */
} else {
thread_unlock(t);
}
if (cpu_id == CPU_CURRENT || cpu_id == CPU_BEST)
kpreempt_enable();
}
/*
* Wrapper for backward compatibility.
*/
void
affinity_set(int cpu_id)
{
thread_affinity_set(curthread, cpu_id);
}
/*
* Decrement the affinity reservation count and if it becomes zero,
* clear the CPU affinity for the current thread, or set it to the user's
* software binding request.
*/
void
thread_affinity_clear(kthread_id_t t)
{
register processorid_t binding;
thread_lock(t);
if (--t->t_affinitycnt == 0) {
if ((binding = t->t_bind_cpu) == PBIND_NONE) {
/*
* Adjust disp_max_unbound_pri if necessary.
*/
disp_adjust_unbound_pri(t);
t->t_bound_cpu = NULL;
if (t->t_cpu->cpu_part != t->t_cpupart) {
force_thread_migrate(t);
return;
}
} else {
t->t_bound_cpu = cpu[binding];
/*
* Make sure the thread is running on the bound CPU.
*/
if (t->t_cpu != t->t_bound_cpu) {
force_thread_migrate(t);
return; /* already dropped lock */
}
}
}
thread_unlock(t);
}
/*
* Wrapper for backward compatibility.
*/
void
affinity_clear(void)
{
thread_affinity_clear(curthread);
}
/*
* Weak cpu affinity. Bind to the "current" cpu for short periods
* of time during which the thread must not block (but may be preempted).
* Use this instead of kpreempt_disable() when it is only "no migration"
* rather than "no preemption" semantics that are required - disabling
* preemption holds higher priority threads off of cpu and if the
* operation that is protected is more than momentary this is not good
* for realtime etc.
*
* Weakly bound threads will not prevent a cpu from being offlined -
* we'll only run them on the cpu to which they are weakly bound but
* (because they do not block) we'll always be able to move them on to
* another cpu at offline time if we give them just a short moment to
* run during which they will unbind. To give a cpu a chance of offlining,
* however, we require a barrier to weak bindings that may be raised for a
* given cpu (offline/move code may set this and then wait a short time for
* existing weak bindings to drop); the cpu_inmotion pointer is that barrier.
*
* There are few restrictions on the calling context of thread_nomigrate.
* The caller must not hold the thread lock. Calls may be nested.
*
* After weakbinding a thread must not perform actions that may block.
* In particular it must not call thread_affinity_set; calling that when
* already weakbound is nonsensical anyway.
*
* If curthread is prevented from migrating for other reasons
* (kernel preemption disabled; high pil; strongly bound; interrupt thread)
* then the weak binding will succeed even if this cpu is the target of an
* offline/move request.
*/
void
thread_nomigrate(void)
{
cpu_t *cp;
kthread_id_t t = curthread;
again:
kpreempt_disable();
cp = CPU;
/*
* A highlevel interrupt must not modify t_nomigrate or
* t_weakbound_cpu of the thread it has interrupted. A lowlevel
* interrupt thread cannot migrate and we can avoid the
* thread_lock call below by short-circuiting here. In either
* case we can just return since no migration is possible and
* the condition will persist (ie, when we test for these again
* in thread_allowmigrate they can't have changed). Migration
* is also impossible if we're at or above DISP_LEVEL pil.
*/
if (CPU_ON_INTR(cp) || t->t_flag & T_INTR_THREAD ||
getpil() >= DISP_LEVEL) {
kpreempt_enable();
return;
}
/*
* We must be consistent with existing weak bindings. Since we
* may be interrupted between the increment of t_nomigrate and
* the store to t_weakbound_cpu below we cannot assume that
* t_weakbound_cpu will be set if t_nomigrate is. Note that we
* cannot assert t_weakbound_cpu == t_bind_cpu since that is not
* always the case.
*/
if (t->t_nomigrate && t->t_weakbound_cpu && t->t_weakbound_cpu != cp) {
if (!panicstr)
panic("thread_nomigrate: binding to %p but already "
"bound to %p", (void *)cp,
(void *)t->t_weakbound_cpu);
}
/*
* At this point we have preemption disabled and we don't yet hold
* the thread lock. So it's possible that somebody else could
* set t_bind_cpu here and not be able to force us across to the
* new cpu (since we have preemption disabled).
*/
thread_lock(curthread);
/*
* If further weak bindings are being (temporarily) suppressed then
* we'll settle for disabling kernel preemption (which assures
* no migration provided the thread does not block which it is
* not allowed to if using thread_nomigrate). We must remember
* this disposition so we can take appropriate action in
* thread_allowmigrate. If this is a nested call and the
* thread is already weakbound then fall through as normal.
* We remember the decision to settle for kpreempt_disable through
* negative nesting counting in t_nomigrate. Once a thread has had one
* weakbinding request satisfied in this way any further (nested)
* requests will continue to be satisfied in the same way,
* even if weak bindings have recommenced.
*/
if (t->t_nomigrate < 0 || weakbindingbarrier && t->t_nomigrate == 0) {
--t->t_nomigrate;
thread_unlock(curthread);
return; /* with kpreempt_disable still active */
}
/*
* We hold thread_lock so t_bind_cpu cannot change. We could,
* however, be running on a different cpu to which we are t_bound_cpu
* to (as explained above). If we grant the weak binding request
* in that case then the dispatcher must favour our weak binding
* over our strong (in which case, just as when preemption is
* disabled, we can continue to run on a cpu other than the one to
* which we are strongbound; the difference in this case is that
* this thread can be preempted and so can appear on the dispatch
* queues of a cpu other than the one it is strongbound to).
*
* If the cpu we are running on does not appear to be a current
* offline target (we check cpu_inmotion to determine this - since
* we don't hold cpu_lock we may not see a recent store to that,
* so it's possible that we at times can grant a weak binding to a
* cpu that is an offline target, but that one request will not
* prevent the offline from succeeding) then we will always grant
* the weak binding request. This includes the case above where
* we grant a weakbinding not commensurate with our strong binding.
*
* If our cpu does appear to be an offline target then we're inclined
* not to grant the weakbinding request just yet - we'd prefer to
* migrate to another cpu and grant the request there. The
* exceptions are those cases where going through preemption code
* will not result in us changing cpu:
*
* . interrupts have already bypassed this case (see above)
* . we are already weakbound to this cpu (dispatcher code will
* always return us to the weakbound cpu)
* . preemption was disabled even before we disabled it above
* . we are strongbound to this cpu (if we're strongbound to
* another and not yet running there the trip through the
* dispatcher will move us to the strongbound cpu and we
* will grant the weak binding there)
*/
if (cp != cpu_inmotion || t->t_nomigrate > 0 || t->t_preempt > 1 ||
t->t_bound_cpu == cp) {
/*
* Don't be tempted to store to t_weakbound_cpu only on
* the first nested bind request - if we're interrupted
* after the increment of t_nomigrate and before the
* store to t_weakbound_cpu and the interrupt calls
* thread_nomigrate then the assertion in thread_allowmigrate
* would fail.
*/
t->t_nomigrate++;
t->t_weakbound_cpu = cp;
membar_producer();
thread_unlock(curthread);
/*
* Now that we have dropped the thread_lock another thread
* can set our t_weakbound_cpu, and will try to migrate us
* to the strongbound cpu (which will not be prevented by
* preemption being disabled since we're about to enable
* preemption). We have granted the weakbinding to the current
* cpu, so again we are in the position that is is is possible
* that our weak and strong bindings differ. Again this
* is catered for by dispatcher code which will favour our
* weak binding.
*/
kpreempt_enable();
} else {
/*
* Move to another cpu before granting the request by
* forcing this thread through preemption code. When we
* get to set{front,back}dq called from CL_PREEMPT()
* cpu_choose() will be used to select a cpu to queue
* us on - that will see cpu_inmotion and take
* steps to avoid returning us to this cpu.
*/
cp->cpu_kprunrun = 1;
thread_unlock(curthread);
kpreempt_enable(); /* will call preempt() */
goto again;
}
}
void
thread_allowmigrate(void)
{
kthread_id_t t = curthread;
ASSERT(t->t_weakbound_cpu == CPU ||
(t->t_nomigrate < 0 && t->t_preempt > 0) ||
CPU_ON_INTR(CPU) || t->t_flag & T_INTR_THREAD ||
getpil() >= DISP_LEVEL);
if (CPU_ON_INTR(CPU) || (t->t_flag & T_INTR_THREAD) ||
getpil() >= DISP_LEVEL)
return;
if (t->t_nomigrate < 0) {
/*
* This thread was granted "weak binding" in the
* stronger form of kernel preemption disabling.
* Undo a level of nesting for both t_nomigrate
* and t_preempt.
*/
++t->t_nomigrate;
kpreempt_enable();
} else if (--t->t_nomigrate == 0) {
/*
* Time to drop the weak binding. We need to cater
* for the case where we're weakbound to a different
* cpu than that to which we're strongbound (a very
* temporary arrangement that must only persist until
* weak binding drops). We don't acquire thread_lock
* here so even as this code executes t_bound_cpu
* may be changing. So we disable preemption and
* a) in the case that t_bound_cpu changes while we
* have preemption disabled kprunrun will be set
* asynchronously, and b) if before disabling
* preemption we were already on a different cpu to
* our t_bound_cpu then we set kprunrun ourselves
* to force a trip through the dispatcher when
* preemption is enabled.
*/
kpreempt_disable();
if (t->t_bound_cpu &&
t->t_weakbound_cpu != t->t_bound_cpu)
CPU->cpu_kprunrun = 1;
t->t_weakbound_cpu = NULL;
membar_producer();
kpreempt_enable();
}
}
/*
* weakbinding_stop can be used to temporarily cause weakbindings made
* with thread_nomigrate to be satisfied through the stronger action of
* kpreempt_disable. weakbinding_start recommences normal weakbinding.
*/
void
weakbinding_stop(void)
{
ASSERT(MUTEX_HELD(&cpu_lock));
weakbindingbarrier = 1;
membar_producer(); /* make visible before subsequent thread_lock */
}
void
weakbinding_start(void)
{
ASSERT(MUTEX_HELD(&cpu_lock));
weakbindingbarrier = 0;
}
void
null_xcall(void)
{
}
/*
* This routine is called to place the CPUs in a safe place so that
* one of them can be taken off line or placed on line. What we are
* trying to do here is prevent a thread from traversing the list
* of active CPUs while we are changing it or from getting placed on
* the run queue of a CPU that has just gone off line. We do this by
* creating a thread with the highest possible prio for each CPU and
* having it call this routine. The advantage of this method is that
* we can eliminate all checks for CPU_ACTIVE in the disp routines.
* This makes disp faster at the expense of making p_online() slower
* which is a good trade off.
*/
static void
cpu_pause(int index)
{
int s;
struct _cpu_pause_info *cpi = &cpu_pause_info;
volatile char *safe = &safe_list[index];
long lindex = index;
ASSERT((curthread->t_bound_cpu != NULL) || (*safe == PAUSE_DIE));
while (*safe != PAUSE_DIE) {
*safe = PAUSE_READY;
membar_enter(); /* make sure stores are flushed */
sema_v(&cpi->cp_sem); /* signal requesting thread */
/*
* Wait here until all pause threads are running. That
* indicates that it's safe to do the spl. Until
* cpu_pause_info.cp_go is set, we don't want to spl
* because that might block clock interrupts needed
* to preempt threads on other CPUs.
*/
while (cpi->cp_go == 0)
;
/*
* Even though we are at the highest disp prio, we need
* to block out all interrupts below LOCK_LEVEL so that
* an intr doesn't come in, wake up a thread, and call
* setbackdq/setfrontdq.
*/
s = splhigh();
/*
* if cp_func has been set then call it using index as the
* argument, currently only used by cpr_suspend_cpus().
* This function is used as the code to execute on the
* "paused" cpu's when a machine comes out of a sleep state
* and CPU's were powered off. (could also be used for
* hotplugging CPU's).
*/
if (cpi->cp_func != NULL)
(*cpi->cp_func)((void *)lindex);
mach_cpu_pause(safe);
splx(s);
/*
* Waiting is at an end. Switch out of cpu_pause
* loop and resume useful work.
*/
swtch();
}
mutex_enter(&pause_free_mutex);
*safe = PAUSE_DEAD;
cv_broadcast(&pause_free_cv);
mutex_exit(&pause_free_mutex);
}
/*
* Allow the cpus to start running again.
*/
void
start_cpus()
{
int i;
ASSERT(MUTEX_HELD(&cpu_lock));
ASSERT(cpu_pause_info.cp_paused);
cpu_pause_info.cp_paused = NULL;
for (i = 0; i < NCPU; i++)
safe_list[i] = PAUSE_IDLE;
membar_enter(); /* make sure stores are flushed */
affinity_clear();
splx(cpu_pause_info.cp_spl);
kpreempt_enable();
}
/*
* Allocate a pause thread for a CPU.
*/
static void
cpu_pause_alloc(cpu_t *cp)
{
kthread_id_t t;
long cpun = cp->cpu_id;
/*
* Note, v.v_nglobpris will not change value as long as I hold
* cpu_lock.
*/
t = thread_create(NULL, 0, cpu_pause, (void *)cpun,
0, &p0, TS_STOPPED, v.v_nglobpris - 1);
thread_lock(t);
t->t_bound_cpu = cp;
t->t_disp_queue = cp->cpu_disp;
t->t_affinitycnt = 1;
t->t_preempt = 1;
thread_unlock(t);
cp->cpu_pause_thread = t;
/*
* Registering a thread in the callback table is usually done
* in the initialization code of the thread. In this
* case, we do it right after thread creation because the
* thread itself may never run, and we need to register the
* fact that it is safe for cpr suspend.
*/
CALLB_CPR_INIT_SAFE(t, "cpu_pause");
}
/*
* Free a pause thread for a CPU.
*/
static void
cpu_pause_free(cpu_t *cp)
{
kthread_id_t t;
int cpun = cp->cpu_id;
ASSERT(MUTEX_HELD(&cpu_lock));
/*
* We have to get the thread and tell it to die.
*/
if ((t = cp->cpu_pause_thread) == NULL) {
ASSERT(safe_list[cpun] == PAUSE_IDLE);
return;
}
thread_lock(t);
t->t_cpu = CPU; /* disp gets upset if last cpu is quiesced. */
t->t_bound_cpu = NULL; /* Must un-bind; cpu may not be running. */
t->t_pri = v.v_nglobpris - 1;
ASSERT(safe_list[cpun] == PAUSE_IDLE);
safe_list[cpun] = PAUSE_DIE;
THREAD_TRANSITION(t);
setbackdq(t);
thread_unlock_nopreempt(t);
/*
* If we don't wait for the thread to actually die, it may try to
* run on the wrong cpu as part of an actual call to pause_cpus().
*/
mutex_enter(&pause_free_mutex);
while (safe_list[cpun] != PAUSE_DEAD) {
cv_wait(&pause_free_cv, &pause_free_mutex);
}
mutex_exit(&pause_free_mutex);
safe_list[cpun] = PAUSE_IDLE;
cp->cpu_pause_thread = NULL;
}
/*
* Initialize basic structures for pausing CPUs.
*/
void
cpu_pause_init()
{
sema_init(&cpu_pause_info.cp_sem, 0, NULL, SEMA_DEFAULT, NULL);
/*
* Create initial CPU pause thread.
*/
cpu_pause_alloc(CPU);
}
/*
* Start the threads used to pause another CPU.
*/
static int
cpu_pause_start(processorid_t cpu_id)
{
int i;
int cpu_count = 0;
for (i = 0; i < NCPU; i++) {
cpu_t *cp;
kthread_id_t t;
cp = cpu[i];
if (!CPU_IN_SET(cpu_available, i) || (i == cpu_id)) {
safe_list[i] = PAUSE_WAIT;
continue;
}
/*
* Skip CPU if it is quiesced or not yet started.
*/
if ((cp->cpu_flags & (CPU_QUIESCED | CPU_READY)) != CPU_READY) {
safe_list[i] = PAUSE_WAIT;
continue;
}
/*
* Start this CPU's pause thread.
*/
t = cp->cpu_pause_thread;
thread_lock(t);
/*
* Reset the priority, since nglobpris may have
* changed since the thread was created, if someone
* has loaded the RT (or some other) scheduling
* class.
*/
t->t_pri = v.v_nglobpris - 1;
THREAD_TRANSITION(t);
setbackdq(t);
thread_unlock_nopreempt(t);
++cpu_count;
}
return (cpu_count);
}
/*
* Pause all of the CPUs except the one we are on by creating a high
* priority thread bound to those CPUs.
*
* Note that one must be extremely careful regarding code
* executed while CPUs are paused. Since a CPU may be paused
* while a thread scheduling on that CPU is holding an adaptive
* lock, code executed with CPUs paused must not acquire adaptive
* (or low-level spin) locks. Also, such code must not block,
* since the thread that is supposed to initiate the wakeup may
* never run.
*
* With a few exceptions, the restrictions on code executed with CPUs
* paused match those for code executed at high-level interrupt
* context.
*/
void
pause_cpus(cpu_t *off_cp, void *(*func)(void *))
{
processorid_t cpu_id;
int i;
struct _cpu_pause_info *cpi = &cpu_pause_info;
ASSERT(MUTEX_HELD(&cpu_lock));
ASSERT(cpi->cp_paused == NULL);
cpi->cp_count = 0;
cpi->cp_go = 0;
for (i = 0; i < NCPU; i++)
safe_list[i] = PAUSE_IDLE;
kpreempt_disable();
cpi->cp_func = func;
/*
* If running on the cpu that is going offline, get off it.
* This is so that it won't be necessary to rechoose a CPU
* when done.
*/
if (CPU == off_cp)
cpu_id = off_cp->cpu_next_part->cpu_id;
else
cpu_id = CPU->cpu_id;
affinity_set(cpu_id);
/*
* Start the pause threads and record how many were started
*/
cpi->cp_count = cpu_pause_start(cpu_id);
/*
* Now wait for all CPUs to be running the pause thread.
*/
while (cpi->cp_count > 0) {
/*
* Spin reading the count without grabbing the disp
* lock to make sure we don't prevent the pause
* threads from getting the lock.
*/
while (sema_held(&cpi->cp_sem))
;
if (sema_tryp(&cpi->cp_sem))
--cpi->cp_count;
}
cpi->cp_go = 1; /* all have reached cpu_pause */
/*
* Now wait for all CPUs to spl. (Transition from PAUSE_READY
* to PAUSE_WAIT.)
*/
for (i = 0; i < NCPU; i++) {
while (safe_list[i] != PAUSE_WAIT)
;
}
cpi->cp_spl = splhigh(); /* block dispatcher on this CPU */
cpi->cp_paused = curthread;
}
/*
* Check whether the current thread has CPUs paused
*/
int
cpus_paused(void)
{
if (cpu_pause_info.cp_paused != NULL) {
ASSERT(cpu_pause_info.cp_paused == curthread);
return (1);
}
return (0);
}
static cpu_t *
cpu_get_all(processorid_t cpun)
{
ASSERT(MUTEX_HELD(&cpu_lock));
if (cpun >= NCPU || cpun < 0 || !CPU_IN_SET(cpu_available, cpun))
return (NULL);
return (cpu[cpun]);
}
/*
* Check whether cpun is a valid processor id and whether it should be
* visible from the current zone. If it is, return a pointer to the
* associated CPU structure.
*/
cpu_t *
cpu_get(processorid_t cpun)
{
cpu_t *c;
ASSERT(MUTEX_HELD(&cpu_lock));
c = cpu_get_all(cpun);
if (c != NULL && !INGLOBALZONE(curproc) && pool_pset_enabled() &&
zone_pset_get(curproc->p_zone) != cpupart_query_cpu(c))
return (NULL);
return (c);
}
/*
* The following functions should be used to check CPU states in the kernel.
* They should be invoked with cpu_lock held. Kernel subsystems interested
* in CPU states should *not* use cpu_get_state() and various P_ONLINE/etc
* states. Those are for user-land (and system call) use only.
*/
/*
* Determine whether the CPU is online and handling interrupts.
*/
int
cpu_is_online(cpu_t *cpu)
{
ASSERT(MUTEX_HELD(&cpu_lock));
return (cpu_flagged_online(cpu->cpu_flags));
}
/*
* Determine whether the CPU is offline (this includes spare and faulted).
*/
int
cpu_is_offline(cpu_t *cpu)
{
ASSERT(MUTEX_HELD(&cpu_lock));
return (cpu_flagged_offline(cpu->cpu_flags));
}
/*
* Determine whether the CPU is powered off.
*/
int
cpu_is_poweredoff(cpu_t *cpu)
{
ASSERT(MUTEX_HELD(&cpu_lock));
return (cpu_flagged_poweredoff(cpu->cpu_flags));
}
/*
* Determine whether the CPU is handling interrupts.
*/
int
cpu_is_nointr(cpu_t *cpu)
{
ASSERT(MUTEX_HELD(&cpu_lock));
return (cpu_flagged_nointr(cpu->cpu_flags));
}
/*
* Determine whether the CPU is active (scheduling threads).
*/
int
cpu_is_active(cpu_t *cpu)
{
ASSERT(MUTEX_HELD(&cpu_lock));
return (cpu_flagged_active(cpu->cpu_flags));
}
/*
* Same as above, but these require cpu_flags instead of cpu_t pointers.
*/
int
cpu_flagged_online(cpu_flag_t cpu_flags)
{
return (cpu_flagged_active(cpu_flags) &&
(cpu_flags & CPU_ENABLE));
}
int
cpu_flagged_offline(cpu_flag_t cpu_flags)
{
return (((cpu_flags & CPU_POWEROFF) == 0) &&
((cpu_flags & (CPU_READY | CPU_OFFLINE)) != CPU_READY));
}
int
cpu_flagged_poweredoff(cpu_flag_t cpu_flags)
{
return ((cpu_flags & CPU_POWEROFF) == CPU_POWEROFF);
}
int
cpu_flagged_nointr(cpu_flag_t cpu_flags)
{
return (cpu_flagged_active(cpu_flags) &&
(cpu_flags & CPU_ENABLE) == 0);
}
int
cpu_flagged_active(cpu_flag_t cpu_flags)
{
return (((cpu_flags & (CPU_POWEROFF | CPU_FAULTED | CPU_SPARE)) == 0) &&
((cpu_flags & (CPU_READY | CPU_OFFLINE)) == CPU_READY));
}
/*
* Bring the indicated CPU online.
*/
int
cpu_online(cpu_t *cp, int flags)
{
int error = 0;
/*
* Handle on-line request.
* This code must put the new CPU on the active list before
* starting it because it will not be paused, and will start
* using the active list immediately. The real start occurs
* when the CPU_QUIESCED flag is turned off.
*/
ASSERT(MUTEX_HELD(&cpu_lock));
if ((cp->cpu_flags & CPU_DISABLED) && !smt_can_enable(cp, flags))
return (EINVAL);
/*
* Put all the cpus into a known safe place.
* No mutexes can be entered while CPUs are paused.
*/
error = mp_cpu_start(cp); /* arch-dep hook */
if (error == 0) {
pg_cpupart_in(cp, cp->cpu_part);
pause_cpus(NULL, NULL);
cpu_add_active_internal(cp);
if (cp->cpu_flags & CPU_FAULTED) {
cp->cpu_flags &= ~CPU_FAULTED;
mp_cpu_faulted_exit(cp);
}
if (cp->cpu_flags & CPU_DISABLED)
smt_force_enabled();
cp->cpu_flags &= ~(CPU_QUIESCED | CPU_OFFLINE | CPU_FROZEN |
CPU_SPARE | CPU_DISABLED);
CPU_NEW_GENERATION(cp);
start_cpus();
cpu_stats_kstat_create(cp);
cpu_create_intrstat(cp);
lgrp_kstat_create(cp);
cpu_state_change_notify(cp->cpu_id, CPU_ON);
cpu_intr_enable(cp); /* arch-dep hook */
cpu_state_change_notify(cp->cpu_id, CPU_INTR_ON);
cpu_set_state(cp);
cyclic_online(cp);
/*
* This has to be called only after cyclic_online(). This
* function uses cyclics.
*/
callout_cpu_online(cp);
poke_cpu(cp->cpu_id);
}
return (error);
}
/*
* Take the indicated CPU offline.
*/
int
cpu_offline(cpu_t *cp, int flags)
{
cpupart_t *pp;
int error = 0;
cpu_t *ncp;
int intr_enable;
int cyclic_off = 0;
int callout_off = 0;
int loop_count;
int no_quiesce = 0;
int (*bound_func)(struct cpu *, int);
kthread_t *t;
lpl_t *cpu_lpl;
proc_t *p;
int lgrp_diff_lpl;
boolean_t forced = (flags & CPU_FORCED) != 0;
ASSERT(MUTEX_HELD(&cpu_lock));
if (cp->cpu_flags & CPU_DISABLED)
return (EINVAL);
/*
* If we're going from faulted or spare to offline, just
* clear these flags and update CPU state.
*/
if (cp->cpu_flags & (CPU_FAULTED | CPU_SPARE)) {
if (cp->cpu_flags & CPU_FAULTED) {
cp->cpu_flags &= ~CPU_FAULTED;
mp_cpu_faulted_exit(cp);
}
cp->cpu_flags &= ~CPU_SPARE;
cpu_set_state(cp);
return (0);
}
/*
* Handle off-line request.
*/
pp = cp->cpu_part;
/*
* Don't offline last online CPU in partition
*/
if (ncpus_online <= 1 || pp->cp_ncpus <= 1 || cpu_intr_count(cp) < 2)
return (EBUSY);
/*
* Unbind all soft-bound threads bound to our CPU and hard bound threads
* if we were asked to.
*/
error = cpu_unbind(cp->cpu_id, forced);
if (error != 0)
return (error);
/*
* We shouldn't be bound to this CPU ourselves.
*/
if (curthread->t_bound_cpu == cp)
return (EBUSY);
/*
* Tell interested parties that this CPU is going offline.
*/
CPU_NEW_GENERATION(cp);
cpu_state_change_notify(cp->cpu_id, CPU_OFF);
/*
* Tell the PG subsystem that the CPU is leaving the partition
*/
pg_cpupart_out(cp, pp);
/*
* Take the CPU out of interrupt participation so we won't find
* bound kernel threads. If the architecture cannot completely
* shut off interrupts on the CPU, don't quiesce it, but don't
* run anything but interrupt thread... this is indicated by
* the CPU_OFFLINE flag being on but the CPU_QUIESCE flag being
* off.
*/
intr_enable = cp->cpu_flags & CPU_ENABLE;
if (intr_enable)
no_quiesce = cpu_intr_disable(cp);
/*
* Record that we are aiming to offline this cpu. This acts as
* a barrier to further weak binding requests in thread_nomigrate
* and also causes cpu_choose, disp_lowpri_cpu and setfrontdq to
* lean away from this cpu. Further strong bindings are already
* avoided since we hold cpu_lock. Since threads that are set
* runnable around now and others coming off the target cpu are
* directed away from the target, existing strong and weak bindings
* (especially the latter) to the target cpu stand maximum chance of
* being able to unbind during the short delay loop below (if other
* unbound threads compete they may not see cpu in time to unbind
* even if they would do so immediately.
*/
cpu_inmotion = cp;
membar_enter();
/*
* Check for kernel threads (strong or weak) bound to that CPU.
* Strongly bound threads may not unbind, and we'll have to return
* EBUSY. Weakly bound threads should always disappear - we've
* stopped more weak binding with cpu_inmotion and existing
* bindings will drain imminently (they may not block). Nonetheless
* we will wait for a fixed period for all bound threads to disappear.
* Inactive interrupt threads are OK (they'll be in TS_FREE
* state). If test finds some bound threads, wait a few ticks
* to give short-lived threads (such as interrupts) chance to
* complete. Note that if no_quiesce is set, i.e. this cpu
* is required to service interrupts, then we take the route
* that permits interrupt threads to be active (or bypassed).
*/
bound_func = no_quiesce ? disp_bound_threads : disp_bound_anythreads;
again: for (loop_count = 0; (*bound_func)(cp, 0); loop_count++) {
if (loop_count >= 5) {
error = EBUSY; /* some threads still bound */
break;
}
/*
* If some threads were assigned, give them
* a chance to complete or move.
*
* This assumes that the clock_thread is not bound
* to any CPU, because the clock_thread is needed to
* do the delay(hz/100).
*
* Note: we still hold the cpu_lock while waiting for
* the next clock tick. This is OK since it isn't
* needed for anything else except processor_bind(2),
* and system initialization. If we drop the lock,
* we would risk another p_online disabling the last
* processor.
*/
delay(hz/100);
}
if (error == 0 && callout_off == 0) {
callout_cpu_offline(cp);
callout_off = 1;
}
if (error == 0 && cyclic_off == 0) {
if (!cyclic_offline(cp)) {
/*
* We must have bound cyclics...
*/
error = EBUSY;
goto out;
}
cyclic_off = 1;
}
/*
* Call mp_cpu_stop() to perform any special operations
* needed for this machine architecture to offline a CPU.
*/
if (error == 0)
error = mp_cpu_stop(cp); /* arch-dep hook */
/*
* If that all worked, take the CPU offline and decrement
* ncpus_online.
*/
if (error == 0) {
/*
* Put all the cpus into a known safe place.
* No mutexes can be entered while CPUs are paused.
*/
pause_cpus(cp, NULL);
/*
* Repeat the operation, if necessary, to make sure that
* all outstanding low-level interrupts run to completion
* before we set the CPU_QUIESCED flag. It's also possible
* that a thread has weak bound to the cpu despite our raising
* cpu_inmotion above since it may have loaded that
* value before the barrier became visible (this would have
* to be the thread that was on the target cpu at the time
* we raised the barrier).
*/
if ((!no_quiesce && cp->cpu_intr_actv != 0) ||
(*bound_func)(cp, 1)) {
start_cpus();
(void) mp_cpu_start(cp);
goto again;
}
ncp = cp->cpu_next_part;
cpu_lpl = cp->cpu_lpl;
ASSERT(cpu_lpl != NULL);
/*
* Remove the CPU from the list of active CPUs.
*/
cpu_remove_active(cp);
/*
* Walk the active process list and look for threads
* whose home lgroup needs to be updated, or
* the last CPU they run on is the one being offlined now.
*/
ASSERT(curthread->t_cpu != cp);
for (p = practive; p != NULL; p = p->p_next) {
t = p->p_tlist;
if (t == NULL)
continue;
lgrp_diff_lpl = 0;
do {
ASSERT(t->t_lpl != NULL);
/*
* Taking last CPU in lpl offline
* Rehome thread if it is in this lpl
* Otherwise, update the count of how many
* threads are in this CPU's lgroup but have
* a different lpl.
*/
if (cpu_lpl->lpl_ncpu == 0) {
if (t->t_lpl == cpu_lpl)
lgrp_move_thread(t,
lgrp_choose(t,
t->t_cpupart), 0);
else if (t->t_lpl->lpl_lgrpid ==
cpu_lpl->lpl_lgrpid)
lgrp_diff_lpl++;
}
ASSERT(t->t_lpl->lpl_ncpu > 0);
/*
* Update CPU last ran on if it was this CPU
*/
if (t->t_cpu == cp && t->t_bound_cpu != cp)
t->t_cpu = disp_lowpri_cpu(ncp, t,
t->t_pri);
ASSERT(t->t_cpu != cp || t->t_bound_cpu == cp ||
t->t_weakbound_cpu == cp);
t = t->t_forw;
} while (t != p->p_tlist);
/*
* Didn't find any threads in the same lgroup as this
* CPU with a different lpl, so remove the lgroup from
* the process lgroup bitmask.
*/
if (lgrp_diff_lpl == 0)
klgrpset_del(p->p_lgrpset, cpu_lpl->lpl_lgrpid);
}
/*
* Walk thread list looking for threads that need to be
* rehomed, since there are some threads that are not in
* their process's p_tlist.
*/
t = curthread;
do {
ASSERT(t != NULL && t->t_lpl != NULL);
/*
* Rehome threads with same lpl as this CPU when this
* is the last CPU in the lpl.
*/
if ((cpu_lpl->lpl_ncpu == 0) && (t->t_lpl == cpu_lpl))
lgrp_move_thread(t,
lgrp_choose(t, t->t_cpupart), 1);
ASSERT(t->t_lpl->lpl_ncpu > 0);
/*
* Update CPU last ran on if it was this CPU
*/
if (t->t_cpu == cp && t->t_bound_cpu != cp)
t->t_cpu = disp_lowpri_cpu(ncp, t, t->t_pri);
ASSERT(t->t_cpu != cp || t->t_bound_cpu == cp ||
t->t_weakbound_cpu == cp);
t = t->t_next;
} while (t != curthread);
ASSERT((cp->cpu_flags & (CPU_FAULTED | CPU_SPARE)) == 0);
cp->cpu_flags |= CPU_OFFLINE;
disp_cpu_inactive(cp);
if (!no_quiesce)
cp->cpu_flags |= CPU_QUIESCED;
ncpus_online--;
cpu_set_state(cp);
cpu_inmotion = NULL;
start_cpus();
cpu_stats_kstat_destroy(cp);
cpu_delete_intrstat(cp);
lgrp_kstat_destroy(cp);
}
out:
cpu_inmotion = NULL;
/*
* If we failed, re-enable interrupts.
* Do this even if cpu_intr_disable returned an error, because
* it may have partially disabled interrupts.
*/
if (error && intr_enable)
cpu_intr_enable(cp);
/*
* If we failed, but managed to offline the cyclic subsystem on this
* CPU, bring it back online.
*/
if (error && cyclic_off)
cyclic_online(cp);
/*
* If we failed, but managed to offline callouts on this CPU,
* bring it back online.
*/
if (error && callout_off)
callout_cpu_online(cp);
/*
* If we failed, tell the PG subsystem that the CPU is back
*/
pg_cpupart_in(cp, pp);
/*
* If we failed, we need to notify everyone that this CPU is back on.
*/
if (error != 0) {
CPU_NEW_GENERATION(cp);
cpu_state_change_notify(cp->cpu_id, CPU_ON);
cpu_state_change_notify(cp->cpu_id, CPU_INTR_ON);
}
return (error);
}
/*
* Mark the indicated CPU as faulted, taking it offline.
*/
int
cpu_faulted(cpu_t *cp, int flags)
{
int error = 0;
ASSERT(MUTEX_HELD(&cpu_lock));
ASSERT(!cpu_is_poweredoff(cp));
if (cp->cpu_flags & CPU_DISABLED)
return (EINVAL);
if (cpu_is_offline(cp)) {
cp->cpu_flags &= ~CPU_SPARE;
cp->cpu_flags |= CPU_FAULTED;
mp_cpu_faulted_enter(cp);
cpu_set_state(cp);
return (0);
}
if ((error = cpu_offline(cp, flags)) == 0) {
cp->cpu_flags |= CPU_FAULTED;
mp_cpu_faulted_enter(cp);
cpu_set_state(cp);
}
return (error);
}
/*
* Mark the indicated CPU as a spare, taking it offline.
*/
int
cpu_spare(cpu_t *cp, int flags)
{
int error = 0;
ASSERT(MUTEX_HELD(&cpu_lock));
ASSERT(!cpu_is_poweredoff(cp));
if (cp->cpu_flags & CPU_DISABLED)
return (EINVAL);
if (cpu_is_offline(cp)) {
if (cp->cpu_flags & CPU_FAULTED) {
cp->cpu_flags &= ~CPU_FAULTED;
mp_cpu_faulted_exit(cp);
}
cp->cpu_flags |= CPU_SPARE;
cpu_set_state(cp);
return (0);
}
if ((error = cpu_offline(cp, flags)) == 0) {
cp->cpu_flags |= CPU_SPARE;
cpu_set_state(cp);
}
return (error);
}
/*
* Take the indicated CPU from poweroff to offline.
*/
int
cpu_poweron(cpu_t *cp)
{
int error = ENOTSUP;
ASSERT(MUTEX_HELD(&cpu_lock));
ASSERT(cpu_is_poweredoff(cp));
error = mp_cpu_poweron(cp); /* arch-dep hook */
if (error == 0)
cpu_set_state(cp);
return (error);
}
/*
* Take the indicated CPU from any inactive state to powered off.
*/
int
cpu_poweroff(cpu_t *cp)
{
int error = ENOTSUP;
ASSERT(MUTEX_HELD(&cpu_lock));
ASSERT(cpu_is_offline(cp));
if (!(cp->cpu_flags & CPU_QUIESCED))
return (EBUSY); /* not completely idle */
error = mp_cpu_poweroff(cp); /* arch-dep hook */
if (error == 0)
cpu_set_state(cp);
return (error);
}
/*
* Initialize the Sequential CPU id lookup table
*/
void
cpu_seq_tbl_init()
{
cpu_t **tbl;
tbl = kmem_zalloc(sizeof (struct cpu *) * max_ncpus, KM_SLEEP);
tbl[0] = CPU;
cpu_seq = tbl;
}
/*
* Initialize the CPU lists for the first CPU.
*/
void
cpu_list_init(cpu_t *cp)
{
cp->cpu_next = cp;
cp->cpu_prev = cp;
cpu_list = cp;
clock_cpu_list = cp;
cp->cpu_next_onln = cp;
cp->cpu_prev_onln = cp;
cpu_active = cp;
cp->cpu_seqid = 0;
CPUSET_ADD(cpu_seqid_inuse, 0);
/*
* Bootstrap cpu_seq using cpu_list
* The cpu_seq[] table will be dynamically allocated
* when kmem later becomes available (but before going MP)
*/
cpu_seq = &cpu_list;
cp->cpu_cache_offset = KMEM_CPU_CACHE_OFFSET(cp->cpu_seqid);
cp_default.cp_cpulist = cp;
cp_default.cp_ncpus = 1;
cp->cpu_next_part = cp;
cp->cpu_prev_part = cp;
cp->cpu_part = &cp_default;
CPUSET_ADD(cpu_available, cp->cpu_id);
CPUSET_ADD(cpu_active_set, cp->cpu_id);
}
/*
* Insert a CPU into the list of available CPUs.
*/
void
cpu_add_unit(cpu_t *cp)
{
int seqid;
ASSERT(MUTEX_HELD(&cpu_lock));
ASSERT(cpu_list != NULL); /* list started in cpu_list_init */
lgrp_config(LGRP_CONFIG_CPU_ADD, (uintptr_t)cp, 0);
/*
* Note: most users of the cpu_list will grab the
* cpu_lock to insure that it isn't modified. However,
* certain users can't or won't do that. To allow this
* we pause the other cpus. Users who walk the list
* without cpu_lock, must disable kernel preemption
* to insure that the list isn't modified underneath
* them. Also, any cached pointers to cpu structures
* must be revalidated by checking to see if the
* cpu_next pointer points to itself. This check must
* be done with the cpu_lock held or kernel preemption
* disabled. This check relies upon the fact that
* old cpu structures are not free'ed or cleared after
* then are removed from the cpu_list.
*
* Note that the clock code walks the cpu list dereferencing
* the cpu_part pointer, so we need to initialize it before
* adding the cpu to the list.
*/
cp->cpu_part = &cp_default;
pause_cpus(NULL, NULL);
cp->cpu_next = cpu_list;
cp->cpu_prev = cpu_list->cpu_prev;
cpu_list->cpu_prev->cpu_next = cp;
cpu_list->cpu_prev = cp;
start_cpus();
for (seqid = 0; CPU_IN_SET(cpu_seqid_inuse, seqid); seqid++)
continue;
CPUSET_ADD(cpu_seqid_inuse, seqid);
cp->cpu_seqid = seqid;
if (seqid > max_cpu_seqid_ever)
max_cpu_seqid_ever = seqid;
ASSERT(ncpus < max_ncpus);
ncpus++;
cp->cpu_cache_offset = KMEM_CPU_CACHE_OFFSET(cp->cpu_seqid);
cpu[cp->cpu_id] = cp;
CPUSET_ADD(cpu_available, cp->cpu_id);
cpu_seq[cp->cpu_seqid] = cp;
/*
* allocate a pause thread for this CPU.
*/
cpu_pause_alloc(cp);
/*
* So that new CPUs won't have NULL prev_onln and next_onln pointers,
* link them into a list of just that CPU.
* This is so that disp_lowpri_cpu will work for thread_create in
* pause_cpus() when called from the startup thread in a new CPU.
*/
cp->cpu_next_onln = cp;
cp->cpu_prev_onln = cp;
cpu_info_kstat_create(cp);
cp->cpu_next_part = cp;
cp->cpu_prev_part = cp;
init_cpu_mstate(cp, CMS_SYSTEM);
pool_pset_mod = gethrtime();
}
/*
* Do the opposite of cpu_add_unit().
*/
void
cpu_del_unit(int cpuid)
{
struct cpu *cp, *cpnext;
ASSERT(MUTEX_HELD(&cpu_lock));
cp = cpu[cpuid];
ASSERT(cp != NULL);
ASSERT(cp->cpu_next_onln == cp);
ASSERT(cp->cpu_prev_onln == cp);
ASSERT(cp->cpu_next_part == cp);
ASSERT(cp->cpu_prev_part == cp);
/*
* Tear down the CPU's physical ID cache, and update any
* processor groups
*/
pg_cpu_fini(cp, NULL);
pghw_physid_destroy(cp);
/*
* Destroy kstat stuff.
*/
cpu_info_kstat_destroy(cp);
term_cpu_mstate(cp);
/*
* Free up pause thread.
*/
cpu_pause_free(cp);
CPUSET_DEL(cpu_available, cp->cpu_id);
cpu[cp->cpu_id] = NULL;
cpu_seq[cp->cpu_seqid] = NULL;
/*
* The clock thread and mutex_vector_enter cannot hold the
* cpu_lock while traversing the cpu list, therefore we pause
* all other threads by pausing the other cpus. These, and any
* other routines holding cpu pointers while possibly sleeping
* must be sure to call kpreempt_disable before processing the
* list and be sure to check that the cpu has not been deleted
* after any sleeps (check cp->cpu_next != NULL). We guarantee
* to keep the deleted cpu structure around.
*
* Note that this MUST be done AFTER cpu_available
* has been updated so that we don't waste time
* trying to pause the cpu we're trying to delete.
*/
pause_cpus(NULL, NULL);
cpnext = cp->cpu_next;
cp->cpu_prev->cpu_next = cp->cpu_next;
cp->cpu_next->cpu_prev = cp->cpu_prev;
if (cp == cpu_list)
cpu_list = cpnext;
/*
* Signals that the cpu has been deleted (see above).
*/
cp->cpu_next = NULL;
cp->cpu_prev = NULL;
start_cpus();
CPUSET_DEL(cpu_seqid_inuse, cp->cpu_seqid);
ncpus--;
lgrp_config(LGRP_CONFIG_CPU_DEL, (uintptr_t)cp, 0);
pool_pset_mod = gethrtime();
}
/*
* Add a CPU to the list of active CPUs.
* This routine must not get any locks, because other CPUs are paused.
*/
static void
cpu_add_active_internal(cpu_t *cp)
{
cpupart_t *pp = cp->cpu_part;
ASSERT(MUTEX_HELD(&cpu_lock));
ASSERT(cpu_list != NULL); /* list started in cpu_list_init */
ncpus_online++;
cpu_set_state(cp);
cp->cpu_next_onln = cpu_active;
cp->cpu_prev_onln = cpu_active->cpu_prev_onln;
cpu_active->cpu_prev_onln->cpu_next_onln = cp;
cpu_active->cpu_prev_onln = cp;
CPUSET_ADD(cpu_active_set, cp->cpu_id);
if (pp->cp_cpulist) {
cp->cpu_next_part = pp->cp_cpulist;
cp->cpu_prev_part = pp->cp_cpulist->cpu_prev_part;
pp->cp_cpulist->cpu_prev_part->cpu_next_part = cp;
pp->cp_cpulist->cpu_prev_part = cp;
} else {
ASSERT(pp->cp_ncpus == 0);
pp->cp_cpulist = cp->cpu_next_part = cp->cpu_prev_part = cp;
}
pp->cp_ncpus++;
if (pp->cp_ncpus == 1) {
cp_numparts_nonempty++;
ASSERT(cp_numparts_nonempty != 0);
}
pg_cpu_active(cp);
lgrp_config(LGRP_CONFIG_CPU_ONLINE, (uintptr_t)cp, 0);
bzero(&cp->cpu_loadavg, sizeof (cp->cpu_loadavg));
}
/*
* Add a CPU to the list of active CPUs.
* This is called from machine-dependent layers when a new CPU is started.
*/
void
cpu_add_active(cpu_t *cp)
{
pg_cpupart_in(cp, cp->cpu_part);
pause_cpus(NULL, NULL);
cpu_add_active_internal(cp);
start_cpus();
cpu_stats_kstat_create(cp);
cpu_create_intrstat(cp);
lgrp_kstat_create(cp);
cpu_state_change_notify(cp->cpu_id, CPU_INIT);
}
/*
* Remove a CPU from the list of active CPUs.
* This routine must not get any locks, because other CPUs are paused.
*/
/* ARGSUSED */
static void
cpu_remove_active(cpu_t *cp)
{
cpupart_t *pp = cp->cpu_part;
ASSERT(MUTEX_HELD(&cpu_lock));
ASSERT(cp->cpu_next_onln != cp); /* not the last one */
ASSERT(cp->cpu_prev_onln != cp); /* not the last one */
pg_cpu_inactive(cp);
lgrp_config(LGRP_CONFIG_CPU_OFFLINE, (uintptr_t)cp, 0);
if (cp == clock_cpu_list)
clock_cpu_list = cp->cpu_next_onln;
cp->cpu_prev_onln->cpu_next_onln = cp->cpu_next_onln;
cp->cpu_next_onln->cpu_prev_onln = cp->cpu_prev_onln;
if (cpu_active == cp) {
cpu_active = cp->cpu_next_onln;
}
cp->cpu_next_onln = cp;
cp->cpu_prev_onln = cp;
CPUSET_DEL(cpu_active_set, cp->cpu_id);
cp->cpu_prev_part->cpu_next_part = cp->cpu_next_part;
cp->cpu_next_part->cpu_prev_part = cp->cpu_prev_part;
if (pp->cp_cpulist == cp) {
pp->cp_cpulist = cp->cpu_next_part;
ASSERT(pp->cp_cpulist != cp);
}
cp->cpu_next_part = cp;
cp->cpu_prev_part = cp;
pp->cp_ncpus--;
if (pp->cp_ncpus == 0) {
cp_numparts_nonempty--;
ASSERT(cp_numparts_nonempty != 0);
}
}
/*
* Routine used to setup a newly inserted CPU in preparation for starting
* it running code.
*/
int
cpu_configure(int cpuid)
{
int retval = 0;
ASSERT(MUTEX_HELD(&cpu_lock));
/*
* Some structures are statically allocated based upon
* the maximum number of cpus the system supports. Do not
* try to add anything beyond this limit.
*/
if (cpuid < 0 || cpuid >= NCPU) {
return (EINVAL);
}
if ((cpu[cpuid] != NULL) && (cpu[cpuid]->cpu_flags != 0)) {
return (EALREADY);
}
if ((retval = mp_cpu_configure(cpuid)) != 0) {
return (retval);
}
cpu[cpuid]->cpu_flags = CPU_QUIESCED | CPU_OFFLINE | CPU_POWEROFF;
cpu_set_state(cpu[cpuid]);
retval = cpu_state_change_hooks(cpuid, CPU_CONFIG, CPU_UNCONFIG);
if (retval != 0)
(void) mp_cpu_unconfigure(cpuid);
return (retval);
}
/*
* Routine used to cleanup a CPU that has been powered off. This will
* destroy all per-cpu information related to this cpu.
*/
int
cpu_unconfigure(int cpuid)
{
int error;
ASSERT(MUTEX_HELD(&cpu_lock));
if (cpu[cpuid] == NULL) {
return (ENODEV);
}
if (cpu[cpuid]->cpu_flags == 0) {
return (EALREADY);
}
if ((cpu[cpuid]->cpu_flags & CPU_POWEROFF) == 0) {
return (EBUSY);
}
if (cpu[cpuid]->cpu_props != NULL) {
(void) nvlist_free(cpu[cpuid]->cpu_props);
cpu[cpuid]->cpu_props = NULL;
}
error = cpu_state_change_hooks(cpuid, CPU_UNCONFIG, CPU_CONFIG);
if (error != 0)
return (error);
return (mp_cpu_unconfigure(cpuid));
}
/*
* Routines for registering and de-registering cpu_setup callback functions.
*
* Caller's context
* These routines must not be called from a driver's attach(9E) or
* detach(9E) entry point.
*
* NOTE: CPU callbacks should not block. They are called with cpu_lock held.
*/
/*
* Ideally, these would be dynamically allocated and put into a linked
* list; however that is not feasible because the registration routine
* has to be available before the kmem allocator is working (in fact,
* it is called by the kmem allocator init code). In any case, there
* are quite a few extra entries for future users.
*/
#define NCPU_SETUPS 20
struct cpu_setup {
cpu_setup_func_t *func;
void *arg;
} cpu_setups[NCPU_SETUPS];
void
register_cpu_setup_func(cpu_setup_func_t *func, void *arg)
{
int i;
ASSERT(MUTEX_HELD(&cpu_lock));
for (i = 0; i < NCPU_SETUPS; i++)
if (cpu_setups[i].func == NULL)
break;
if (i >= NCPU_SETUPS)
cmn_err(CE_PANIC, "Ran out of cpu_setup callback entries");
cpu_setups[i].func = func;
cpu_setups[i].arg = arg;
}
void
unregister_cpu_setup_func(cpu_setup_func_t *func, void *arg)
{
int i;
ASSERT(MUTEX_HELD(&cpu_lock));
for (i = 0; i < NCPU_SETUPS; i++)
if ((cpu_setups[i].func == func) &&
(cpu_setups[i].arg == arg))
break;
if (i >= NCPU_SETUPS)
cmn_err(CE_PANIC, "Could not find cpu_setup callback to "
"deregister");
cpu_setups[i].func = NULL;
cpu_setups[i].arg = 0;
}
/*
* Call any state change hooks for this CPU, ignore any errors.
*/
void
cpu_state_change_notify(int id, cpu_setup_t what)
{
int i;
ASSERT(MUTEX_HELD(&cpu_lock));
for (i = 0; i < NCPU_SETUPS; i++) {
if (cpu_setups[i].func != NULL) {
cpu_setups[i].func(what, id, cpu_setups[i].arg);
}
}
}
/*
* Call any state change hooks for this CPU, undo it if error found.
*/
static int
cpu_state_change_hooks(int id, cpu_setup_t what, cpu_setup_t undo)
{
int i;
int retval = 0;
ASSERT(MUTEX_HELD(&cpu_lock));
for (i = 0; i < NCPU_SETUPS; i++) {
if (cpu_setups[i].func != NULL) {
retval = cpu_setups[i].func(what, id,
cpu_setups[i].arg);
if (retval) {
for (i--; i >= 0; i--) {
if (cpu_setups[i].func != NULL)
cpu_setups[i].func(undo,
id, cpu_setups[i].arg);
}
break;
}
}
}
return (retval);
}
/*
* Export information about this CPU via the kstat mechanism.
*/
static struct {
kstat_named_t ci_state;
kstat_named_t ci_state_begin;
kstat_named_t ci_cpu_type;
kstat_named_t ci_fpu_type;
kstat_named_t ci_clock_MHz;
kstat_named_t ci_chip_id;
kstat_named_t ci_implementation;
kstat_named_t ci_brandstr;
kstat_named_t ci_core_id;
kstat_named_t ci_curr_clock_Hz;
kstat_named_t ci_supp_freq_Hz;
kstat_named_t ci_pg_id;
#if defined(__sparcv9)
kstat_named_t ci_device_ID;
kstat_named_t ci_cpu_fru;
#endif
#if defined(__x86)
kstat_named_t ci_vendorstr;
kstat_named_t ci_family;
kstat_named_t ci_model;
kstat_named_t ci_step;
kstat_named_t ci_clogid;
kstat_named_t ci_pkg_core_id;
kstat_named_t ci_ncpuperchip;
kstat_named_t ci_ncoreperchip;
kstat_named_t ci_max_cstates;
kstat_named_t ci_curr_cstate;
kstat_named_t ci_cacheid;
kstat_named_t ci_sktstr;
#endif
} cpu_info_template = {
{ "state", KSTAT_DATA_CHAR },
{ "state_begin", KSTAT_DATA_LONG },
{ "cpu_type", KSTAT_DATA_CHAR },
{ "fpu_type", KSTAT_DATA_CHAR },
{ "clock_MHz", KSTAT_DATA_LONG },
{ "chip_id", KSTAT_DATA_LONG },
{ "implementation", KSTAT_DATA_STRING },
{ "brand", KSTAT_DATA_STRING },
{ "core_id", KSTAT_DATA_LONG },
{ "current_clock_Hz", KSTAT_DATA_UINT64 },
{ "supported_frequencies_Hz", KSTAT_DATA_STRING },
{ "pg_id", KSTAT_DATA_LONG },
#if defined(__sparcv9)
{ "device_ID", KSTAT_DATA_UINT64 },
{ "cpu_fru", KSTAT_DATA_STRING },
#endif
#if defined(__x86)
{ "vendor_id", KSTAT_DATA_STRING },
{ "family", KSTAT_DATA_INT32 },
{ "model", KSTAT_DATA_INT32 },
{ "stepping", KSTAT_DATA_INT32 },
{ "clog_id", KSTAT_DATA_INT32 },
{ "pkg_core_id", KSTAT_DATA_LONG },
{ "ncpu_per_chip", KSTAT_DATA_INT32 },
{ "ncore_per_chip", KSTAT_DATA_INT32 },
{ "supported_max_cstates", KSTAT_DATA_INT32 },
{ "current_cstate", KSTAT_DATA_INT32 },
{ "cache_id", KSTAT_DATA_INT32 },
{ "socket_type", KSTAT_DATA_STRING },
#endif
};
static kmutex_t cpu_info_template_lock;
static int
cpu_info_kstat_update(kstat_t *ksp, int rw)
{
cpu_t *cp = ksp->ks_private;
const char *pi_state;
if (rw == KSTAT_WRITE)
return (EACCES);
#if defined(__x86)
/* Is the cpu still initialising itself? */
if (cpuid_checkpass(cp, 1) == 0)
return (ENXIO);
#endif
pi_state = cpu_get_state_str(cp->cpu_flags);
(void) strcpy(cpu_info_template.ci_state.value.c, pi_state);
cpu_info_template.ci_state_begin.value.l = cp->cpu_state_begin;
(void) strncpy(cpu_info_template.ci_cpu_type.value.c,
cp->cpu_type_info.pi_processor_type, 15);
(void) strncpy(cpu_info_template.ci_fpu_type.value.c,
cp->cpu_type_info.pi_fputypes, 15);
cpu_info_template.ci_clock_MHz.value.l = cp->cpu_type_info.pi_clock;
cpu_info_template.ci_chip_id.value.l =
pg_plat_hw_instance_id(cp, PGHW_CHIP);
kstat_named_setstr(&cpu_info_template.ci_implementation,
cp->cpu_idstr);
kstat_named_setstr(&cpu_info_template.ci_brandstr, cp->cpu_brandstr);
cpu_info_template.ci_core_id.value.l = pg_plat_get_core_id(cp);
cpu_info_template.ci_curr_clock_Hz.value.ui64 =
cp->cpu_curr_clock;
cpu_info_template.ci_pg_id.value.l =
cp->cpu_pg && cp->cpu_pg->cmt_lineage ?
cp->cpu_pg->cmt_lineage->pg_id : -1;
kstat_named_setstr(&cpu_info_template.ci_supp_freq_Hz,
cp->cpu_supp_freqs);
#if defined(__sparcv9)
cpu_info_template.ci_device_ID.value.ui64 =
cpunodes[cp->cpu_id].device_id;
kstat_named_setstr(&cpu_info_template.ci_cpu_fru, cpu_fru_fmri(cp));
#endif
#if defined(__x86)
kstat_named_setstr(&cpu_info_template.ci_vendorstr,
cpuid_getvendorstr(cp));
cpu_info_template.ci_family.value.l = cpuid_getfamily(cp);
cpu_info_template.ci_model.value.l = cpuid_getmodel(cp);
cpu_info_template.ci_step.value.l = cpuid_getstep(cp);
cpu_info_template.ci_clogid.value.l = cpuid_get_clogid(cp);
cpu_info_template.ci_ncpuperchip.value.l = cpuid_get_ncpu_per_chip(cp);
cpu_info_template.ci_ncoreperchip.value.l =
cpuid_get_ncore_per_chip(cp);
cpu_info_template.ci_pkg_core_id.value.l = cpuid_get_pkgcoreid(cp);
cpu_info_template.ci_max_cstates.value.l = cp->cpu_m.max_cstates;
cpu_info_template.ci_curr_cstate.value.l = cpu_idle_get_cpu_state(cp);
cpu_info_template.ci_cacheid.value.i32 = cpuid_get_cacheid(cp);
kstat_named_setstr(&cpu_info_template.ci_sktstr,
cpuid_getsocketstr(cp));
#endif
return (0);
}
static void
cpu_info_kstat_create(cpu_t *cp)
{
zoneid_t zoneid;
ASSERT(MUTEX_HELD(&cpu_lock));
if (pool_pset_enabled())
zoneid = GLOBAL_ZONEID;
else
zoneid = ALL_ZONES;
if ((cp->cpu_info_kstat = kstat_create_zone("cpu_info", cp->cpu_id,
NULL, "misc", KSTAT_TYPE_NAMED,
sizeof (cpu_info_template) / sizeof (kstat_named_t),
KSTAT_FLAG_VIRTUAL | KSTAT_FLAG_VAR_SIZE, zoneid)) != NULL) {
cp->cpu_info_kstat->ks_data_size += 2 * CPU_IDSTRLEN;
#if defined(__sparcv9)
cp->cpu_info_kstat->ks_data_size +=
strlen(cpu_fru_fmri(cp)) + 1;
#endif
#if defined(__x86)
cp->cpu_info_kstat->ks_data_size += X86_VENDOR_STRLEN;
#endif
if (cp->cpu_supp_freqs != NULL)
cp->cpu_info_kstat->ks_data_size +=
strlen(cp->cpu_supp_freqs) + 1;
cp->cpu_info_kstat->ks_lock = &cpu_info_template_lock;
cp->cpu_info_kstat->ks_data = &cpu_info_template;
cp->cpu_info_kstat->ks_private = cp;
cp->cpu_info_kstat->ks_update = cpu_info_kstat_update;
kstat_install(cp->cpu_info_kstat);
}
}
static void
cpu_info_kstat_destroy(cpu_t *cp)
{
ASSERT(MUTEX_HELD(&cpu_lock));
kstat_delete(cp->cpu_info_kstat);
cp->cpu_info_kstat = NULL;
}
/*
* Create and install kstats for the boot CPU.
*/
void
cpu_kstat_init(cpu_t *cp)
{
mutex_enter(&cpu_lock);
cpu_info_kstat_create(cp);
cpu_stats_kstat_create(cp);
cpu_create_intrstat(cp);
cpu_set_state(cp);
mutex_exit(&cpu_lock);
}
/*
* Make visible to the zone that subset of the cpu information that would be
* initialized when a cpu is configured (but still offline).
*/
void
cpu_visibility_configure(cpu_t *cp, zone_t *zone)
{
zoneid_t zoneid = zone ? zone->zone_id : ALL_ZONES;
ASSERT(MUTEX_HELD(&cpu_lock));
ASSERT(pool_pset_enabled());
ASSERT(cp != NULL);
if (zoneid != ALL_ZONES && zoneid != GLOBAL_ZONEID) {
zone->zone_ncpus++;
ASSERT(zone->zone_ncpus <= ncpus);
}
if (cp->cpu_info_kstat != NULL)
kstat_zone_add(cp->cpu_info_kstat, zoneid);
}
/*
* Make visible to the zone that subset of the cpu information that would be
* initialized when a previously configured cpu is onlined.
*/
void
cpu_visibility_online(cpu_t *cp, zone_t *zone)
{
kstat_t *ksp;
char name[sizeof ("cpu_stat") + 10]; /* enough for 32-bit cpuids */
zoneid_t zoneid = zone ? zone->zone_id : ALL_ZONES;
processorid_t cpun;
ASSERT(MUTEX_HELD(&cpu_lock));
ASSERT(pool_pset_enabled());
ASSERT(cp != NULL);
ASSERT(cpu_is_active(cp));
cpun = cp->cpu_id;
if (zoneid != ALL_ZONES && zoneid != GLOBAL_ZONEID) {
zone->zone_ncpus_online++;
ASSERT(zone->zone_ncpus_online <= ncpus_online);
}
(void) snprintf(name, sizeof (name), "cpu_stat%d", cpun);
if ((ksp = kstat_hold_byname("cpu_stat", cpun, name, ALL_ZONES))
!= NULL) {
kstat_zone_add(ksp, zoneid);
kstat_rele(ksp);
}
if ((ksp = kstat_hold_byname("cpu", cpun, "sys", ALL_ZONES)) != NULL) {
kstat_zone_add(ksp, zoneid);
kstat_rele(ksp);
}
if ((ksp = kstat_hold_byname("cpu", cpun, "vm", ALL_ZONES)) != NULL) {
kstat_zone_add(ksp, zoneid);
kstat_rele(ksp);
}
if ((ksp = kstat_hold_byname("cpu", cpun, "intrstat", ALL_ZONES)) !=
NULL) {
kstat_zone_add(ksp, zoneid);
kstat_rele(ksp);
}
}
/*
* Update relevant kstats such that cpu is now visible to processes
* executing in specified zone.
*/
void
cpu_visibility_add(cpu_t *cp, zone_t *zone)
{
cpu_visibility_configure(cp, zone);
if (cpu_is_active(cp))
cpu_visibility_online(cp, zone);
}
/*
* Make invisible to the zone that subset of the cpu information that would be
* torn down when a previously offlined cpu is unconfigured.
*/
void
cpu_visibility_unconfigure(cpu_t *cp, zone_t *zone)
{
zoneid_t zoneid = zone ? zone->zone_id : ALL_ZONES;
ASSERT(MUTEX_HELD(&cpu_lock));
ASSERT(pool_pset_enabled());
ASSERT(cp != NULL);
if (zoneid != ALL_ZONES && zoneid != GLOBAL_ZONEID) {
ASSERT(zone->zone_ncpus != 0);
zone->zone_ncpus--;
}
if (cp->cpu_info_kstat)
kstat_zone_remove(cp->cpu_info_kstat, zoneid);
}
/*
* Make invisible to the zone that subset of the cpu information that would be
* torn down when a cpu is offlined (but still configured).
*/
void
cpu_visibility_offline(cpu_t *cp, zone_t *zone)
{
kstat_t *ksp;
char name[sizeof ("cpu_stat") + 10]; /* enough for 32-bit cpuids */
zoneid_t zoneid = zone ? zone->zone_id : ALL_ZONES;
processorid_t cpun;
ASSERT(MUTEX_HELD(&cpu_lock));
ASSERT(pool_pset_enabled());
ASSERT(cp != NULL);
ASSERT(cpu_is_active(cp));
cpun = cp->cpu_id;
if (zoneid != ALL_ZONES && zoneid != GLOBAL_ZONEID) {
ASSERT(zone->zone_ncpus_online != 0);
zone->zone_ncpus_online--;
}
if ((ksp = kstat_hold_byname("cpu", cpun, "intrstat", ALL_ZONES)) !=
NULL) {
kstat_zone_remove(ksp, zoneid);
kstat_rele(ksp);
}
if ((ksp = kstat_hold_byname("cpu", cpun, "vm", ALL_ZONES)) != NULL) {
kstat_zone_remove(ksp, zoneid);
kstat_rele(ksp);
}
if ((ksp = kstat_hold_byname("cpu", cpun, "sys", ALL_ZONES)) != NULL) {
kstat_zone_remove(ksp, zoneid);
kstat_rele(ksp);
}
(void) snprintf(name, sizeof (name), "cpu_stat%d", cpun);
if ((ksp = kstat_hold_byname("cpu_stat", cpun, name, ALL_ZONES))
!= NULL) {
kstat_zone_remove(ksp, zoneid);
kstat_rele(ksp);
}
}
/*
* Update relevant kstats such that cpu is no longer visible to processes
* executing in specified zone.
*/
void
cpu_visibility_remove(cpu_t *cp, zone_t *zone)
{
if (cpu_is_active(cp))
cpu_visibility_offline(cp, zone);
cpu_visibility_unconfigure(cp, zone);
}
/*
* Bind a thread to a CPU as requested.
*/
int
cpu_bind_thread(kthread_id_t tp, processorid_t bind, processorid_t *obind,
int *error)
{
processorid_t binding;
cpu_t *cp = NULL;
ASSERT(MUTEX_HELD(&cpu_lock));
ASSERT(MUTEX_HELD(&ttoproc(tp)->p_lock));
thread_lock(tp);
/*
* Record old binding, but change the obind, which was initialized
* to PBIND_NONE, only if this thread has a binding. This avoids
* reporting PBIND_NONE for a process when some LWPs are bound.
*/
binding = tp->t_bind_cpu;
if (binding != PBIND_NONE)
*obind = binding; /* record old binding */
switch (bind) {
case PBIND_QUERY:
/* Just return the old binding */
thread_unlock(tp);
return (0);
case PBIND_QUERY_TYPE:
/* Return the binding type */
*obind = TB_CPU_IS_SOFT(tp) ? PBIND_SOFT : PBIND_HARD;
thread_unlock(tp);
return (0);
case PBIND_SOFT:
/*
* Set soft binding for this thread and return the actual
* binding
*/
TB_CPU_SOFT_SET(tp);
thread_unlock(tp);
return (0);
case PBIND_HARD:
/*
* Set hard binding for this thread and return the actual
* binding
*/
TB_CPU_HARD_SET(tp);
thread_unlock(tp);
return (0);
default:
break;
}
/*
* If this thread/LWP cannot be bound because of permission
* problems, just note that and return success so that the
* other threads/LWPs will be bound. This is the way
* processor_bind() is defined to work.
*
* Binding will get EPERM if the thread is of system class
* or hasprocperm() fails.
*/
if (tp->t_cid == 0 || !hasprocperm(tp->t_cred, CRED())) {
*error = EPERM;
thread_unlock(tp);
return (0);
}
binding = bind;
if (binding != PBIND_NONE) {
cp = cpu_get((processorid_t)binding);
/*
* Make sure binding is valid and is in right partition.
*/
if (cp == NULL || tp->t_cpupart != cp->cpu_part) {
*error = EINVAL;
thread_unlock(tp);
return (0);
}
}
tp->t_bind_cpu = binding; /* set new binding */
/*
* If there is no system-set reason for affinity, set
* the t_bound_cpu field to reflect the binding.
*/
if (tp->t_affinitycnt == 0) {
if (binding == PBIND_NONE) {
/*
* We may need to adjust disp_max_unbound_pri
* since we're becoming unbound.
*/
disp_adjust_unbound_pri(tp);
tp->t_bound_cpu = NULL; /* set new binding */
/*
* Move thread to lgroup with strongest affinity
* after unbinding
*/
if (tp->t_lgrp_affinity)
lgrp_move_thread(tp,
lgrp_choose(tp, tp->t_cpupart), 1);
if (tp->t_state == TS_ONPROC &&
tp->t_cpu->cpu_part != tp->t_cpupart)
cpu_surrender(tp);
} else {
lpl_t *lpl;
tp->t_bound_cpu = cp;
ASSERT(cp->cpu_lpl != NULL);
/*
* Set home to lgroup with most affinity containing CPU
* that thread is being bound or minimum bounding
* lgroup if no affinities set
*/
if (tp->t_lgrp_affinity)
lpl = lgrp_affinity_best(tp, tp->t_cpupart,
LGRP_NONE, B_FALSE);
else
lpl = cp->cpu_lpl;
if (tp->t_lpl != lpl) {
/* can't grab cpu_lock */
lgrp_move_thread(tp, lpl, 1);
}
/*
* Make the thread switch to the bound CPU.
* If the thread is runnable, we need to
* requeue it even if t_cpu is already set
* to the right CPU, since it may be on a
* kpreempt queue and need to move to a local
* queue. We could check t_disp_queue to
* avoid unnecessary overhead if it's already
* on the right queue, but since this isn't
* a performance-critical operation it doesn't
* seem worth the extra code and complexity.
*
* If the thread is weakbound to the cpu then it will
* resist the new binding request until the weak
* binding drops. The cpu_surrender or requeueing
* below could be skipped in such cases (since it
* will have no effect), but that would require
* thread_allowmigrate to acquire thread_lock so
* we'll take the very occasional hit here instead.
*/
if (tp->t_state == TS_ONPROC) {
cpu_surrender(tp);
} else if (tp->t_state == TS_RUN) {
cpu_t *ocp = tp->t_cpu;
(void) dispdeq(tp);
setbackdq(tp);
/*
* Either on the bound CPU's disp queue now,
* or swapped out or on the swap queue.
*/
ASSERT(tp->t_disp_queue == cp->cpu_disp ||
tp->t_weakbound_cpu == ocp ||
(tp->t_schedflag & (TS_LOAD | TS_ON_SWAPQ))
!= TS_LOAD);
}
}
}
/*
* Our binding has changed; set TP_CHANGEBIND.
*/
tp->t_proc_flag |= TP_CHANGEBIND;
aston(tp);
thread_unlock(tp);
return (0);
}
cpuset_t *
cpuset_alloc(int kmflags)
{
return (kmem_alloc(sizeof (cpuset_t), kmflags));
}
void
cpuset_free(cpuset_t *s)
{
kmem_free(s, sizeof (cpuset_t));
}
void
cpuset_all(cpuset_t *s)
{
int i;
for (i = 0; i < CPUSET_WORDS; i++)
s->cpub[i] = ~0UL;
}
void
cpuset_all_but(cpuset_t *s, const uint_t cpu)
{
cpuset_all(s);
CPUSET_DEL(*s, cpu);
}
void
cpuset_only(cpuset_t *s, const uint_t cpu)
{
CPUSET_ZERO(*s);
CPUSET_ADD(*s, cpu);
}
long
cpu_in_set(const cpuset_t *s, const uint_t cpu)
{
VERIFY(cpu < NCPU);
return (BT_TEST(s->cpub, cpu));
}
void
cpuset_add(cpuset_t *s, const uint_t cpu)
{
VERIFY(cpu < NCPU);
BT_SET(s->cpub, cpu);
}
void
cpuset_del(cpuset_t *s, const uint_t cpu)
{
VERIFY(cpu < NCPU);
BT_CLEAR(s->cpub, cpu);
}
int
cpuset_isnull(const cpuset_t *s)
{
int i;
for (i = 0; i < CPUSET_WORDS; i++) {
if (s->cpub[i] != 0)
return (0);
}
return (1);
}
int
cpuset_isequal(const cpuset_t *s1, const cpuset_t *s2)
{
int i;
for (i = 0; i < CPUSET_WORDS; i++) {
if (s1->cpub[i] != s2->cpub[i])
return (0);
}
return (1);
}
uint_t
cpuset_find(const cpuset_t *s)
{
uint_t i;
uint_t cpu = (uint_t)-1;
/*
* Find a cpu in the cpuset
*/
for (i = 0; i < CPUSET_WORDS; i++) {
cpu = (uint_t)(lowbit(s->cpub[i]) - 1);
if (cpu != (uint_t)-1) {
cpu += i * BT_NBIPUL;
break;
}
}
return (cpu);
}
void
cpuset_bounds(const cpuset_t *s, uint_t *smallestid, uint_t *largestid)
{
int i, j;
uint_t bit;
/*
* First, find the smallest cpu id in the set.
*/
for (i = 0; i < CPUSET_WORDS; i++) {
if (s->cpub[i] != 0) {
bit = (uint_t)(lowbit(s->cpub[i]) - 1);
ASSERT(bit != (uint_t)-1);
*smallestid = bit + (i * BT_NBIPUL);
/*
* Now find the largest cpu id in
* the set and return immediately.
* Done in an inner loop to avoid
* having to break out of the first
* loop.
*/
for (j = CPUSET_WORDS - 1; j >= i; j--) {
if (s->cpub[j] != 0) {
bit = (uint_t)(highbit(s->cpub[j]) - 1);
ASSERT(bit != (uint_t)-1);
*largestid = bit + (j * BT_NBIPUL);
ASSERT(*largestid >= *smallestid);
return;
}
}
/*
* If this code is reached, a
* smallestid was found, but not a
* largestid. The cpuset must have
* been changed during the course
* of this function call.
*/
ASSERT(0);
}
}
*smallestid = *largestid = CPUSET_NOTINSET;
}
void
cpuset_atomic_del(cpuset_t *s, const uint_t cpu)
{
VERIFY(cpu < NCPU);
BT_ATOMIC_CLEAR(s->cpub, (cpu))
}
void
cpuset_atomic_add(cpuset_t *s, const uint_t cpu)
{
VERIFY(cpu < NCPU);
BT_ATOMIC_SET(s->cpub, (cpu))
}
long
cpuset_atomic_xadd(cpuset_t *s, const uint_t cpu)
{
long res;
VERIFY(cpu < NCPU);
BT_ATOMIC_SET_EXCL(s->cpub, cpu, res);
return (res);
}
long
cpuset_atomic_xdel(cpuset_t *s, const uint_t cpu)
{
long res;
VERIFY(cpu < NCPU);
BT_ATOMIC_CLEAR_EXCL(s->cpub, cpu, res);
return (res);
}
void
cpuset_or(cpuset_t *dst, cpuset_t *src)
{
for (int i = 0; i < CPUSET_WORDS; i++) {
dst->cpub[i] |= src->cpub[i];
}
}
void
cpuset_xor(cpuset_t *dst, cpuset_t *src)
{
for (int i = 0; i < CPUSET_WORDS; i++) {
dst->cpub[i] ^= src->cpub[i];
}
}
void
cpuset_and(cpuset_t *dst, cpuset_t *src)
{
for (int i = 0; i < CPUSET_WORDS; i++) {
dst->cpub[i] &= src->cpub[i];
}
}
void
cpuset_zero(cpuset_t *dst)
{
for (int i = 0; i < CPUSET_WORDS; i++) {
dst->cpub[i] = 0;
}
}
/*
* Unbind threads bound to specified CPU.
*
* If `unbind_all_threads' is true, unbind all user threads bound to a given
* CPU. Otherwise unbind all soft-bound user threads.
*/
int
cpu_unbind(processorid_t cpu, boolean_t unbind_all_threads)
{
processorid_t obind;
kthread_t *tp;
int ret = 0;
proc_t *pp;
int err, berr = 0;
ASSERT(MUTEX_HELD(&cpu_lock));
mutex_enter(&pidlock);
for (pp = practive; pp != NULL; pp = pp->p_next) {
mutex_enter(&pp->p_lock);
tp = pp->p_tlist;
/*
* Skip zombies, kernel processes, and processes in
* other zones, if called from a non-global zone.
*/
if (tp == NULL || (pp->p_flag & SSYS) ||
!HASZONEACCESS(curproc, pp->p_zone->zone_id)) {
mutex_exit(&pp->p_lock);
continue;
}
do {
if (tp->t_bind_cpu != cpu)
continue;
/*
* Skip threads with hard binding when
* `unbind_all_threads' is not specified.
*/
if (!unbind_all_threads && TB_CPU_IS_HARD(tp))
continue;
err = cpu_bind_thread(tp, PBIND_NONE, &obind, &berr);
if (ret == 0)
ret = err;
} while ((tp = tp->t_forw) != pp->p_tlist);
mutex_exit(&pp->p_lock);
}
mutex_exit(&pidlock);
if (ret == 0)
ret = berr;
return (ret);
}
/*
* Destroy all remaining bound threads on a cpu.
*/
void
cpu_destroy_bound_threads(cpu_t *cp)
{
extern id_t syscid;
register kthread_id_t t, tlist, tnext;
/*
* Destroy all remaining bound threads on the cpu. This
* should include both the interrupt threads and the idle thread.
* This requires some care, since we need to traverse the
* thread list with the pidlock mutex locked, but thread_free
* also locks the pidlock mutex. So, we collect the threads
* we're going to reap in a list headed by "tlist", then we
* unlock the pidlock mutex and traverse the tlist list,
* doing thread_free's on the thread's. Simple, n'est pas?
* Also, this depends on thread_free not mucking with the
* t_next and t_prev links of the thread.
*/
if ((t = curthread) != NULL) {
tlist = NULL;
mutex_enter(&pidlock);
do {
tnext = t->t_next;
if (t->t_bound_cpu == cp) {
/*
* We've found a bound thread, carefully unlink
* it out of the thread list, and add it to
* our "tlist". We "know" we don't have to
* worry about unlinking curthread (the thread
* that is executing this code).
*/
t->t_next->t_prev = t->t_prev;
t->t_prev->t_next = t->t_next;
t->t_next = tlist;
tlist = t;
ASSERT(t->t_cid == syscid);
/* wake up anyone blocked in thread_join */
cv_broadcast(&t->t_joincv);
/*
* t_lwp set by interrupt threads and not
* cleared.
*/
t->t_lwp = NULL;
/*
* Pause and idle threads always have
* t_state set to TS_ONPROC.
*/
t->t_state = TS_FREE;
t->t_prev = NULL; /* Just in case */
}
} while ((t = tnext) != curthread);
mutex_exit(&pidlock);
mutex_sync();
for (t = tlist; t != NULL; t = tnext) {
tnext = t->t_next;
thread_free(t);
}
}
}
/*
* Update the cpu_supp_freqs of this cpu. This information is returned
* as part of cpu_info kstats. If the cpu_info_kstat exists already, then
* maintain the kstat data size.
*/
void
cpu_set_supp_freqs(cpu_t *cp, const char *freqs)
{
char clkstr[sizeof ("18446744073709551615") + 1]; /* ui64 MAX */
const char *lfreqs = clkstr;
boolean_t kstat_exists = B_FALSE;
kstat_t *ksp;
size_t len;
/*
* A NULL pointer means we only support one speed.
*/
if (freqs == NULL)
(void) snprintf(clkstr, sizeof (clkstr), "%"PRIu64,
cp->cpu_curr_clock);
else
lfreqs = freqs;
/*
* Make sure the frequency doesn't change while a snapshot is
* going on. Of course, we only need to worry about this if
* the kstat exists.
*/
if ((ksp = cp->cpu_info_kstat) != NULL) {
mutex_enter(ksp->ks_lock);
kstat_exists = B_TRUE;
}
/*
* Free any previously allocated string and if the kstat
* already exists, then update its data size.
*/
if (cp->cpu_supp_freqs != NULL) {
len = strlen(cp->cpu_supp_freqs) + 1;
kmem_free(cp->cpu_supp_freqs, len);
if (kstat_exists)
ksp->ks_data_size -= len;
}
/*
* Allocate the new string and set the pointer.
*/
len = strlen(lfreqs) + 1;
cp->cpu_supp_freqs = kmem_alloc(len, KM_SLEEP);
(void) strcpy(cp->cpu_supp_freqs, lfreqs);
/*
* If the kstat already exists then update the data size and
* free the lock.
*/
if (kstat_exists) {
ksp->ks_data_size += len;
mutex_exit(ksp->ks_lock);
}
}
/*
* Indicate the current CPU's clock freqency (in Hz).
* The calling context must be such that CPU references are safe.
*/
void
cpu_set_curr_clock(uint64_t new_clk)
{
uint64_t old_clk;
old_clk = CPU->cpu_curr_clock;
CPU->cpu_curr_clock = new_clk;
/*
* The cpu-change-speed DTrace probe exports the frequency in Hz
*/
DTRACE_PROBE3(cpu__change__speed, processorid_t, CPU->cpu_id,
uint64_t, old_clk, uint64_t, new_clk);
}
/*
* processor_info(2) and p_online(2) status support functions
* The constants returned by the cpu_get_state() and cpu_get_state_str() are
* for use in communicating processor state information to userland. Kernel
* subsystems should only be using the cpu_flags value directly. Subsystems
* modifying cpu_flags should record the state change via a call to the
* cpu_set_state().
*/
/*
* Update the pi_state of this CPU. This function provides the CPU status for
* the information returned by processor_info(2).
*/
void
cpu_set_state(cpu_t *cpu)
{
ASSERT(MUTEX_HELD(&cpu_lock));
cpu->cpu_type_info.pi_state = cpu_get_state(cpu);
cpu->cpu_state_begin = gethrestime_sec();
pool_cpu_mod = gethrtime();
}
/*
* Return offline/online/other status for the indicated CPU. Use only for
* communication with user applications; cpu_flags provides the in-kernel
* interface.
*/
static int
cpu_flags_to_state(cpu_flag_t flags)
{
if (flags & CPU_DISABLED)
return (P_DISABLED);
else if (flags & CPU_POWEROFF)
return (P_POWEROFF);
else if (flags & CPU_FAULTED)
return (P_FAULTED);
else if (flags & CPU_SPARE)
return (P_SPARE);
else if ((flags & (CPU_READY | CPU_OFFLINE)) != CPU_READY)
return (P_OFFLINE);
else if (flags & CPU_ENABLE)
return (P_ONLINE);
else
return (P_NOINTR);
}
int
cpu_get_state(cpu_t *cpu)
{
ASSERT(MUTEX_HELD(&cpu_lock));
return (cpu_flags_to_state(cpu->cpu_flags));
}
/*
* Return processor_info(2) state as a string.
*/
const char *
cpu_get_state_str(cpu_flag_t flags)
{
const char *string;
switch (cpu_flags_to_state(flags)) {
case P_ONLINE:
string = PS_ONLINE;
break;
case P_POWEROFF:
string = PS_POWEROFF;
break;
case P_NOINTR:
string = PS_NOINTR;
break;
case P_SPARE:
string = PS_SPARE;
break;
case P_FAULTED:
string = PS_FAULTED;
break;
case P_OFFLINE:
string = PS_OFFLINE;
break;
case P_DISABLED:
string = PS_DISABLED;
break;
default:
string = "unknown";
break;
}
return (string);
}
/*
* Export this CPU's statistics (cpu_stat_t and cpu_stats_t) as raw and named
* kstats, respectively. This is done when a CPU is initialized or placed
* online via p_online(2).
*/
static void
cpu_stats_kstat_create(cpu_t *cp)
{
int instance = cp->cpu_id;
char *module = "cpu";
char *class = "misc";
kstat_t *ksp;
zoneid_t zoneid;
ASSERT(MUTEX_HELD(&cpu_lock));
if (pool_pset_enabled())
zoneid = GLOBAL_ZONEID;
else
zoneid = ALL_ZONES;
/*
* Create named kstats
*/
#define CPU_STATS_KS_CREATE(name, tsize, update_func) \
ksp = kstat_create_zone(module, instance, (name), class, \
KSTAT_TYPE_NAMED, (tsize) / sizeof (kstat_named_t), 0, \
zoneid); \
if (ksp != NULL) { \
ksp->ks_private = cp; \
ksp->ks_update = (update_func); \
kstat_install(ksp); \
} else \
cmn_err(CE_WARN, "cpu: unable to create %s:%d:%s kstat", \
module, instance, (name));
CPU_STATS_KS_CREATE("sys", sizeof (cpu_sys_stats_ks_data_template),
cpu_sys_stats_ks_update);
CPU_STATS_KS_CREATE("vm", sizeof (cpu_vm_stats_ks_data_template),
cpu_vm_stats_ks_update);
/*
* Export the familiar cpu_stat_t KSTAT_TYPE_RAW kstat.
*/
ksp = kstat_create_zone("cpu_stat", cp->cpu_id, NULL,
"misc", KSTAT_TYPE_RAW, sizeof (cpu_stat_t), 0, zoneid);
if (ksp != NULL) {
ksp->ks_update = cpu_stat_ks_update;
ksp->ks_private = cp;
kstat_install(ksp);
}
}
static void
cpu_stats_kstat_destroy(cpu_t *cp)
{
char ks_name[KSTAT_STRLEN];
(void) sprintf(ks_name, "cpu_stat%d", cp->cpu_id);
kstat_delete_byname("cpu_stat", cp->cpu_id, ks_name);
kstat_delete_byname("cpu", cp->cpu_id, "sys");
kstat_delete_byname("cpu", cp->cpu_id, "vm");
}
static int
cpu_sys_stats_ks_update(kstat_t *ksp, int rw)
{
cpu_t *cp = (cpu_t *)ksp->ks_private;
struct cpu_sys_stats_ks_data *csskd;
cpu_sys_stats_t *css;
hrtime_t msnsecs[NCMSTATES];
int i;
if (rw == KSTAT_WRITE)
return (EACCES);
csskd = ksp->ks_data;
css = &cp->cpu_stats.sys;
/*
* Read CPU mstate, but compare with the last values we
* received to make sure that the returned kstats never
* decrease.
*/
get_cpu_mstate(cp, msnsecs);
if (csskd->cpu_nsec_idle.value.ui64 > msnsecs[CMS_IDLE])
msnsecs[CMS_IDLE] = csskd->cpu_nsec_idle.value.ui64;
if (csskd->cpu_nsec_user.value.ui64 > msnsecs[CMS_USER])
msnsecs[CMS_USER] = csskd->cpu_nsec_user.value.ui64;
if (csskd->cpu_nsec_kernel.value.ui64 > msnsecs[CMS_SYSTEM])
msnsecs[CMS_SYSTEM] = csskd->cpu_nsec_kernel.value.ui64;
bcopy(&cpu_sys_stats_ks_data_template, ksp->ks_data,
sizeof (cpu_sys_stats_ks_data_template));
csskd->cpu_ticks_wait.value.ui64 = 0;
csskd->wait_ticks_io.value.ui64 = 0;
csskd->cpu_nsec_idle.value.ui64 = msnsecs[CMS_IDLE];
csskd->cpu_nsec_user.value.ui64 = msnsecs[CMS_USER];
csskd->cpu_nsec_kernel.value.ui64 = msnsecs[CMS_SYSTEM];
csskd->cpu_ticks_idle.value.ui64 =
NSEC_TO_TICK(csskd->cpu_nsec_idle.value.ui64);
csskd->cpu_ticks_user.value.ui64 =
NSEC_TO_TICK(csskd->cpu_nsec_user.value.ui64);
csskd->cpu_ticks_kernel.value.ui64 =
NSEC_TO_TICK(csskd->cpu_nsec_kernel.value.ui64);
csskd->cpu_nsec_dtrace.value.ui64 = cp->cpu_dtrace_nsec;
csskd->dtrace_probes.value.ui64 = cp->cpu_dtrace_probes;
csskd->cpu_nsec_intr.value.ui64 = cp->cpu_intrlast;
csskd->cpu_load_intr.value.ui64 = cp->cpu_intrload;
csskd->bread.value.ui64 = css->bread;
csskd->bwrite.value.ui64 = css->bwrite;
csskd->lread.value.ui64 = css->lread;
csskd->lwrite.value.ui64 = css->lwrite;
csskd->phread.value.ui64 = css->phread;
csskd->phwrite.value.ui64 = css->phwrite;
csskd->pswitch.value.ui64 = css->pswitch;
csskd->trap.value.ui64 = css->trap;
csskd->intr.value.ui64 = 0;
for (i = 0; i < PIL_MAX; i++)
csskd->intr.value.ui64 += css->intr[i];
csskd->syscall.value.ui64 = css->syscall;
csskd->sysread.value.ui64 = css->sysread;
csskd->syswrite.value.ui64 = css->syswrite;
csskd->sysfork.value.ui64 = css->sysfork;
csskd->sysvfork.value.ui64 = css->sysvfork;
csskd->sysexec.value.ui64 = css->sysexec;
csskd->readch.value.ui64 = css->readch;
csskd->writech.value.ui64 = css->writech;
csskd->rcvint.value.ui64 = css->rcvint;
csskd->xmtint.value.ui64 = css->xmtint;
csskd->mdmint.value.ui64 = css->mdmint;
csskd->rawch.value.ui64 = css->rawch;
csskd->canch.value.ui64 = css->canch;
csskd->outch.value.ui64 = css->outch;
csskd->msg.value.ui64 = css->msg;
csskd->sema.value.ui64 = css->sema;
csskd->namei.value.ui64 = css->namei;
csskd->ufsiget.value.ui64 = css->ufsiget;
csskd->ufsdirblk.value.ui64 = css->ufsdirblk;
csskd->ufsipage.value.ui64 = css->ufsipage;
csskd->ufsinopage.value.ui64 = css->ufsinopage;
csskd->procovf.value.ui64 = css->procovf;
csskd->intrthread.value.ui64 = 0;
for (i = 0; i < LOCK_LEVEL - 1; i++)
csskd->intrthread.value.ui64 += css->intr[i];
csskd->intrblk.value.ui64 = css->intrblk;
csskd->intrunpin.value.ui64 = css->intrunpin;
csskd->idlethread.value.ui64 = css->idlethread;
csskd->inv_swtch.value.ui64 = css->inv_swtch;
csskd->nthreads.value.ui64 = css->nthreads;
csskd->cpumigrate.value.ui64 = css->cpumigrate;
csskd->xcalls.value.ui64 = css->xcalls;
csskd->mutex_adenters.value.ui64 = css->mutex_adenters;
csskd->rw_rdfails.value.ui64 = css->rw_rdfails;
csskd->rw_wrfails.value.ui64 = css->rw_wrfails;
csskd->modload.value.ui64 = css->modload;
csskd->modunload.value.ui64 = css->modunload;
csskd->bawrite.value.ui64 = css->bawrite;
csskd->iowait.value.ui64 = css->iowait;
return (0);
}
static int
cpu_vm_stats_ks_update(kstat_t *ksp, int rw)
{
cpu_t *cp = (cpu_t *)ksp->ks_private;
struct cpu_vm_stats_ks_data *cvskd;
cpu_vm_stats_t *cvs;
if (rw == KSTAT_WRITE)
return (EACCES);
cvs = &cp->cpu_stats.vm;
cvskd = ksp->ks_data;
bcopy(&cpu_vm_stats_ks_data_template, ksp->ks_data,
sizeof (cpu_vm_stats_ks_data_template));
cvskd->pgrec.value.ui64 = cvs->pgrec;
cvskd->pgfrec.value.ui64 = cvs->pgfrec;
cvskd->pgin.value.ui64 = cvs->pgin;
cvskd->pgpgin.value.ui64 = cvs->pgpgin;
cvskd->pgout.value.ui64 = cvs->pgout;
cvskd->pgpgout.value.ui64 = cvs->pgpgout;
cvskd->swapin.value.ui64 = cvs->swapin;
cvskd->pgswapin.value.ui64 = cvs->pgswapin;
cvskd->swapout.value.ui64 = cvs->swapout;
cvskd->pgswapout.value.ui64 = cvs->pgswapout;
cvskd->zfod.value.ui64 = cvs->zfod;
cvskd->dfree.value.ui64 = cvs->dfree;
cvskd->scan.value.ui64 = cvs->scan;
cvskd->rev.value.ui64 = cvs->rev;
cvskd->hat_fault.value.ui64 = cvs->hat_fault;
cvskd->as_fault.value.ui64 = cvs->as_fault;
cvskd->maj_fault.value.ui64 = cvs->maj_fault;
cvskd->cow_fault.value.ui64 = cvs->cow_fault;
cvskd->prot_fault.value.ui64 = cvs->prot_fault;
cvskd->softlock.value.ui64 = cvs->softlock;
cvskd->kernel_asflt.value.ui64 = cvs->kernel_asflt;
cvskd->pgrrun.value.ui64 = cvs->pgrrun;
cvskd->execpgin.value.ui64 = cvs->execpgin;
cvskd->execpgout.value.ui64 = cvs->execpgout;
cvskd->execfree.value.ui64 = cvs->execfree;
cvskd->anonpgin.value.ui64 = cvs->anonpgin;
cvskd->anonpgout.value.ui64 = cvs->anonpgout;
cvskd->anonfree.value.ui64 = cvs->anonfree;
cvskd->fspgin.value.ui64 = cvs->fspgin;
cvskd->fspgout.value.ui64 = cvs->fspgout;
cvskd->fsfree.value.ui64 = cvs->fsfree;
return (0);
}
static int
cpu_stat_ks_update(kstat_t *ksp, int rw)
{
cpu_stat_t *cso;
cpu_t *cp;
int i;
hrtime_t msnsecs[NCMSTATES];
cso = (cpu_stat_t *)ksp->ks_data;
cp = (cpu_t *)ksp->ks_private;
if (rw == KSTAT_WRITE)
return (EACCES);
/*
* Read CPU mstate, but compare with the last values we
* received to make sure that the returned kstats never
* decrease.
*/
get_cpu_mstate(cp, msnsecs);
msnsecs[CMS_IDLE] = NSEC_TO_TICK(msnsecs[CMS_IDLE]);
msnsecs[CMS_USER] = NSEC_TO_TICK(msnsecs[CMS_USER]);
msnsecs[CMS_SYSTEM] = NSEC_TO_TICK(msnsecs[CMS_SYSTEM]);
if (cso->cpu_sysinfo.cpu[CPU_IDLE] < msnsecs[CMS_IDLE])
cso->cpu_sysinfo.cpu[CPU_IDLE] = msnsecs[CMS_IDLE];
if (cso->cpu_sysinfo.cpu[CPU_USER] < msnsecs[CMS_USER])
cso->cpu_sysinfo.cpu[CPU_USER] = msnsecs[CMS_USER];
if (cso->cpu_sysinfo.cpu[CPU_KERNEL] < msnsecs[CMS_SYSTEM])
cso->cpu_sysinfo.cpu[CPU_KERNEL] = msnsecs[CMS_SYSTEM];
cso->cpu_sysinfo.cpu[CPU_WAIT] = 0;
cso->cpu_sysinfo.wait[W_IO] = 0;
cso->cpu_sysinfo.wait[W_SWAP] = 0;
cso->cpu_sysinfo.wait[W_PIO] = 0;
cso->cpu_sysinfo.bread = CPU_STATS(cp, sys.bread);
cso->cpu_sysinfo.bwrite = CPU_STATS(cp, sys.bwrite);
cso->cpu_sysinfo.lread = CPU_STATS(cp, sys.lread);
cso->cpu_sysinfo.lwrite = CPU_STATS(cp, sys.lwrite);
cso->cpu_sysinfo.phread = CPU_STATS(cp, sys.phread);
cso->cpu_sysinfo.phwrite = CPU_STATS(cp, sys.phwrite);
cso->cpu_sysinfo.pswitch = CPU_STATS(cp, sys.pswitch);
cso->cpu_sysinfo.trap = CPU_STATS(cp, sys.trap);
cso->cpu_sysinfo.intr = 0;
for (i = 0; i < PIL_MAX; i++)
cso->cpu_sysinfo.intr += CPU_STATS(cp, sys.intr[i]);
cso->cpu_sysinfo.syscall = CPU_STATS(cp, sys.syscall);
cso->cpu_sysinfo.sysread = CPU_STATS(cp, sys.sysread);
cso->cpu_sysinfo.syswrite = CPU_STATS(cp, sys.syswrite);
cso->cpu_sysinfo.sysfork = CPU_STATS(cp, sys.sysfork);
cso->cpu_sysinfo.sysvfork = CPU_STATS(cp, sys.sysvfork);
cso->cpu_sysinfo.sysexec = CPU_STATS(cp, sys.sysexec);
cso->cpu_sysinfo.readch = CPU_STATS(cp, sys.readch);
cso->cpu_sysinfo.writech = CPU_STATS(cp, sys.writech);
cso->cpu_sysinfo.rcvint = CPU_STATS(cp, sys.rcvint);
cso->cpu_sysinfo.xmtint = CPU_STATS(cp, sys.xmtint);
cso->cpu_sysinfo.mdmint = CPU_STATS(cp, sys.mdmint);
cso->cpu_sysinfo.rawch = CPU_STATS(cp, sys.rawch);
cso->cpu_sysinfo.canch = CPU_STATS(cp, sys.canch);
cso->cpu_sysinfo.outch = CPU_STATS(cp, sys.outch);
cso->cpu_sysinfo.msg = CPU_STATS(cp, sys.msg);
cso->cpu_sysinfo.sema = CPU_STATS(cp, sys.sema);
cso->cpu_sysinfo.namei = CPU_STATS(cp, sys.namei);
cso->cpu_sysinfo.ufsiget = CPU_STATS(cp, sys.ufsiget);
cso->cpu_sysinfo.ufsdirblk = CPU_STATS(cp, sys.ufsdirblk);
cso->cpu_sysinfo.ufsipage = CPU_STATS(cp, sys.ufsipage);
cso->cpu_sysinfo.ufsinopage = CPU_STATS(cp, sys.ufsinopage);
cso->cpu_sysinfo.inodeovf = 0;
cso->cpu_sysinfo.fileovf = 0;
cso->cpu_sysinfo.procovf = CPU_STATS(cp, sys.procovf);
cso->cpu_sysinfo.intrthread = 0;
for (i = 0; i < LOCK_LEVEL - 1; i++)
cso->cpu_sysinfo.intrthread += CPU_STATS(cp, sys.intr[i]);
cso->cpu_sysinfo.intrblk = CPU_STATS(cp, sys.intrblk);
cso->cpu_sysinfo.idlethread = CPU_STATS(cp, sys.idlethread);
cso->cpu_sysinfo.inv_swtch = CPU_STATS(cp, sys.inv_swtch);
cso->cpu_sysinfo.nthreads = CPU_STATS(cp, sys.nthreads);
cso->cpu_sysinfo.cpumigrate = CPU_STATS(cp, sys.cpumigrate);
cso->cpu_sysinfo.xcalls = CPU_STATS(cp, sys.xcalls);
cso->cpu_sysinfo.mutex_adenters = CPU_STATS(cp, sys.mutex_adenters);
cso->cpu_sysinfo.rw_rdfails = CPU_STATS(cp, sys.rw_rdfails);
cso->cpu_sysinfo.rw_wrfails = CPU_STATS(cp, sys.rw_wrfails);
cso->cpu_sysinfo.modload = CPU_STATS(cp, sys.modload);
cso->cpu_sysinfo.modunload = CPU_STATS(cp, sys.modunload);
cso->cpu_sysinfo.bawrite = CPU_STATS(cp, sys.bawrite);
cso->cpu_sysinfo.rw_enters = 0;
cso->cpu_sysinfo.win_uo_cnt = 0;
cso->cpu_sysinfo.win_uu_cnt = 0;
cso->cpu_sysinfo.win_so_cnt = 0;
cso->cpu_sysinfo.win_su_cnt = 0;
cso->cpu_sysinfo.win_suo_cnt = 0;
cso->cpu_syswait.iowait = CPU_STATS(cp, sys.iowait);
cso->cpu_syswait.swap = 0;
cso->cpu_syswait.physio = 0;
cso->cpu_vminfo.pgrec = CPU_STATS(cp, vm.pgrec);
cso->cpu_vminfo.pgfrec = CPU_STATS(cp, vm.pgfrec);
cso->cpu_vminfo.pgin = CPU_STATS(cp, vm.pgin);
cso->cpu_vminfo.pgpgin = CPU_STATS(cp, vm.pgpgin);
cso->cpu_vminfo.pgout = CPU_STATS(cp, vm.pgout);
cso->cpu_vminfo.pgpgout = CPU_STATS(cp, vm.pgpgout);
cso->cpu_vminfo.swapin = CPU_STATS(cp, vm.swapin);
cso->cpu_vminfo.pgswapin = CPU_STATS(cp, vm.pgswapin);
cso->cpu_vminfo.swapout = CPU_STATS(cp, vm.swapout);
cso->cpu_vminfo.pgswapout = CPU_STATS(cp, vm.pgswapout);
cso->cpu_vminfo.zfod = CPU_STATS(cp, vm.zfod);
cso->cpu_vminfo.dfree = CPU_STATS(cp, vm.dfree);
cso->cpu_vminfo.scan = CPU_STATS(cp, vm.scan);
cso->cpu_vminfo.rev = CPU_STATS(cp, vm.rev);
cso->cpu_vminfo.hat_fault = CPU_STATS(cp, vm.hat_fault);
cso->cpu_vminfo.as_fault = CPU_STATS(cp, vm.as_fault);
cso->cpu_vminfo.maj_fault = CPU_STATS(cp, vm.maj_fault);
cso->cpu_vminfo.cow_fault = CPU_STATS(cp, vm.cow_fault);
cso->cpu_vminfo.prot_fault = CPU_STATS(cp, vm.prot_fault);
cso->cpu_vminfo.softlock = CPU_STATS(cp, vm.softlock);
cso->cpu_vminfo.kernel_asflt = CPU_STATS(cp, vm.kernel_asflt);
cso->cpu_vminfo.pgrrun = CPU_STATS(cp, vm.pgrrun);
cso->cpu_vminfo.execpgin = CPU_STATS(cp, vm.execpgin);
cso->cpu_vminfo.execpgout = CPU_STATS(cp, vm.execpgout);
cso->cpu_vminfo.execfree = CPU_STATS(cp, vm.execfree);
cso->cpu_vminfo.anonpgin = CPU_STATS(cp, vm.anonpgin);
cso->cpu_vminfo.anonpgout = CPU_STATS(cp, vm.anonpgout);
cso->cpu_vminfo.anonfree = CPU_STATS(cp, vm.anonfree);
cso->cpu_vminfo.fspgin = CPU_STATS(cp, vm.fspgin);
cso->cpu_vminfo.fspgout = CPU_STATS(cp, vm.fspgout);
cso->cpu_vminfo.fsfree = CPU_STATS(cp, vm.fsfree);
return (0);
}
| 27.103911 | 80 | 0.69543 | [
"model"
] |
ef07feb3e196c4c2844e0e0824a44081ae29e6ed | 192 | h | C | include/provenance_rewriter/lateral_rewrites/lateral_prov_main.h | lordpretzel/gprom | 143b8e950a843ceac8585c31156ae174295a5315 | [
"Apache-2.0"
] | 5 | 2017-02-01T16:27:47.000Z | 2021-04-23T16:02:03.000Z | include/provenance_rewriter/lateral_rewrites/lateral_prov_main.h | lordpretzel/gprom | 143b8e950a843ceac8585c31156ae174295a5315 | [
"Apache-2.0"
] | 82 | 2016-11-30T15:57:48.000Z | 2022-03-04T21:35:03.000Z | include/provenance_rewriter/lateral_rewrites/lateral_prov_main.h | lordpretzel/gprom | 143b8e950a843ceac8585c31156ae174295a5315 | [
"Apache-2.0"
] | 4 | 2017-02-09T20:53:13.000Z | 2022-02-10T22:01:35.000Z | /*
* lateral_prov_main.h
*
* Created on: July 27, 2018
* Author: Xing
*/
#include "model/query_operator/query_operator.h"
extern Node *lateralTranslateQBModel (Node *qbModel);
| 13.714286 | 53 | 0.6875 | [
"model"
] |
ef154fe9b6ceba1f34aa193562f5b24a30e1f933 | 5,391 | h | C | t_swift_vector.h | FenixFeather/t_swift-vector | 2c0e7ebd109add135e7049fd3e7e06d43ffbd167 | [
"MIT"
] | 2 | 2019-12-30T14:17:17.000Z | 2020-01-05T20:02:03.000Z | t_swift_vector.h | FenixFeather/t_swift-vector | 2c0e7ebd109add135e7049fd3e7e06d43ffbd167 | [
"MIT"
] | null | null | null | t_swift_vector.h | FenixFeather/t_swift-vector | 2c0e7ebd109add135e7049fd3e7e06d43ffbd167 | [
"MIT"
] | null | null | null | /*
* @file t_swift_vector.h
* @brief A Taylor Swift themed, threadsafe dynamically expanding array.
*
* Autocomplete is almost mandatory when using this code.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#ifndef __T_SWIFT_VECTOR__
#define __T_SWIFT_VECTOR__
#define FACTOR 2 /* The factor the capacity of the array should grow by when full. */
#define ELEMENTS 2 /* Number of elements each entry will have. */
#define STARTSIZE 8 /* The max capacity the array should start with. */
#define THREADSAFE 1 /* Whether the vector should be threadsafe. */
/* @brief A struct that holds the data for each element. */
typedef struct _picture_to_burn_t
{
void data[ELEMENTS];
} picture_to_burn_t;
/*
* @brief A struct that points to the array and keeps track of its fullness.
*
*/
typedef struct _swift_t
{
picture_to_burn_t *holy_ground;
int blank_space; /* Total capacity of the array. */
int ex_lovers; /* Number of elements currently in the array. */
#if THREADSAFE
pthread_mutex_t we_are_never_ever_getting_back_together; /* Mutex for synchronization purposes. */
#endif
} swift_t;
/*
* @brief Initialize the data structure.
*
* @param t_swift A pointer to a swift_t struct that should already be initialized.
*
*/
void welcome_to_new_york(swift_t *t_swift)
{
t_swift->holy_ground = malloc(sizeof(mine_t) * STARTSIZE);
memset(t_swift->holy_ground, 0x0, sizeof(mine_t) * STARTSIZE);
t_swift->blank_space = STARTSIZE;
t_swift->ex_lovers = 0;
pthread_mutex_init(&t_swift->we_are_never_ever_getting_back_together, NULL);
}
/*
* @brief Push a new element to the back of the array.
*
* @param t_swift A pointer to the data structure to operate on.
* @param picture_to_burn_t The new element to append.
*
*/
void i_knew_you_were_trouble_when_you_walked_in(swift_t *t_swift, picture_to_burn_t picture)
{
#if THREADSAFE
pthread_mutex_lock(&t_swift->we_are_never_ever_getting_back_together);
#endif
if (t_swift->ex_lovers == t_swift->blank_space) {
t_swift->blank_space *= FACTOR;
t_swift->holy_ground = (picture_to_burn_t*) realloc(t_swift->holy_ground, t_swift->blank_space * sizeof(picture_to_burn_t));
}
t_swift->holy_ground[t_swift->ex_lovers] = picture;
t_swift->ex_lovers++;
#if THREADSAFE
pthread_mutex_unlock(&t_swift->we_are_never_ever_getting_back_together);
#endif THREADSAFE
}
/*
* @brief Insert an element into an arbitrary index.
*
* @param t_swift A pointer to the data structure to operate on.
* @param index The index at which to insert the element.
* @param picture_to_burn_t The element to insert.
*/
void i_know_places(swift_t *t_swift, int index, picture_to_burn_t picture)
{
#if THREADSAFE
pthread_mutex_lock(&t_swift->we_are_never_ever_getting_back_together);
#endif THREADSAFE
if (t_swift->ex_lovers == t_swift->blank_space) {
t_swift->blank_space *= FACTOR;
t_swift->holy_ground = (picture_to_burn_t*) realloc(t_swift->holy_ground, t_swift->blank_space * sizeof(picture_to_burn_t));
}
int ii = t_swift->ex_lovers;
for (; ii > index; ii--) {
t_swift->holy_ground[ii] = t_swift->holy_ground[ii - 1];
}
t_swift->holy_ground[index] = picture;
t_swift->ex_lovers++;
#if THREADSAFE
pthread_mutex_unlock(&t_swift->we_are_never_ever_getting_back_together);
#endif
}
/*
* @brief Get a pointer to the desired element in the array.
*
* @param t_swift A pointer to the data structure to operate on.
* @param index The index to fetch.
*
* @return picture_to_burn_t* A pointer to the desired picture to burn, or NULL if out of bounds.
*/
picture_to_burn_t *the_lucky_one(swift_t *t_swift, int index)
{
#if THREADSAFE
pthread_mutex_lock(&t_swift->we_are_never_ever_getting_back_together);
#endif
if (index >= t_swift->ex_lovers || index < 0) {
pthread_mutex_unlock(&t_swift->we_are_never_ever_getting_back_together);
return NULL;
}
#if THREADSAFE
pthread_mutex_unlock(&t_swift->we_are_never_ever_getting_back_together);
#endif
return &t_swift->holy_ground[index];
}
/*
* @brief Delete an element at an index in the array and copy elements over.
*
* @param t_swift A pointer to the data structure to operate on.
* @param index The index at which to delete.
*
* @return int Return 1 if deletion was successful, or 0 if deletion failed.
*
*/
int shake_it_off(swift_t *t_swift, int index)
{
#if THREADSAFE
pthread_mutex_lock(&t_swift->we_are_never_ever_getting_back_together);
#endif
if (index >= t_swift->ex_lovers || index < 0) {
#if THREADSAFE
pthread_mutex_unlock(&t_swift->we_are_never_ever_getting_back_together);
#endif
return 0;
}
int ii = index;
for (; ii < t_swift->ex_lovers - 1; ii++) {
t_swift->holy_ground[ii] = t_swift->holy_ground[ii + 1];
}
t_swift->ex_lovers--;
#if THREADSAFE
pthread_mutex_unlock(&t_swift->we_are_never_ever_getting_back_together);
#endif
return 1;
}
/*
* @brief Clean up data structure memory. Run when done using the structure.
*
* @param t_swift A pointer to the data structure to operate on.
*/
void out_of_the_woods(swift_t *t_swift)
{
free(t_swift->holy_ground);
}
#endif
| 29.140541 | 127 | 0.70729 | [
"vector"
] |
ef215d61d33dead2260cdf98c00467f407951255 | 746 | c | C | main.c | Acknex/StandardShader | 4355f89e8cb0b3bd884bd4f0d3d8976759dd13ca | [
"Zlib"
] | null | null | null | main.c | Acknex/StandardShader | 4355f89e8cb0b3bd884bd4f0d3d8976759dd13ca | [
"Zlib"
] | null | null | null | main.c | Acknex/StandardShader | 4355f89e8cb0b3bd884bd4f0d3d8976759dd13ca | [
"Zlib"
] | 1 | 2020-02-11T17:30:52.000Z | 2020-02-11T17:30:52.000Z | #include <acknex.h>
#include <default.c>
MATERIAL * mtl_nextgen =
{
effect = "fx_default.fx";
technique = "std_lightmapped";
flags = AUTORELOAD | TANGENT;
ambient_red = 100;
ambient_green = 100;
ambient_blue = 100;
diffuse_red = 200;
diffuse_green = 200;
diffuse_blue = 200;
specular_red = 0;
specular_green = 0;
specular_blue = 0;
emissive_red = 0;
emissive_green = 0;
emissive_blue = 0;
power = 2;
}
function main()
{
level_load("scene/scene.wmb");
ent_create("cylinder.mdl", vector(64, 16, 0), NULL);
you = ent_create("cylinder.mdl", vector(64, -16, 4), NULL);
you.material = mtl_nextgen;
while(!key_space)
wait(1);
mtl_shaded.technique = "std_lightmapped";
effect_load(mtl_shaded, "fx_default.fx");
}
| 17.348837 | 60 | 0.683646 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.