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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2ca9eabe4299f39cb515249a662cf7981abc1e94 | 1,275 | h | C | ow_gazebo_plugins/src/LinkForcePlugin/LinkForcePlugin.h | thewindsofwinter/ow_simulator | a92698a1cc7e80ac6aec17d74bcbac81edf726f7 | [
"NASA-1.3"
] | 97 | 2020-08-10T08:43:14.000Z | 2022-03-21T21:14:15.000Z | ow_gazebo_plugins/src/LinkForcePlugin/LinkForcePlugin.h | thewindsofwinter/ow_simulator | a92698a1cc7e80ac6aec17d74bcbac81edf726f7 | [
"NASA-1.3"
] | 153 | 2020-08-11T22:37:25.000Z | 2022-03-31T23:29:41.000Z | ow_gazebo_plugins/src/LinkForcePlugin/LinkForcePlugin.h | thewindsofwinter/ow_simulator | a92698a1cc7e80ac6aec17d74bcbac81edf726f7 | [
"NASA-1.3"
] | 26 | 2020-08-06T17:07:03.000Z | 2022-03-16T01:04:01.000Z | // The Notices and Disclaimers for Ocean Worlds Autonomy Testbed for Exploration
// Research and Simulation can be found in README.md in the root directory of
// this repository.
#ifndef LinkForcePlugin_h
#define LinkForcePlugin_h
#include <gazebo/common/Plugin.hh>
#include "ForceRow.h"
namespace gazebo {
// This plugin is added to a robot description and applies forces from a
// specified lookup table to a specified link in the robot.
class LinkForcePlugin : public ModelPlugin
{
public:
LinkForcePlugin();
~LinkForcePlugin();
virtual void Load(physics::ModelPtr _model, sdf::ElementPtr _sdf);
private:
bool LoadLookupTable(std::string filename);
void OnUpdate();
bool GetForces(int material, float depth, int pass, float rho,
std::vector<float>& out_forces);
// Find a value in a map when there is not necessarily an exact match for the key
template <typename key_t, typename value_t>
value_t FindValueForClosestKey(const std::map<key_t, value_t>& inmap, const key_t& key);
physics::LinkPtr m_link;
// Connection to the update event
event::ConnectionPtr m_updateConnection;
std::map<int, std::map<float, std::map<int, std::map<float, std::vector<float> > > > > m_forcesMap;
};
}
#endif // LinkForcePlugin_h
| 27.12766 | 101 | 0.737255 | [
"vector"
] |
2caa155fd71ffdf45d6446cd20f8f4c2e1020228 | 4,002 | h | C | include/1.4/dom/domSphere.h | maemo5/android-source-browsing.platform--external--collada | 538700ec332c8306a1283f8dfdb016e493905e6f | [
"MIT"
] | null | null | null | include/1.4/dom/domSphere.h | maemo5/android-source-browsing.platform--external--collada | 538700ec332c8306a1283f8dfdb016e493905e6f | [
"MIT"
] | null | null | null | include/1.4/dom/domSphere.h | maemo5/android-source-browsing.platform--external--collada | 538700ec332c8306a1283f8dfdb016e493905e6f | [
"MIT"
] | null | null | null | /*
* Copyright 2006 Sony Computer Entertainment Inc.
*
* Licensed under the MIT Open Source License, for details please see license.txt or the website
* http://www.opensource.org/licenses/mit-license.php
*
*/
#ifndef __domSphere_h__
#define __domSphere_h__
#include <dae/daeDocument.h>
#include <dom/domTypes.h>
#include <dom/domElements.h>
#include <dom/domExtra.h>
class DAE;
/**
* A centered sphere primitive.
*/
class domSphere : public daeElement
{
public:
virtual COLLADA_TYPE::TypeEnum getElementType() const { return COLLADA_TYPE::SPHERE; }
static daeInt ID() { return 771; }
virtual daeInt typeID() const { return ID(); }
public:
class domRadius;
typedef daeSmartRef<domRadius> domRadiusRef;
typedef daeTArray<domRadiusRef> domRadius_Array;
/**
* A float value that represents the radius of the sphere
*/
class domRadius : public daeElement
{
public:
virtual COLLADA_TYPE::TypeEnum getElementType() const { return COLLADA_TYPE::RADIUS; }
static daeInt ID() { return 772; }
virtual daeInt typeID() const { return ID(); }
protected: // Value
/**
* The domFloat value of the text data of this element.
*/
domFloat _value;
public: //Accessors and Mutators
/**
* Gets the value of this element.
* @return a domFloat of the value.
*/
domFloat getValue() const { return _value; }
/**
* Sets the _value of this element.
* @param val The new value for this element.
*/
void setValue( domFloat val ) { _value = val; }
protected:
/**
* Constructor
*/
domRadius(DAE& dae) : daeElement(dae), _value() {}
/**
* Destructor
*/
virtual ~domRadius() {}
/**
* Overloaded assignment operator
*/
virtual domRadius &operator=( const domRadius &cpy ) { (void)cpy; return *this; }
public: // STATIC METHODS
/**
* Creates an instance of this class and returns a daeElementRef referencing it.
* @return a daeElementRef referencing an instance of this object.
*/
static DLLSPEC daeElementRef create(DAE& dae);
/**
* Creates a daeMetaElement object that describes this element in the meta object reflection framework.
* If a daeMetaElement already exists it will return that instead of creating a new one.
* @return A daeMetaElement describing this COLLADA element.
*/
static DLLSPEC daeMetaElement* registerElement(DAE& dae);
};
protected: // Elements
/**
* A float value that represents the radius of the sphere @see domRadius
*/
domRadiusRef elemRadius;
/**
* The extra element may appear any number of times. @see domExtra
*/
domExtra_Array elemExtra_array;
public: //Accessors and Mutators
/**
* Gets the radius element.
* @return a daeSmartRef to the radius element.
*/
const domRadiusRef getRadius() const { return elemRadius; }
/**
* Gets the extra element array.
* @return Returns a reference to the array of extra elements.
*/
domExtra_Array &getExtra_array() { return elemExtra_array; }
/**
* Gets the extra element array.
* @return Returns a constant reference to the array of extra elements.
*/
const domExtra_Array &getExtra_array() const { return elemExtra_array; }
protected:
/**
* Constructor
*/
domSphere(DAE& dae) : daeElement(dae), elemRadius(), elemExtra_array() {}
/**
* Destructor
*/
virtual ~domSphere() {}
/**
* Overloaded assignment operator
*/
virtual domSphere &operator=( const domSphere &cpy ) { (void)cpy; return *this; }
public: // STATIC METHODS
/**
* Creates an instance of this class and returns a daeElementRef referencing it.
* @return a daeElementRef referencing an instance of this object.
*/
static DLLSPEC daeElementRef create(DAE& dae);
/**
* Creates a daeMetaElement object that describes this element in the meta object reflection framework.
* If a daeMetaElement already exists it will return that instead of creating a new one.
* @return A daeMetaElement describing this COLLADA element.
*/
static DLLSPEC daeMetaElement* registerElement(DAE& dae);
};
#endif
| 27.040541 | 105 | 0.707396 | [
"object"
] |
2caa94801ba6947854fc638cafcfc14a9d4890fd | 64,303 | c | C | dpdk/drivers/net/avp/avp_ethdev.c | muziding/jupiter | 1fd7df081f7b459ee5e951ff16ca1741f6c8e021 | [
"MIT"
] | 287 | 2017-12-17T14:48:00.000Z | 2022-03-28T06:12:07.000Z | dpdk/drivers/net/avp/avp_ethdev.c | Tominous/jupiter | 1fd7df081f7b459ee5e951ff16ca1741f6c8e021 | [
"MIT"
] | 18 | 2017-12-18T15:50:59.000Z | 2020-05-14T09:19:38.000Z | dpdk/drivers/net/avp/avp_ethdev.c | Tominous/jupiter | 1fd7df081f7b459ee5e951ff16ca1741f6c8e021 | [
"MIT"
] | 109 | 2017-12-19T03:42:09.000Z | 2022-03-25T11:25:39.000Z | /*
* BSD LICENSE
*
* Copyright (c) 2013-2017, Wind River Systems, Inc.
*
* 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 Wind River Systems nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdint.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <rte_ethdev_driver.h>
#include <rte_ethdev_pci.h>
#include <rte_memcpy.h>
#include <rte_string_fns.h>
#include <rte_malloc.h>
#include <rte_atomic.h>
#include <rte_branch_prediction.h>
#include <rte_pci.h>
#include <rte_bus_pci.h>
#include <rte_ether.h>
#include <rte_common.h>
#include <rte_cycles.h>
#include <rte_spinlock.h>
#include <rte_byteorder.h>
#include <rte_dev.h>
#include <rte_memory.h>
#include <rte_eal.h>
#include <rte_io.h>
#include "rte_avp_common.h"
#include "rte_avp_fifo.h"
#include "avp_logs.h"
int avp_logtype_driver;
static int avp_dev_create(struct rte_pci_device *pci_dev,
struct rte_eth_dev *eth_dev);
static int avp_dev_configure(struct rte_eth_dev *dev);
static int avp_dev_start(struct rte_eth_dev *dev);
static void avp_dev_stop(struct rte_eth_dev *dev);
static void avp_dev_close(struct rte_eth_dev *dev);
static void avp_dev_info_get(struct rte_eth_dev *dev,
struct rte_eth_dev_info *dev_info);
static int avp_vlan_offload_set(struct rte_eth_dev *dev, int mask);
static int avp_dev_link_update(struct rte_eth_dev *dev, int wait_to_complete);
static void avp_dev_promiscuous_enable(struct rte_eth_dev *dev);
static void avp_dev_promiscuous_disable(struct rte_eth_dev *dev);
static int avp_dev_rx_queue_setup(struct rte_eth_dev *dev,
uint16_t rx_queue_id,
uint16_t nb_rx_desc,
unsigned int socket_id,
const struct rte_eth_rxconf *rx_conf,
struct rte_mempool *pool);
static int avp_dev_tx_queue_setup(struct rte_eth_dev *dev,
uint16_t tx_queue_id,
uint16_t nb_tx_desc,
unsigned int socket_id,
const struct rte_eth_txconf *tx_conf);
static uint16_t avp_recv_scattered_pkts(void *rx_queue,
struct rte_mbuf **rx_pkts,
uint16_t nb_pkts);
static uint16_t avp_recv_pkts(void *rx_queue,
struct rte_mbuf **rx_pkts,
uint16_t nb_pkts);
static uint16_t avp_xmit_scattered_pkts(void *tx_queue,
struct rte_mbuf **tx_pkts,
uint16_t nb_pkts);
static uint16_t avp_xmit_pkts(void *tx_queue,
struct rte_mbuf **tx_pkts,
uint16_t nb_pkts);
static void avp_dev_rx_queue_release(void *rxq);
static void avp_dev_tx_queue_release(void *txq);
static int avp_dev_stats_get(struct rte_eth_dev *dev,
struct rte_eth_stats *stats);
static void avp_dev_stats_reset(struct rte_eth_dev *dev);
#define AVP_MAX_RX_BURST 64
#define AVP_MAX_TX_BURST 64
#define AVP_MAX_MAC_ADDRS 1
#define AVP_MIN_RX_BUFSIZE ETHER_MIN_LEN
/*
* Defines the number of microseconds to wait before checking the response
* queue for completion.
*/
#define AVP_REQUEST_DELAY_USECS (5000)
/*
* Defines the number times to check the response queue for completion before
* declaring a timeout.
*/
#define AVP_MAX_REQUEST_RETRY (100)
/* Defines the current PCI driver version number */
#define AVP_DPDK_DRIVER_VERSION RTE_AVP_CURRENT_GUEST_VERSION
/*
* The set of PCI devices this driver supports
*/
static const struct rte_pci_id pci_id_avp_map[] = {
{ .vendor_id = RTE_AVP_PCI_VENDOR_ID,
.device_id = RTE_AVP_PCI_DEVICE_ID,
.subsystem_vendor_id = RTE_AVP_PCI_SUB_VENDOR_ID,
.subsystem_device_id = RTE_AVP_PCI_SUB_DEVICE_ID,
.class_id = RTE_CLASS_ANY_ID,
},
{ .vendor_id = 0, /* sentinel */
},
};
/*
* dev_ops for avp, bare necessities for basic operation
*/
static const struct eth_dev_ops avp_eth_dev_ops = {
.dev_configure = avp_dev_configure,
.dev_start = avp_dev_start,
.dev_stop = avp_dev_stop,
.dev_close = avp_dev_close,
.dev_infos_get = avp_dev_info_get,
.vlan_offload_set = avp_vlan_offload_set,
.stats_get = avp_dev_stats_get,
.stats_reset = avp_dev_stats_reset,
.link_update = avp_dev_link_update,
.promiscuous_enable = avp_dev_promiscuous_enable,
.promiscuous_disable = avp_dev_promiscuous_disable,
.rx_queue_setup = avp_dev_rx_queue_setup,
.rx_queue_release = avp_dev_rx_queue_release,
.tx_queue_setup = avp_dev_tx_queue_setup,
.tx_queue_release = avp_dev_tx_queue_release,
};
/**@{ AVP device flags */
#define AVP_F_PROMISC (1 << 1)
#define AVP_F_CONFIGURED (1 << 2)
#define AVP_F_LINKUP (1 << 3)
#define AVP_F_DETACHED (1 << 4)
/**@} */
/* Ethernet device validation marker */
#define AVP_ETHDEV_MAGIC 0x92972862
/*
* Defines the AVP device attributes which are attached to an RTE ethernet
* device
*/
struct avp_dev {
uint32_t magic; /**< Memory validation marker */
uint64_t device_id; /**< Unique system identifier */
struct ether_addr ethaddr; /**< Host specified MAC address */
struct rte_eth_dev_data *dev_data;
/**< Back pointer to ethernet device data */
volatile uint32_t flags; /**< Device operational flags */
uint16_t port_id; /**< Ethernet port identifier */
struct rte_mempool *pool; /**< pkt mbuf mempool */
unsigned int guest_mbuf_size; /**< local pool mbuf size */
unsigned int host_mbuf_size; /**< host mbuf size */
unsigned int max_rx_pkt_len; /**< maximum receive unit */
uint32_t host_features; /**< Supported feature bitmap */
uint32_t features; /**< Enabled feature bitmap */
unsigned int num_tx_queues; /**< Negotiated number of transmit queues */
unsigned int max_tx_queues; /**< Maximum number of transmit queues */
unsigned int num_rx_queues; /**< Negotiated number of receive queues */
unsigned int max_rx_queues; /**< Maximum number of receive queues */
struct rte_avp_fifo *tx_q[RTE_AVP_MAX_QUEUES]; /**< TX queue */
struct rte_avp_fifo *rx_q[RTE_AVP_MAX_QUEUES]; /**< RX queue */
struct rte_avp_fifo *alloc_q[RTE_AVP_MAX_QUEUES];
/**< Allocated mbufs queue */
struct rte_avp_fifo *free_q[RTE_AVP_MAX_QUEUES];
/**< To be freed mbufs queue */
/* mutual exclusion over the 'flag' and 'resp_q/req_q' fields */
rte_spinlock_t lock;
/* For request & response */
struct rte_avp_fifo *req_q; /**< Request queue */
struct rte_avp_fifo *resp_q; /**< Response queue */
void *host_sync_addr; /**< (host) Req/Resp Mem address */
void *sync_addr; /**< Req/Resp Mem address */
void *host_mbuf_addr; /**< (host) MBUF pool start address */
void *mbuf_addr; /**< MBUF pool start address */
} __rte_cache_aligned;
/* RTE ethernet private data */
struct avp_adapter {
struct avp_dev avp;
} __rte_cache_aligned;
/* 32-bit MMIO register write */
#define AVP_WRITE32(_value, _addr) rte_write32_relaxed((_value), (_addr))
/* 32-bit MMIO register read */
#define AVP_READ32(_addr) rte_read32_relaxed((_addr))
/* Macro to cast the ethernet device private data to a AVP object */
#define AVP_DEV_PRIVATE_TO_HW(adapter) \
(&((struct avp_adapter *)adapter)->avp)
/*
* Defines the structure of a AVP device queue for the purpose of handling the
* receive and transmit burst callback functions
*/
struct avp_queue {
struct rte_eth_dev_data *dev_data;
/**< Backpointer to ethernet device data */
struct avp_dev *avp; /**< Backpointer to AVP device */
uint16_t queue_id;
/**< Queue identifier used for indexing current queue */
uint16_t queue_base;
/**< Base queue identifier for queue servicing */
uint16_t queue_limit;
/**< Maximum queue identifier for queue servicing */
uint64_t packets;
uint64_t bytes;
uint64_t errors;
};
/* send a request and wait for a response
*
* @warning must be called while holding the avp->lock spinlock.
*/
static int
avp_dev_process_request(struct avp_dev *avp, struct rte_avp_request *request)
{
unsigned int retry = AVP_MAX_REQUEST_RETRY;
void *resp_addr = NULL;
unsigned int count;
int ret;
PMD_DRV_LOG(DEBUG, "Sending request %u to host\n", request->req_id);
request->result = -ENOTSUP;
/* Discard any stale responses before starting a new request */
while (avp_fifo_get(avp->resp_q, (void **)&resp_addr, 1))
PMD_DRV_LOG(DEBUG, "Discarding stale response\n");
rte_memcpy(avp->sync_addr, request, sizeof(*request));
count = avp_fifo_put(avp->req_q, &avp->host_sync_addr, 1);
if (count < 1) {
PMD_DRV_LOG(ERR, "Cannot send request %u to host\n",
request->req_id);
ret = -EBUSY;
goto done;
}
while (retry--) {
/* wait for a response */
usleep(AVP_REQUEST_DELAY_USECS);
count = avp_fifo_count(avp->resp_q);
if (count >= 1) {
/* response received */
break;
}
if ((count < 1) && (retry == 0)) {
PMD_DRV_LOG(ERR, "Timeout while waiting for a response for %u\n",
request->req_id);
ret = -ETIME;
goto done;
}
}
/* retrieve the response */
count = avp_fifo_get(avp->resp_q, (void **)&resp_addr, 1);
if ((count != 1) || (resp_addr != avp->host_sync_addr)) {
PMD_DRV_LOG(ERR, "Invalid response from host, count=%u resp=%p host_sync_addr=%p\n",
count, resp_addr, avp->host_sync_addr);
ret = -ENODATA;
goto done;
}
/* copy to user buffer */
rte_memcpy(request, avp->sync_addr, sizeof(*request));
ret = 0;
PMD_DRV_LOG(DEBUG, "Result %d received for request %u\n",
request->result, request->req_id);
done:
return ret;
}
static int
avp_dev_ctrl_set_link_state(struct rte_eth_dev *eth_dev, unsigned int state)
{
struct avp_dev *avp = AVP_DEV_PRIVATE_TO_HW(eth_dev->data->dev_private);
struct rte_avp_request request;
int ret;
/* setup a link state change request */
memset(&request, 0, sizeof(request));
request.req_id = RTE_AVP_REQ_CFG_NETWORK_IF;
request.if_up = state;
ret = avp_dev_process_request(avp, &request);
return ret == 0 ? request.result : ret;
}
static int
avp_dev_ctrl_set_config(struct rte_eth_dev *eth_dev,
struct rte_avp_device_config *config)
{
struct avp_dev *avp = AVP_DEV_PRIVATE_TO_HW(eth_dev->data->dev_private);
struct rte_avp_request request;
int ret;
/* setup a configure request */
memset(&request, 0, sizeof(request));
request.req_id = RTE_AVP_REQ_CFG_DEVICE;
memcpy(&request.config, config, sizeof(request.config));
ret = avp_dev_process_request(avp, &request);
return ret == 0 ? request.result : ret;
}
static int
avp_dev_ctrl_shutdown(struct rte_eth_dev *eth_dev)
{
struct avp_dev *avp = AVP_DEV_PRIVATE_TO_HW(eth_dev->data->dev_private);
struct rte_avp_request request;
int ret;
/* setup a shutdown request */
memset(&request, 0, sizeof(request));
request.req_id = RTE_AVP_REQ_SHUTDOWN_DEVICE;
ret = avp_dev_process_request(avp, &request);
return ret == 0 ? request.result : ret;
}
/* translate from host mbuf virtual address to guest virtual address */
static inline void *
avp_dev_translate_buffer(struct avp_dev *avp, void *host_mbuf_address)
{
return RTE_PTR_ADD(RTE_PTR_SUB(host_mbuf_address,
(uintptr_t)avp->host_mbuf_addr),
(uintptr_t)avp->mbuf_addr);
}
/* translate from host physical address to guest virtual address */
static void *
avp_dev_translate_address(struct rte_eth_dev *eth_dev,
rte_iova_t host_phys_addr)
{
struct rte_pci_device *pci_dev = RTE_ETH_DEV_TO_PCI(eth_dev);
struct rte_mem_resource *resource;
struct rte_avp_memmap_info *info;
struct rte_avp_memmap *map;
off_t offset;
void *addr;
unsigned int i;
addr = pci_dev->mem_resource[RTE_AVP_PCI_MEMORY_BAR].addr;
resource = &pci_dev->mem_resource[RTE_AVP_PCI_MEMMAP_BAR];
info = (struct rte_avp_memmap_info *)resource->addr;
offset = 0;
for (i = 0; i < info->nb_maps; i++) {
/* search all segments looking for a matching address */
map = &info->maps[i];
if ((host_phys_addr >= map->phys_addr) &&
(host_phys_addr < (map->phys_addr + map->length))) {
/* address is within this segment */
offset += (host_phys_addr - map->phys_addr);
addr = RTE_PTR_ADD(addr, offset);
PMD_DRV_LOG(DEBUG, "Translating host physical 0x%" PRIx64 " to guest virtual 0x%p\n",
host_phys_addr, addr);
return addr;
}
offset += map->length;
}
return NULL;
}
/* verify that the incoming device version is compatible with our version */
static int
avp_dev_version_check(uint32_t version)
{
uint32_t driver = RTE_AVP_STRIP_MINOR_VERSION(AVP_DPDK_DRIVER_VERSION);
uint32_t device = RTE_AVP_STRIP_MINOR_VERSION(version);
if (device <= driver) {
/* the host driver version is less than or equal to ours */
return 0;
}
return 1;
}
/* verify that memory regions have expected version and validation markers */
static int
avp_dev_check_regions(struct rte_eth_dev *eth_dev)
{
struct rte_pci_device *pci_dev = RTE_ETH_DEV_TO_PCI(eth_dev);
struct rte_avp_memmap_info *memmap;
struct rte_avp_device_info *info;
struct rte_mem_resource *resource;
unsigned int i;
/* Dump resource info for debug */
for (i = 0; i < PCI_MAX_RESOURCE; i++) {
resource = &pci_dev->mem_resource[i];
if ((resource->phys_addr == 0) || (resource->len == 0))
continue;
PMD_DRV_LOG(DEBUG, "resource[%u]: phys=0x%" PRIx64 " len=%" PRIu64 " addr=%p\n",
i, resource->phys_addr,
resource->len, resource->addr);
switch (i) {
case RTE_AVP_PCI_MEMMAP_BAR:
memmap = (struct rte_avp_memmap_info *)resource->addr;
if ((memmap->magic != RTE_AVP_MEMMAP_MAGIC) ||
(memmap->version != RTE_AVP_MEMMAP_VERSION)) {
PMD_DRV_LOG(ERR, "Invalid memmap magic 0x%08x and version %u\n",
memmap->magic, memmap->version);
return -EINVAL;
}
break;
case RTE_AVP_PCI_DEVICE_BAR:
info = (struct rte_avp_device_info *)resource->addr;
if ((info->magic != RTE_AVP_DEVICE_MAGIC) ||
avp_dev_version_check(info->version)) {
PMD_DRV_LOG(ERR, "Invalid device info magic 0x%08x or version 0x%08x > 0x%08x\n",
info->magic, info->version,
AVP_DPDK_DRIVER_VERSION);
return -EINVAL;
}
break;
case RTE_AVP_PCI_MEMORY_BAR:
case RTE_AVP_PCI_MMIO_BAR:
if (resource->addr == NULL) {
PMD_DRV_LOG(ERR, "Missing address space for BAR%u\n",
i);
return -EINVAL;
}
break;
case RTE_AVP_PCI_MSIX_BAR:
default:
/* no validation required */
break;
}
}
return 0;
}
static int
avp_dev_detach(struct rte_eth_dev *eth_dev)
{
struct avp_dev *avp = AVP_DEV_PRIVATE_TO_HW(eth_dev->data->dev_private);
int ret;
PMD_DRV_LOG(NOTICE, "Detaching port %u from AVP device 0x%" PRIx64 "\n",
eth_dev->data->port_id, avp->device_id);
rte_spinlock_lock(&avp->lock);
if (avp->flags & AVP_F_DETACHED) {
PMD_DRV_LOG(NOTICE, "port %u already detached\n",
eth_dev->data->port_id);
ret = 0;
goto unlock;
}
/* shutdown the device first so the host stops sending us packets. */
ret = avp_dev_ctrl_shutdown(eth_dev);
if (ret < 0) {
PMD_DRV_LOG(ERR, "Failed to send/recv shutdown to host, ret=%d\n",
ret);
avp->flags &= ~AVP_F_DETACHED;
goto unlock;
}
avp->flags |= AVP_F_DETACHED;
rte_wmb();
/* wait for queues to acknowledge the presence of the detach flag */
rte_delay_ms(1);
ret = 0;
unlock:
rte_spinlock_unlock(&avp->lock);
return ret;
}
static void
_avp_set_rx_queue_mappings(struct rte_eth_dev *eth_dev, uint16_t rx_queue_id)
{
struct avp_dev *avp =
AVP_DEV_PRIVATE_TO_HW(eth_dev->data->dev_private);
struct avp_queue *rxq;
uint16_t queue_count;
uint16_t remainder;
rxq = (struct avp_queue *)eth_dev->data->rx_queues[rx_queue_id];
/*
* Must map all AVP fifos as evenly as possible between the configured
* device queues. Each device queue will service a subset of the AVP
* fifos. If there is an odd number of device queues the first set of
* device queues will get the extra AVP fifos.
*/
queue_count = avp->num_rx_queues / eth_dev->data->nb_rx_queues;
remainder = avp->num_rx_queues % eth_dev->data->nb_rx_queues;
if (rx_queue_id < remainder) {
/* these queues must service one extra FIFO */
rxq->queue_base = rx_queue_id * (queue_count + 1);
rxq->queue_limit = rxq->queue_base + (queue_count + 1) - 1;
} else {
/* these queues service the regular number of FIFO */
rxq->queue_base = ((remainder * (queue_count + 1)) +
((rx_queue_id - remainder) * queue_count));
rxq->queue_limit = rxq->queue_base + queue_count - 1;
}
PMD_DRV_LOG(DEBUG, "rxq %u at %p base %u limit %u\n",
rx_queue_id, rxq, rxq->queue_base, rxq->queue_limit);
rxq->queue_id = rxq->queue_base;
}
static void
_avp_set_queue_counts(struct rte_eth_dev *eth_dev)
{
struct rte_pci_device *pci_dev = RTE_ETH_DEV_TO_PCI(eth_dev);
struct avp_dev *avp = AVP_DEV_PRIVATE_TO_HW(eth_dev->data->dev_private);
struct rte_avp_device_info *host_info;
void *addr;
addr = pci_dev->mem_resource[RTE_AVP_PCI_DEVICE_BAR].addr;
host_info = (struct rte_avp_device_info *)addr;
/*
* the transmit direction is not negotiated beyond respecting the max
* number of queues because the host can handle arbitrary guest tx
* queues (host rx queues).
*/
avp->num_tx_queues = eth_dev->data->nb_tx_queues;
/*
* the receive direction is more restrictive. The host requires a
* minimum number of guest rx queues (host tx queues) therefore
* negotiate a value that is at least as large as the host minimum
* requirement. If the host and guest values are not identical then a
* mapping will be established in the receive_queue_setup function.
*/
avp->num_rx_queues = RTE_MAX(host_info->min_rx_queues,
eth_dev->data->nb_rx_queues);
PMD_DRV_LOG(DEBUG, "Requesting %u Tx and %u Rx queues from host\n",
avp->num_tx_queues, avp->num_rx_queues);
}
static int
avp_dev_attach(struct rte_eth_dev *eth_dev)
{
struct avp_dev *avp = AVP_DEV_PRIVATE_TO_HW(eth_dev->data->dev_private);
struct rte_avp_device_config config;
unsigned int i;
int ret;
PMD_DRV_LOG(NOTICE, "Attaching port %u to AVP device 0x%" PRIx64 "\n",
eth_dev->data->port_id, avp->device_id);
rte_spinlock_lock(&avp->lock);
if (!(avp->flags & AVP_F_DETACHED)) {
PMD_DRV_LOG(NOTICE, "port %u already attached\n",
eth_dev->data->port_id);
ret = 0;
goto unlock;
}
/*
* make sure that the detached flag is set prior to reconfiguring the
* queues.
*/
avp->flags |= AVP_F_DETACHED;
rte_wmb();
/*
* re-run the device create utility which will parse the new host info
* and setup the AVP device queue pointers.
*/
ret = avp_dev_create(RTE_ETH_DEV_TO_PCI(eth_dev), eth_dev);
if (ret < 0) {
PMD_DRV_LOG(ERR, "Failed to re-create AVP device, ret=%d\n",
ret);
goto unlock;
}
if (avp->flags & AVP_F_CONFIGURED) {
/*
* Update the receive queue mapping to handle cases where the
* source and destination hosts have different queue
* requirements. As long as the DETACHED flag is asserted the
* queue table should not be referenced so it should be safe to
* update it.
*/
_avp_set_queue_counts(eth_dev);
for (i = 0; i < eth_dev->data->nb_rx_queues; i++)
_avp_set_rx_queue_mappings(eth_dev, i);
/*
* Update the host with our config details so that it knows the
* device is active.
*/
memset(&config, 0, sizeof(config));
config.device_id = avp->device_id;
config.driver_type = RTE_AVP_DRIVER_TYPE_DPDK;
config.driver_version = AVP_DPDK_DRIVER_VERSION;
config.features = avp->features;
config.num_tx_queues = avp->num_tx_queues;
config.num_rx_queues = avp->num_rx_queues;
config.if_up = !!(avp->flags & AVP_F_LINKUP);
ret = avp_dev_ctrl_set_config(eth_dev, &config);
if (ret < 0) {
PMD_DRV_LOG(ERR, "Config request failed by host, ret=%d\n",
ret);
goto unlock;
}
}
rte_wmb();
avp->flags &= ~AVP_F_DETACHED;
ret = 0;
unlock:
rte_spinlock_unlock(&avp->lock);
return ret;
}
static void
avp_dev_interrupt_handler(void *data)
{
struct rte_eth_dev *eth_dev = data;
struct rte_pci_device *pci_dev = RTE_ETH_DEV_TO_PCI(eth_dev);
void *registers = pci_dev->mem_resource[RTE_AVP_PCI_MMIO_BAR].addr;
uint32_t status, value;
int ret;
if (registers == NULL)
rte_panic("no mapped MMIO register space\n");
/* read the interrupt status register
* note: this register clears on read so all raised interrupts must be
* handled or remembered for later processing
*/
status = AVP_READ32(
RTE_PTR_ADD(registers,
RTE_AVP_INTERRUPT_STATUS_OFFSET));
if (status & RTE_AVP_MIGRATION_INTERRUPT_MASK) {
/* handle interrupt based on current status */
value = AVP_READ32(
RTE_PTR_ADD(registers,
RTE_AVP_MIGRATION_STATUS_OFFSET));
switch (value) {
case RTE_AVP_MIGRATION_DETACHED:
ret = avp_dev_detach(eth_dev);
break;
case RTE_AVP_MIGRATION_ATTACHED:
ret = avp_dev_attach(eth_dev);
break;
default:
PMD_DRV_LOG(ERR, "unexpected migration status, status=%u\n",
value);
ret = -EINVAL;
}
/* acknowledge the request by writing out our current status */
value = (ret == 0 ? value : RTE_AVP_MIGRATION_ERROR);
AVP_WRITE32(value,
RTE_PTR_ADD(registers,
RTE_AVP_MIGRATION_ACK_OFFSET));
PMD_DRV_LOG(NOTICE, "AVP migration interrupt handled\n");
}
if (status & ~RTE_AVP_MIGRATION_INTERRUPT_MASK)
PMD_DRV_LOG(WARNING, "AVP unexpected interrupt, status=0x%08x\n",
status);
/* re-enable UIO interrupt handling */
ret = rte_intr_enable(&pci_dev->intr_handle);
if (ret < 0) {
PMD_DRV_LOG(ERR, "Failed to re-enable UIO interrupts, ret=%d\n",
ret);
/* continue */
}
}
static int
avp_dev_enable_interrupts(struct rte_eth_dev *eth_dev)
{
struct rte_pci_device *pci_dev = RTE_ETH_DEV_TO_PCI(eth_dev);
void *registers = pci_dev->mem_resource[RTE_AVP_PCI_MMIO_BAR].addr;
int ret;
if (registers == NULL)
return -EINVAL;
/* enable UIO interrupt handling */
ret = rte_intr_enable(&pci_dev->intr_handle);
if (ret < 0) {
PMD_DRV_LOG(ERR, "Failed to enable UIO interrupts, ret=%d\n",
ret);
return ret;
}
/* inform the device that all interrupts are enabled */
AVP_WRITE32(RTE_AVP_APP_INTERRUPTS_MASK,
RTE_PTR_ADD(registers, RTE_AVP_INTERRUPT_MASK_OFFSET));
return 0;
}
static int
avp_dev_disable_interrupts(struct rte_eth_dev *eth_dev)
{
struct rte_pci_device *pci_dev = RTE_ETH_DEV_TO_PCI(eth_dev);
void *registers = pci_dev->mem_resource[RTE_AVP_PCI_MMIO_BAR].addr;
int ret;
if (registers == NULL)
return 0;
/* inform the device that all interrupts are disabled */
AVP_WRITE32(RTE_AVP_NO_INTERRUPTS_MASK,
RTE_PTR_ADD(registers, RTE_AVP_INTERRUPT_MASK_OFFSET));
/* enable UIO interrupt handling */
ret = rte_intr_disable(&pci_dev->intr_handle);
if (ret < 0) {
PMD_DRV_LOG(ERR, "Failed to disable UIO interrupts, ret=%d\n",
ret);
return ret;
}
return 0;
}
static int
avp_dev_setup_interrupts(struct rte_eth_dev *eth_dev)
{
struct rte_pci_device *pci_dev = RTE_ETH_DEV_TO_PCI(eth_dev);
int ret;
/* register a callback handler with UIO for interrupt notifications */
ret = rte_intr_callback_register(&pci_dev->intr_handle,
avp_dev_interrupt_handler,
(void *)eth_dev);
if (ret < 0) {
PMD_DRV_LOG(ERR, "Failed to register UIO interrupt callback, ret=%d\n",
ret);
return ret;
}
/* enable interrupt processing */
return avp_dev_enable_interrupts(eth_dev);
}
static int
avp_dev_migration_pending(struct rte_eth_dev *eth_dev)
{
struct rte_pci_device *pci_dev = RTE_ETH_DEV_TO_PCI(eth_dev);
void *registers = pci_dev->mem_resource[RTE_AVP_PCI_MMIO_BAR].addr;
uint32_t value;
if (registers == NULL)
return 0;
value = AVP_READ32(RTE_PTR_ADD(registers,
RTE_AVP_MIGRATION_STATUS_OFFSET));
if (value == RTE_AVP_MIGRATION_DETACHED) {
/* migration is in progress; ack it if we have not already */
AVP_WRITE32(value,
RTE_PTR_ADD(registers,
RTE_AVP_MIGRATION_ACK_OFFSET));
return 1;
}
return 0;
}
/*
* create a AVP device using the supplied device info by first translating it
* to guest address space(s).
*/
static int
avp_dev_create(struct rte_pci_device *pci_dev,
struct rte_eth_dev *eth_dev)
{
struct avp_dev *avp = AVP_DEV_PRIVATE_TO_HW(eth_dev->data->dev_private);
struct rte_avp_device_info *host_info;
struct rte_mem_resource *resource;
unsigned int i;
resource = &pci_dev->mem_resource[RTE_AVP_PCI_DEVICE_BAR];
if (resource->addr == NULL) {
PMD_DRV_LOG(ERR, "BAR%u is not mapped\n",
RTE_AVP_PCI_DEVICE_BAR);
return -EFAULT;
}
host_info = (struct rte_avp_device_info *)resource->addr;
if ((host_info->magic != RTE_AVP_DEVICE_MAGIC) ||
avp_dev_version_check(host_info->version)) {
PMD_DRV_LOG(ERR, "Invalid AVP PCI device, magic 0x%08x version 0x%08x > 0x%08x\n",
host_info->magic, host_info->version,
AVP_DPDK_DRIVER_VERSION);
return -EINVAL;
}
PMD_DRV_LOG(DEBUG, "AVP host device is v%u.%u.%u\n",
RTE_AVP_GET_RELEASE_VERSION(host_info->version),
RTE_AVP_GET_MAJOR_VERSION(host_info->version),
RTE_AVP_GET_MINOR_VERSION(host_info->version));
PMD_DRV_LOG(DEBUG, "AVP host supports %u to %u TX queue(s)\n",
host_info->min_tx_queues, host_info->max_tx_queues);
PMD_DRV_LOG(DEBUG, "AVP host supports %u to %u RX queue(s)\n",
host_info->min_rx_queues, host_info->max_rx_queues);
PMD_DRV_LOG(DEBUG, "AVP host supports features 0x%08x\n",
host_info->features);
if (avp->magic != AVP_ETHDEV_MAGIC) {
/*
* First time initialization (i.e., not during a VM
* migration)
*/
memset(avp, 0, sizeof(*avp));
avp->magic = AVP_ETHDEV_MAGIC;
avp->dev_data = eth_dev->data;
avp->port_id = eth_dev->data->port_id;
avp->host_mbuf_size = host_info->mbuf_size;
avp->host_features = host_info->features;
rte_spinlock_init(&avp->lock);
memcpy(&avp->ethaddr.addr_bytes[0],
host_info->ethaddr, ETHER_ADDR_LEN);
/* adjust max values to not exceed our max */
avp->max_tx_queues =
RTE_MIN(host_info->max_tx_queues, RTE_AVP_MAX_QUEUES);
avp->max_rx_queues =
RTE_MIN(host_info->max_rx_queues, RTE_AVP_MAX_QUEUES);
} else {
/* Re-attaching during migration */
/* TODO... requires validation of host values */
if ((host_info->features & avp->features) != avp->features) {
PMD_DRV_LOG(ERR, "AVP host features mismatched; 0x%08x, host=0x%08x\n",
avp->features, host_info->features);
/* this should not be possible; continue for now */
}
}
/* the device id is allowed to change over migrations */
avp->device_id = host_info->device_id;
/* translate incoming host addresses to guest address space */
PMD_DRV_LOG(DEBUG, "AVP first host tx queue at 0x%" PRIx64 "\n",
host_info->tx_phys);
PMD_DRV_LOG(DEBUG, "AVP first host alloc queue at 0x%" PRIx64 "\n",
host_info->alloc_phys);
for (i = 0; i < avp->max_tx_queues; i++) {
avp->tx_q[i] = avp_dev_translate_address(eth_dev,
host_info->tx_phys + (i * host_info->tx_size));
avp->alloc_q[i] = avp_dev_translate_address(eth_dev,
host_info->alloc_phys + (i * host_info->alloc_size));
}
PMD_DRV_LOG(DEBUG, "AVP first host rx queue at 0x%" PRIx64 "\n",
host_info->rx_phys);
PMD_DRV_LOG(DEBUG, "AVP first host free queue at 0x%" PRIx64 "\n",
host_info->free_phys);
for (i = 0; i < avp->max_rx_queues; i++) {
avp->rx_q[i] = avp_dev_translate_address(eth_dev,
host_info->rx_phys + (i * host_info->rx_size));
avp->free_q[i] = avp_dev_translate_address(eth_dev,
host_info->free_phys + (i * host_info->free_size));
}
PMD_DRV_LOG(DEBUG, "AVP host request queue at 0x%" PRIx64 "\n",
host_info->req_phys);
PMD_DRV_LOG(DEBUG, "AVP host response queue at 0x%" PRIx64 "\n",
host_info->resp_phys);
PMD_DRV_LOG(DEBUG, "AVP host sync address at 0x%" PRIx64 "\n",
host_info->sync_phys);
PMD_DRV_LOG(DEBUG, "AVP host mbuf address at 0x%" PRIx64 "\n",
host_info->mbuf_phys);
avp->req_q = avp_dev_translate_address(eth_dev, host_info->req_phys);
avp->resp_q = avp_dev_translate_address(eth_dev, host_info->resp_phys);
avp->sync_addr =
avp_dev_translate_address(eth_dev, host_info->sync_phys);
avp->mbuf_addr =
avp_dev_translate_address(eth_dev, host_info->mbuf_phys);
/*
* store the host mbuf virtual address so that we can calculate
* relative offsets for each mbuf as they are processed
*/
avp->host_mbuf_addr = host_info->mbuf_va;
avp->host_sync_addr = host_info->sync_va;
/*
* store the maximum packet length that is supported by the host.
*/
avp->max_rx_pkt_len = host_info->max_rx_pkt_len;
PMD_DRV_LOG(DEBUG, "AVP host max receive packet length is %u\n",
host_info->max_rx_pkt_len);
return 0;
}
/*
* This function is based on probe() function in avp_pci.c
* It returns 0 on success.
*/
static int
eth_avp_dev_init(struct rte_eth_dev *eth_dev)
{
struct avp_dev *avp =
AVP_DEV_PRIVATE_TO_HW(eth_dev->data->dev_private);
struct rte_pci_device *pci_dev;
int ret;
pci_dev = RTE_ETH_DEV_TO_PCI(eth_dev);
eth_dev->dev_ops = &avp_eth_dev_ops;
eth_dev->rx_pkt_burst = &avp_recv_pkts;
eth_dev->tx_pkt_burst = &avp_xmit_pkts;
if (rte_eal_process_type() != RTE_PROC_PRIMARY) {
/*
* no setup required on secondary processes. All data is saved
* in dev_private by the primary process. All resource should
* be mapped to the same virtual address so all pointers should
* be valid.
*/
if (eth_dev->data->scattered_rx) {
PMD_DRV_LOG(NOTICE, "AVP device configured for chained mbufs\n");
eth_dev->rx_pkt_burst = avp_recv_scattered_pkts;
eth_dev->tx_pkt_burst = avp_xmit_scattered_pkts;
}
return 0;
}
rte_eth_copy_pci_info(eth_dev, pci_dev);
/* Check current migration status */
if (avp_dev_migration_pending(eth_dev)) {
PMD_DRV_LOG(ERR, "VM live migration operation in progress\n");
return -EBUSY;
}
/* Check BAR resources */
ret = avp_dev_check_regions(eth_dev);
if (ret < 0) {
PMD_DRV_LOG(ERR, "Failed to validate BAR resources, ret=%d\n",
ret);
return ret;
}
/* Enable interrupts */
ret = avp_dev_setup_interrupts(eth_dev);
if (ret < 0) {
PMD_DRV_LOG(ERR, "Failed to enable interrupts, ret=%d\n", ret);
return ret;
}
/* Handle each subtype */
ret = avp_dev_create(pci_dev, eth_dev);
if (ret < 0) {
PMD_DRV_LOG(ERR, "Failed to create device, ret=%d\n", ret);
return ret;
}
/* Allocate memory for storing MAC addresses */
eth_dev->data->mac_addrs = rte_zmalloc("avp_ethdev", ETHER_ADDR_LEN, 0);
if (eth_dev->data->mac_addrs == NULL) {
PMD_DRV_LOG(ERR, "Failed to allocate %d bytes needed to store MAC addresses\n",
ETHER_ADDR_LEN);
return -ENOMEM;
}
/* Get a mac from device config */
ether_addr_copy(&avp->ethaddr, ð_dev->data->mac_addrs[0]);
return 0;
}
static int
eth_avp_dev_uninit(struct rte_eth_dev *eth_dev)
{
int ret;
if (rte_eal_process_type() != RTE_PROC_PRIMARY)
return -EPERM;
if (eth_dev->data == NULL)
return 0;
ret = avp_dev_disable_interrupts(eth_dev);
if (ret != 0) {
PMD_DRV_LOG(ERR, "Failed to disable interrupts, ret=%d\n", ret);
return ret;
}
if (eth_dev->data->mac_addrs != NULL) {
rte_free(eth_dev->data->mac_addrs);
eth_dev->data->mac_addrs = NULL;
}
return 0;
}
static int
eth_avp_pci_probe(struct rte_pci_driver *pci_drv __rte_unused,
struct rte_pci_device *pci_dev)
{
return rte_eth_dev_pci_generic_probe(pci_dev, sizeof(struct avp_adapter),
eth_avp_dev_init);
}
static int
eth_avp_pci_remove(struct rte_pci_device *pci_dev)
{
return rte_eth_dev_pci_generic_remove(pci_dev,
eth_avp_dev_uninit);
}
static struct rte_pci_driver rte_avp_pmd = {
.id_table = pci_id_avp_map,
.drv_flags = RTE_PCI_DRV_NEED_MAPPING,
.probe = eth_avp_pci_probe,
.remove = eth_avp_pci_remove,
};
static int
avp_dev_enable_scattered(struct rte_eth_dev *eth_dev,
struct avp_dev *avp)
{
unsigned int max_rx_pkt_len;
max_rx_pkt_len = eth_dev->data->dev_conf.rxmode.max_rx_pkt_len;
if ((max_rx_pkt_len > avp->guest_mbuf_size) ||
(max_rx_pkt_len > avp->host_mbuf_size)) {
/*
* If the guest MTU is greater than either the host or guest
* buffers then chained mbufs have to be enabled in the TX
* direction. It is assumed that the application will not need
* to send packets larger than their max_rx_pkt_len (MRU).
*/
return 1;
}
if ((avp->max_rx_pkt_len > avp->guest_mbuf_size) ||
(avp->max_rx_pkt_len > avp->host_mbuf_size)) {
/*
* If the host MRU is greater than its own mbuf size or the
* guest mbuf size then chained mbufs have to be enabled in the
* RX direction.
*/
return 1;
}
return 0;
}
static int
avp_dev_rx_queue_setup(struct rte_eth_dev *eth_dev,
uint16_t rx_queue_id,
uint16_t nb_rx_desc,
unsigned int socket_id,
const struct rte_eth_rxconf *rx_conf,
struct rte_mempool *pool)
{
struct avp_dev *avp = AVP_DEV_PRIVATE_TO_HW(eth_dev->data->dev_private);
struct rte_pktmbuf_pool_private *mbp_priv;
struct avp_queue *rxq;
if (rx_queue_id >= eth_dev->data->nb_rx_queues) {
PMD_DRV_LOG(ERR, "RX queue id is out of range: rx_queue_id=%u, nb_rx_queues=%u\n",
rx_queue_id, eth_dev->data->nb_rx_queues);
return -EINVAL;
}
/* Save mbuf pool pointer */
avp->pool = pool;
/* Save the local mbuf size */
mbp_priv = rte_mempool_get_priv(pool);
avp->guest_mbuf_size = (uint16_t)(mbp_priv->mbuf_data_room_size);
avp->guest_mbuf_size -= RTE_PKTMBUF_HEADROOM;
if (avp_dev_enable_scattered(eth_dev, avp)) {
if (!eth_dev->data->scattered_rx) {
PMD_DRV_LOG(NOTICE, "AVP device configured for chained mbufs\n");
eth_dev->data->scattered_rx = 1;
eth_dev->rx_pkt_burst = avp_recv_scattered_pkts;
eth_dev->tx_pkt_burst = avp_xmit_scattered_pkts;
}
}
PMD_DRV_LOG(DEBUG, "AVP max_rx_pkt_len=(%u,%u) mbuf_size=(%u,%u)\n",
avp->max_rx_pkt_len,
eth_dev->data->dev_conf.rxmode.max_rx_pkt_len,
avp->host_mbuf_size,
avp->guest_mbuf_size);
/* allocate a queue object */
rxq = rte_zmalloc_socket("ethdev RX queue", sizeof(struct avp_queue),
RTE_CACHE_LINE_SIZE, socket_id);
if (rxq == NULL) {
PMD_DRV_LOG(ERR, "Failed to allocate new Rx queue object\n");
return -ENOMEM;
}
/* save back pointers to AVP and Ethernet devices */
rxq->avp = avp;
rxq->dev_data = eth_dev->data;
eth_dev->data->rx_queues[rx_queue_id] = (void *)rxq;
/* setup the queue receive mapping for the current queue. */
_avp_set_rx_queue_mappings(eth_dev, rx_queue_id);
PMD_DRV_LOG(DEBUG, "Rx queue %u setup at %p\n", rx_queue_id, rxq);
(void)nb_rx_desc;
(void)rx_conf;
return 0;
}
static int
avp_dev_tx_queue_setup(struct rte_eth_dev *eth_dev,
uint16_t tx_queue_id,
uint16_t nb_tx_desc,
unsigned int socket_id,
const struct rte_eth_txconf *tx_conf)
{
struct avp_dev *avp = AVP_DEV_PRIVATE_TO_HW(eth_dev->data->dev_private);
struct avp_queue *txq;
if (tx_queue_id >= eth_dev->data->nb_tx_queues) {
PMD_DRV_LOG(ERR, "TX queue id is out of range: tx_queue_id=%u, nb_tx_queues=%u\n",
tx_queue_id, eth_dev->data->nb_tx_queues);
return -EINVAL;
}
/* allocate a queue object */
txq = rte_zmalloc_socket("ethdev TX queue", sizeof(struct avp_queue),
RTE_CACHE_LINE_SIZE, socket_id);
if (txq == NULL) {
PMD_DRV_LOG(ERR, "Failed to allocate new Tx queue object\n");
return -ENOMEM;
}
/* only the configured set of transmit queues are used */
txq->queue_id = tx_queue_id;
txq->queue_base = tx_queue_id;
txq->queue_limit = tx_queue_id;
/* save back pointers to AVP and Ethernet devices */
txq->avp = avp;
txq->dev_data = eth_dev->data;
eth_dev->data->tx_queues[tx_queue_id] = (void *)txq;
PMD_DRV_LOG(DEBUG, "Tx queue %u setup at %p\n", tx_queue_id, txq);
(void)nb_tx_desc;
(void)tx_conf;
return 0;
}
static inline int
_avp_cmp_ether_addr(struct ether_addr *a, struct ether_addr *b)
{
uint16_t *_a = (uint16_t *)&a->addr_bytes[0];
uint16_t *_b = (uint16_t *)&b->addr_bytes[0];
return (_a[0] ^ _b[0]) | (_a[1] ^ _b[1]) | (_a[2] ^ _b[2]);
}
static inline int
_avp_mac_filter(struct avp_dev *avp, struct rte_mbuf *m)
{
struct ether_hdr *eth = rte_pktmbuf_mtod(m, struct ether_hdr *);
if (likely(_avp_cmp_ether_addr(&avp->ethaddr, ð->d_addr) == 0)) {
/* allow all packets destined to our address */
return 0;
}
if (likely(is_broadcast_ether_addr(ð->d_addr))) {
/* allow all broadcast packets */
return 0;
}
if (likely(is_multicast_ether_addr(ð->d_addr))) {
/* allow all multicast packets */
return 0;
}
if (avp->flags & AVP_F_PROMISC) {
/* allow all packets when in promiscuous mode */
return 0;
}
return -1;
}
#ifdef RTE_LIBRTE_AVP_DEBUG_BUFFERS
static inline void
__avp_dev_buffer_sanity_check(struct avp_dev *avp, struct rte_avp_desc *buf)
{
struct rte_avp_desc *first_buf;
struct rte_avp_desc *pkt_buf;
unsigned int pkt_len;
unsigned int nb_segs;
void *pkt_data;
unsigned int i;
first_buf = avp_dev_translate_buffer(avp, buf);
i = 0;
pkt_len = 0;
nb_segs = first_buf->nb_segs;
do {
/* Adjust pointers for guest addressing */
pkt_buf = avp_dev_translate_buffer(avp, buf);
if (pkt_buf == NULL)
rte_panic("bad buffer: segment %u has an invalid address %p\n",
i, buf);
pkt_data = avp_dev_translate_buffer(avp, pkt_buf->data);
if (pkt_data == NULL)
rte_panic("bad buffer: segment %u has a NULL data pointer\n",
i);
if (pkt_buf->data_len == 0)
rte_panic("bad buffer: segment %u has 0 data length\n",
i);
pkt_len += pkt_buf->data_len;
nb_segs--;
i++;
} while (nb_segs && (buf = pkt_buf->next) != NULL);
if (nb_segs != 0)
rte_panic("bad buffer: expected %u segments found %u\n",
first_buf->nb_segs, (first_buf->nb_segs - nb_segs));
if (pkt_len != first_buf->pkt_len)
rte_panic("bad buffer: expected length %u found %u\n",
first_buf->pkt_len, pkt_len);
}
#define avp_dev_buffer_sanity_check(a, b) \
__avp_dev_buffer_sanity_check((a), (b))
#else /* RTE_LIBRTE_AVP_DEBUG_BUFFERS */
#define avp_dev_buffer_sanity_check(a, b) do {} while (0)
#endif
/*
* Copy a host buffer chain to a set of mbufs. This function assumes that
* there exactly the required number of mbufs to copy all source bytes.
*/
static inline struct rte_mbuf *
avp_dev_copy_from_buffers(struct avp_dev *avp,
struct rte_avp_desc *buf,
struct rte_mbuf **mbufs,
unsigned int count)
{
struct rte_mbuf *m_previous = NULL;
struct rte_avp_desc *pkt_buf;
unsigned int total_length = 0;
unsigned int copy_length;
unsigned int src_offset;
struct rte_mbuf *m;
uint16_t ol_flags;
uint16_t vlan_tci;
void *pkt_data;
unsigned int i;
avp_dev_buffer_sanity_check(avp, buf);
/* setup the first source buffer */
pkt_buf = avp_dev_translate_buffer(avp, buf);
pkt_data = avp_dev_translate_buffer(avp, pkt_buf->data);
total_length = pkt_buf->pkt_len;
src_offset = 0;
if (pkt_buf->ol_flags & RTE_AVP_RX_VLAN_PKT) {
ol_flags = PKT_RX_VLAN;
vlan_tci = pkt_buf->vlan_tci;
} else {
ol_flags = 0;
vlan_tci = 0;
}
for (i = 0; (i < count) && (buf != NULL); i++) {
/* fill each destination buffer */
m = mbufs[i];
if (m_previous != NULL)
m_previous->next = m;
m_previous = m;
do {
/*
* Copy as many source buffers as will fit in the
* destination buffer.
*/
copy_length = RTE_MIN((avp->guest_mbuf_size -
rte_pktmbuf_data_len(m)),
(pkt_buf->data_len -
src_offset));
rte_memcpy(RTE_PTR_ADD(rte_pktmbuf_mtod(m, void *),
rte_pktmbuf_data_len(m)),
RTE_PTR_ADD(pkt_data, src_offset),
copy_length);
rte_pktmbuf_data_len(m) += copy_length;
src_offset += copy_length;
if (likely(src_offset == pkt_buf->data_len)) {
/* need a new source buffer */
buf = pkt_buf->next;
if (buf != NULL) {
pkt_buf = avp_dev_translate_buffer(
avp, buf);
pkt_data = avp_dev_translate_buffer(
avp, pkt_buf->data);
src_offset = 0;
}
}
if (unlikely(rte_pktmbuf_data_len(m) ==
avp->guest_mbuf_size)) {
/* need a new destination mbuf */
break;
}
} while (buf != NULL);
}
m = mbufs[0];
m->ol_flags = ol_flags;
m->nb_segs = count;
rte_pktmbuf_pkt_len(m) = total_length;
m->vlan_tci = vlan_tci;
__rte_mbuf_sanity_check(m, 1);
return m;
}
static uint16_t
avp_recv_scattered_pkts(void *rx_queue,
struct rte_mbuf **rx_pkts,
uint16_t nb_pkts)
{
struct avp_queue *rxq = (struct avp_queue *)rx_queue;
struct rte_avp_desc *avp_bufs[AVP_MAX_RX_BURST];
struct rte_mbuf *mbufs[RTE_AVP_MAX_MBUF_SEGMENTS];
struct avp_dev *avp = rxq->avp;
struct rte_avp_desc *pkt_buf;
struct rte_avp_fifo *free_q;
struct rte_avp_fifo *rx_q;
struct rte_avp_desc *buf;
unsigned int count, avail, n;
unsigned int guest_mbuf_size;
struct rte_mbuf *m;
unsigned int required;
unsigned int buf_len;
unsigned int port_id;
unsigned int i;
if (unlikely(avp->flags & AVP_F_DETACHED)) {
/* VM live migration in progress */
return 0;
}
guest_mbuf_size = avp->guest_mbuf_size;
port_id = avp->port_id;
rx_q = avp->rx_q[rxq->queue_id];
free_q = avp->free_q[rxq->queue_id];
/* setup next queue to service */
rxq->queue_id = (rxq->queue_id < rxq->queue_limit) ?
(rxq->queue_id + 1) : rxq->queue_base;
/* determine how many slots are available in the free queue */
count = avp_fifo_free_count(free_q);
/* determine how many packets are available in the rx queue */
avail = avp_fifo_count(rx_q);
/* determine how many packets can be received */
count = RTE_MIN(count, avail);
count = RTE_MIN(count, nb_pkts);
count = RTE_MIN(count, (unsigned int)AVP_MAX_RX_BURST);
if (unlikely(count == 0)) {
/* no free buffers, or no buffers on the rx queue */
return 0;
}
/* retrieve pending packets */
n = avp_fifo_get(rx_q, (void **)&avp_bufs, count);
PMD_RX_LOG(DEBUG, "Receiving %u packets from Rx queue at %p\n",
count, rx_q);
count = 0;
for (i = 0; i < n; i++) {
/* prefetch next entry while processing current one */
if (i + 1 < n) {
pkt_buf = avp_dev_translate_buffer(avp,
avp_bufs[i + 1]);
rte_prefetch0(pkt_buf);
}
buf = avp_bufs[i];
/* Peek into the first buffer to determine the total length */
pkt_buf = avp_dev_translate_buffer(avp, buf);
buf_len = pkt_buf->pkt_len;
/* Allocate enough mbufs to receive the entire packet */
required = (buf_len + guest_mbuf_size - 1) / guest_mbuf_size;
if (rte_pktmbuf_alloc_bulk(avp->pool, mbufs, required)) {
rxq->dev_data->rx_mbuf_alloc_failed++;
continue;
}
/* Copy the data from the buffers to our mbufs */
m = avp_dev_copy_from_buffers(avp, buf, mbufs, required);
/* finalize mbuf */
m->port = port_id;
if (_avp_mac_filter(avp, m) != 0) {
/* silently discard packets not destined to our MAC */
rte_pktmbuf_free(m);
continue;
}
/* return new mbuf to caller */
rx_pkts[count++] = m;
rxq->bytes += buf_len;
}
rxq->packets += count;
/* return the buffers to the free queue */
avp_fifo_put(free_q, (void **)&avp_bufs[0], n);
return count;
}
static uint16_t
avp_recv_pkts(void *rx_queue,
struct rte_mbuf **rx_pkts,
uint16_t nb_pkts)
{
struct avp_queue *rxq = (struct avp_queue *)rx_queue;
struct rte_avp_desc *avp_bufs[AVP_MAX_RX_BURST];
struct avp_dev *avp = rxq->avp;
struct rte_avp_desc *pkt_buf;
struct rte_avp_fifo *free_q;
struct rte_avp_fifo *rx_q;
unsigned int count, avail, n;
unsigned int pkt_len;
struct rte_mbuf *m;
char *pkt_data;
unsigned int i;
if (unlikely(avp->flags & AVP_F_DETACHED)) {
/* VM live migration in progress */
return 0;
}
rx_q = avp->rx_q[rxq->queue_id];
free_q = avp->free_q[rxq->queue_id];
/* setup next queue to service */
rxq->queue_id = (rxq->queue_id < rxq->queue_limit) ?
(rxq->queue_id + 1) : rxq->queue_base;
/* determine how many slots are available in the free queue */
count = avp_fifo_free_count(free_q);
/* determine how many packets are available in the rx queue */
avail = avp_fifo_count(rx_q);
/* determine how many packets can be received */
count = RTE_MIN(count, avail);
count = RTE_MIN(count, nb_pkts);
count = RTE_MIN(count, (unsigned int)AVP_MAX_RX_BURST);
if (unlikely(count == 0)) {
/* no free buffers, or no buffers on the rx queue */
return 0;
}
/* retrieve pending packets */
n = avp_fifo_get(rx_q, (void **)&avp_bufs, count);
PMD_RX_LOG(DEBUG, "Receiving %u packets from Rx queue at %p\n",
count, rx_q);
count = 0;
for (i = 0; i < n; i++) {
/* prefetch next entry while processing current one */
if (i < n - 1) {
pkt_buf = avp_dev_translate_buffer(avp,
avp_bufs[i + 1]);
rte_prefetch0(pkt_buf);
}
/* Adjust host pointers for guest addressing */
pkt_buf = avp_dev_translate_buffer(avp, avp_bufs[i]);
pkt_data = avp_dev_translate_buffer(avp, pkt_buf->data);
pkt_len = pkt_buf->pkt_len;
if (unlikely((pkt_len > avp->guest_mbuf_size) ||
(pkt_buf->nb_segs > 1))) {
/*
* application should be using the scattered receive
* function
*/
rxq->errors++;
continue;
}
/* process each packet to be transmitted */
m = rte_pktmbuf_alloc(avp->pool);
if (unlikely(m == NULL)) {
rxq->dev_data->rx_mbuf_alloc_failed++;
continue;
}
/* copy data out of the host buffer to our buffer */
m->data_off = RTE_PKTMBUF_HEADROOM;
rte_memcpy(rte_pktmbuf_mtod(m, void *), pkt_data, pkt_len);
/* initialize the local mbuf */
rte_pktmbuf_data_len(m) = pkt_len;
rte_pktmbuf_pkt_len(m) = pkt_len;
m->port = avp->port_id;
if (pkt_buf->ol_flags & RTE_AVP_RX_VLAN_PKT) {
m->ol_flags = PKT_RX_VLAN;
m->vlan_tci = pkt_buf->vlan_tci;
}
if (_avp_mac_filter(avp, m) != 0) {
/* silently discard packets not destined to our MAC */
rte_pktmbuf_free(m);
continue;
}
/* return new mbuf to caller */
rx_pkts[count++] = m;
rxq->bytes += pkt_len;
}
rxq->packets += count;
/* return the buffers to the free queue */
avp_fifo_put(free_q, (void **)&avp_bufs[0], n);
return count;
}
/*
* Copy a chained mbuf to a set of host buffers. This function assumes that
* there are sufficient destination buffers to contain the entire source
* packet.
*/
static inline uint16_t
avp_dev_copy_to_buffers(struct avp_dev *avp,
struct rte_mbuf *mbuf,
struct rte_avp_desc **buffers,
unsigned int count)
{
struct rte_avp_desc *previous_buf = NULL;
struct rte_avp_desc *first_buf = NULL;
struct rte_avp_desc *pkt_buf;
struct rte_avp_desc *buf;
size_t total_length;
struct rte_mbuf *m;
size_t copy_length;
size_t src_offset;
char *pkt_data;
unsigned int i;
__rte_mbuf_sanity_check(mbuf, 1);
m = mbuf;
src_offset = 0;
total_length = rte_pktmbuf_pkt_len(m);
for (i = 0; (i < count) && (m != NULL); i++) {
/* fill each destination buffer */
buf = buffers[i];
if (i < count - 1) {
/* prefetch next entry while processing this one */
pkt_buf = avp_dev_translate_buffer(avp, buffers[i + 1]);
rte_prefetch0(pkt_buf);
}
/* Adjust pointers for guest addressing */
pkt_buf = avp_dev_translate_buffer(avp, buf);
pkt_data = avp_dev_translate_buffer(avp, pkt_buf->data);
/* setup the buffer chain */
if (previous_buf != NULL)
previous_buf->next = buf;
else
first_buf = pkt_buf;
previous_buf = pkt_buf;
do {
/*
* copy as many source mbuf segments as will fit in the
* destination buffer.
*/
copy_length = RTE_MIN((avp->host_mbuf_size -
pkt_buf->data_len),
(rte_pktmbuf_data_len(m) -
src_offset));
rte_memcpy(RTE_PTR_ADD(pkt_data, pkt_buf->data_len),
RTE_PTR_ADD(rte_pktmbuf_mtod(m, void *),
src_offset),
copy_length);
pkt_buf->data_len += copy_length;
src_offset += copy_length;
if (likely(src_offset == rte_pktmbuf_data_len(m))) {
/* need a new source buffer */
m = m->next;
src_offset = 0;
}
if (unlikely(pkt_buf->data_len ==
avp->host_mbuf_size)) {
/* need a new destination buffer */
break;
}
} while (m != NULL);
}
first_buf->nb_segs = count;
first_buf->pkt_len = total_length;
if (mbuf->ol_flags & PKT_TX_VLAN_PKT) {
first_buf->ol_flags |= RTE_AVP_TX_VLAN_PKT;
first_buf->vlan_tci = mbuf->vlan_tci;
}
avp_dev_buffer_sanity_check(avp, buffers[0]);
return total_length;
}
static uint16_t
avp_xmit_scattered_pkts(void *tx_queue,
struct rte_mbuf **tx_pkts,
uint16_t nb_pkts)
{
struct rte_avp_desc *avp_bufs[(AVP_MAX_TX_BURST *
RTE_AVP_MAX_MBUF_SEGMENTS)];
struct avp_queue *txq = (struct avp_queue *)tx_queue;
struct rte_avp_desc *tx_bufs[AVP_MAX_TX_BURST];
struct avp_dev *avp = txq->avp;
struct rte_avp_fifo *alloc_q;
struct rte_avp_fifo *tx_q;
unsigned int count, avail, n;
unsigned int orig_nb_pkts;
struct rte_mbuf *m;
unsigned int required;
unsigned int segments;
unsigned int tx_bytes;
unsigned int i;
orig_nb_pkts = nb_pkts;
if (unlikely(avp->flags & AVP_F_DETACHED)) {
/* VM live migration in progress */
/* TODO ... buffer for X packets then drop? */
txq->errors += nb_pkts;
return 0;
}
tx_q = avp->tx_q[txq->queue_id];
alloc_q = avp->alloc_q[txq->queue_id];
/* limit the number of transmitted packets to the max burst size */
if (unlikely(nb_pkts > AVP_MAX_TX_BURST))
nb_pkts = AVP_MAX_TX_BURST;
/* determine how many buffers are available to copy into */
avail = avp_fifo_count(alloc_q);
if (unlikely(avail > (AVP_MAX_TX_BURST *
RTE_AVP_MAX_MBUF_SEGMENTS)))
avail = AVP_MAX_TX_BURST * RTE_AVP_MAX_MBUF_SEGMENTS;
/* determine how many slots are available in the transmit queue */
count = avp_fifo_free_count(tx_q);
/* determine how many packets can be sent */
nb_pkts = RTE_MIN(count, nb_pkts);
/* determine how many packets will fit in the available buffers */
count = 0;
segments = 0;
for (i = 0; i < nb_pkts; i++) {
m = tx_pkts[i];
if (likely(i < (unsigned int)nb_pkts - 1)) {
/* prefetch next entry while processing this one */
rte_prefetch0(tx_pkts[i + 1]);
}
required = (rte_pktmbuf_pkt_len(m) + avp->host_mbuf_size - 1) /
avp->host_mbuf_size;
if (unlikely((required == 0) ||
(required > RTE_AVP_MAX_MBUF_SEGMENTS)))
break;
else if (unlikely(required + segments > avail))
break;
segments += required;
count++;
}
nb_pkts = count;
if (unlikely(nb_pkts == 0)) {
/* no available buffers, or no space on the tx queue */
txq->errors += orig_nb_pkts;
return 0;
}
PMD_TX_LOG(DEBUG, "Sending %u packets on Tx queue at %p\n",
nb_pkts, tx_q);
/* retrieve sufficient send buffers */
n = avp_fifo_get(alloc_q, (void **)&avp_bufs, segments);
if (unlikely(n != segments)) {
PMD_TX_LOG(DEBUG, "Failed to allocate buffers "
"n=%u, segments=%u, orig=%u\n",
n, segments, orig_nb_pkts);
txq->errors += orig_nb_pkts;
return 0;
}
tx_bytes = 0;
count = 0;
for (i = 0; i < nb_pkts; i++) {
/* process each packet to be transmitted */
m = tx_pkts[i];
/* determine how many buffers are required for this packet */
required = (rte_pktmbuf_pkt_len(m) + avp->host_mbuf_size - 1) /
avp->host_mbuf_size;
tx_bytes += avp_dev_copy_to_buffers(avp, m,
&avp_bufs[count], required);
tx_bufs[i] = avp_bufs[count];
count += required;
/* free the original mbuf */
rte_pktmbuf_free(m);
}
txq->packets += nb_pkts;
txq->bytes += tx_bytes;
#ifdef RTE_LIBRTE_AVP_DEBUG_BUFFERS
for (i = 0; i < nb_pkts; i++)
avp_dev_buffer_sanity_check(avp, tx_bufs[i]);
#endif
/* send the packets */
n = avp_fifo_put(tx_q, (void **)&tx_bufs[0], nb_pkts);
if (unlikely(n != orig_nb_pkts))
txq->errors += (orig_nb_pkts - n);
return n;
}
static uint16_t
avp_xmit_pkts(void *tx_queue, struct rte_mbuf **tx_pkts, uint16_t nb_pkts)
{
struct avp_queue *txq = (struct avp_queue *)tx_queue;
struct rte_avp_desc *avp_bufs[AVP_MAX_TX_BURST];
struct avp_dev *avp = txq->avp;
struct rte_avp_desc *pkt_buf;
struct rte_avp_fifo *alloc_q;
struct rte_avp_fifo *tx_q;
unsigned int count, avail, n;
struct rte_mbuf *m;
unsigned int pkt_len;
unsigned int tx_bytes;
char *pkt_data;
unsigned int i;
if (unlikely(avp->flags & AVP_F_DETACHED)) {
/* VM live migration in progress */
/* TODO ... buffer for X packets then drop?! */
txq->errors++;
return 0;
}
tx_q = avp->tx_q[txq->queue_id];
alloc_q = avp->alloc_q[txq->queue_id];
/* limit the number of transmitted packets to the max burst size */
if (unlikely(nb_pkts > AVP_MAX_TX_BURST))
nb_pkts = AVP_MAX_TX_BURST;
/* determine how many buffers are available to copy into */
avail = avp_fifo_count(alloc_q);
/* determine how many slots are available in the transmit queue */
count = avp_fifo_free_count(tx_q);
/* determine how many packets can be sent */
count = RTE_MIN(count, avail);
count = RTE_MIN(count, nb_pkts);
if (unlikely(count == 0)) {
/* no available buffers, or no space on the tx queue */
txq->errors += nb_pkts;
return 0;
}
PMD_TX_LOG(DEBUG, "Sending %u packets on Tx queue at %p\n",
count, tx_q);
/* retrieve sufficient send buffers */
n = avp_fifo_get(alloc_q, (void **)&avp_bufs, count);
if (unlikely(n != count)) {
txq->errors++;
return 0;
}
tx_bytes = 0;
for (i = 0; i < count; i++) {
/* prefetch next entry while processing the current one */
if (i < count - 1) {
pkt_buf = avp_dev_translate_buffer(avp,
avp_bufs[i + 1]);
rte_prefetch0(pkt_buf);
}
/* process each packet to be transmitted */
m = tx_pkts[i];
/* Adjust pointers for guest addressing */
pkt_buf = avp_dev_translate_buffer(avp, avp_bufs[i]);
pkt_data = avp_dev_translate_buffer(avp, pkt_buf->data);
pkt_len = rte_pktmbuf_pkt_len(m);
if (unlikely((pkt_len > avp->guest_mbuf_size) ||
(pkt_len > avp->host_mbuf_size))) {
/*
* application should be using the scattered transmit
* function; send it truncated to avoid the performance
* hit of having to manage returning the already
* allocated buffer to the free list. This should not
* happen since the application should have set the
* max_rx_pkt_len based on its MTU and it should be
* policing its own packet sizes.
*/
txq->errors++;
pkt_len = RTE_MIN(avp->guest_mbuf_size,
avp->host_mbuf_size);
}
/* copy data out of our mbuf and into the AVP buffer */
rte_memcpy(pkt_data, rte_pktmbuf_mtod(m, void *), pkt_len);
pkt_buf->pkt_len = pkt_len;
pkt_buf->data_len = pkt_len;
pkt_buf->nb_segs = 1;
pkt_buf->next = NULL;
if (m->ol_flags & PKT_TX_VLAN_PKT) {
pkt_buf->ol_flags |= RTE_AVP_TX_VLAN_PKT;
pkt_buf->vlan_tci = m->vlan_tci;
}
tx_bytes += pkt_len;
/* free the original mbuf */
rte_pktmbuf_free(m);
}
txq->packets += count;
txq->bytes += tx_bytes;
/* send the packets */
n = avp_fifo_put(tx_q, (void **)&avp_bufs[0], count);
return n;
}
static void
avp_dev_rx_queue_release(void *rx_queue)
{
struct avp_queue *rxq = (struct avp_queue *)rx_queue;
struct avp_dev *avp = rxq->avp;
struct rte_eth_dev_data *data = avp->dev_data;
unsigned int i;
for (i = 0; i < avp->num_rx_queues; i++) {
if (data->rx_queues[i] == rxq)
data->rx_queues[i] = NULL;
}
}
static void
avp_dev_tx_queue_release(void *tx_queue)
{
struct avp_queue *txq = (struct avp_queue *)tx_queue;
struct avp_dev *avp = txq->avp;
struct rte_eth_dev_data *data = avp->dev_data;
unsigned int i;
for (i = 0; i < avp->num_tx_queues; i++) {
if (data->tx_queues[i] == txq)
data->tx_queues[i] = NULL;
}
}
static int
avp_dev_configure(struct rte_eth_dev *eth_dev)
{
struct rte_pci_device *pci_dev = RTE_ETH_DEV_TO_PCI(eth_dev);
struct avp_dev *avp = AVP_DEV_PRIVATE_TO_HW(eth_dev->data->dev_private);
struct rte_avp_device_info *host_info;
struct rte_avp_device_config config;
int mask = 0;
void *addr;
int ret;
rte_spinlock_lock(&avp->lock);
if (avp->flags & AVP_F_DETACHED) {
PMD_DRV_LOG(ERR, "Operation not supported during VM live migration\n");
ret = -ENOTSUP;
goto unlock;
}
addr = pci_dev->mem_resource[RTE_AVP_PCI_DEVICE_BAR].addr;
host_info = (struct rte_avp_device_info *)addr;
/* Setup required number of queues */
_avp_set_queue_counts(eth_dev);
mask = (ETH_VLAN_STRIP_MASK |
ETH_VLAN_FILTER_MASK |
ETH_VLAN_EXTEND_MASK);
ret = avp_vlan_offload_set(eth_dev, mask);
if (ret < 0) {
PMD_DRV_LOG(ERR, "VLAN offload set failed by host, ret=%d\n",
ret);
goto unlock;
}
/* update device config */
memset(&config, 0, sizeof(config));
config.device_id = host_info->device_id;
config.driver_type = RTE_AVP_DRIVER_TYPE_DPDK;
config.driver_version = AVP_DPDK_DRIVER_VERSION;
config.features = avp->features;
config.num_tx_queues = avp->num_tx_queues;
config.num_rx_queues = avp->num_rx_queues;
ret = avp_dev_ctrl_set_config(eth_dev, &config);
if (ret < 0) {
PMD_DRV_LOG(ERR, "Config request failed by host, ret=%d\n",
ret);
goto unlock;
}
avp->flags |= AVP_F_CONFIGURED;
ret = 0;
unlock:
rte_spinlock_unlock(&avp->lock);
return ret;
}
static int
avp_dev_start(struct rte_eth_dev *eth_dev)
{
struct avp_dev *avp = AVP_DEV_PRIVATE_TO_HW(eth_dev->data->dev_private);
int ret;
rte_spinlock_lock(&avp->lock);
if (avp->flags & AVP_F_DETACHED) {
PMD_DRV_LOG(ERR, "Operation not supported during VM live migration\n");
ret = -ENOTSUP;
goto unlock;
}
/* disable features that we do not support */
eth_dev->data->dev_conf.rxmode.hw_ip_checksum = 0;
eth_dev->data->dev_conf.rxmode.hw_vlan_filter = 0;
eth_dev->data->dev_conf.rxmode.hw_vlan_extend = 0;
eth_dev->data->dev_conf.rxmode.hw_strip_crc = 0;
/* update link state */
ret = avp_dev_ctrl_set_link_state(eth_dev, 1);
if (ret < 0) {
PMD_DRV_LOG(ERR, "Link state change failed by host, ret=%d\n",
ret);
goto unlock;
}
/* remember current link state */
avp->flags |= AVP_F_LINKUP;
ret = 0;
unlock:
rte_spinlock_unlock(&avp->lock);
return ret;
}
static void
avp_dev_stop(struct rte_eth_dev *eth_dev)
{
struct avp_dev *avp = AVP_DEV_PRIVATE_TO_HW(eth_dev->data->dev_private);
int ret;
rte_spinlock_lock(&avp->lock);
if (avp->flags & AVP_F_DETACHED) {
PMD_DRV_LOG(ERR, "Operation not supported during VM live migration\n");
goto unlock;
}
/* remember current link state */
avp->flags &= ~AVP_F_LINKUP;
/* update link state */
ret = avp_dev_ctrl_set_link_state(eth_dev, 0);
if (ret < 0) {
PMD_DRV_LOG(ERR, "Link state change failed by host, ret=%d\n",
ret);
}
unlock:
rte_spinlock_unlock(&avp->lock);
}
static void
avp_dev_close(struct rte_eth_dev *eth_dev)
{
struct avp_dev *avp = AVP_DEV_PRIVATE_TO_HW(eth_dev->data->dev_private);
int ret;
rte_spinlock_lock(&avp->lock);
if (avp->flags & AVP_F_DETACHED) {
PMD_DRV_LOG(ERR, "Operation not supported during VM live migration\n");
goto unlock;
}
/* remember current link state */
avp->flags &= ~AVP_F_LINKUP;
avp->flags &= ~AVP_F_CONFIGURED;
ret = avp_dev_disable_interrupts(eth_dev);
if (ret < 0) {
PMD_DRV_LOG(ERR, "Failed to disable interrupts\n");
/* continue */
}
/* update device state */
ret = avp_dev_ctrl_shutdown(eth_dev);
if (ret < 0) {
PMD_DRV_LOG(ERR, "Device shutdown failed by host, ret=%d\n",
ret);
/* continue */
}
unlock:
rte_spinlock_unlock(&avp->lock);
}
static int
avp_dev_link_update(struct rte_eth_dev *eth_dev,
__rte_unused int wait_to_complete)
{
struct avp_dev *avp = AVP_DEV_PRIVATE_TO_HW(eth_dev->data->dev_private);
struct rte_eth_link *link = ð_dev->data->dev_link;
link->link_speed = ETH_SPEED_NUM_10G;
link->link_duplex = ETH_LINK_FULL_DUPLEX;
link->link_status = !!(avp->flags & AVP_F_LINKUP);
return -1;
}
static void
avp_dev_promiscuous_enable(struct rte_eth_dev *eth_dev)
{
struct avp_dev *avp = AVP_DEV_PRIVATE_TO_HW(eth_dev->data->dev_private);
rte_spinlock_lock(&avp->lock);
if ((avp->flags & AVP_F_PROMISC) == 0) {
avp->flags |= AVP_F_PROMISC;
PMD_DRV_LOG(DEBUG, "Promiscuous mode enabled on %u\n",
eth_dev->data->port_id);
}
rte_spinlock_unlock(&avp->lock);
}
static void
avp_dev_promiscuous_disable(struct rte_eth_dev *eth_dev)
{
struct avp_dev *avp = AVP_DEV_PRIVATE_TO_HW(eth_dev->data->dev_private);
rte_spinlock_lock(&avp->lock);
if ((avp->flags & AVP_F_PROMISC) != 0) {
avp->flags &= ~AVP_F_PROMISC;
PMD_DRV_LOG(DEBUG, "Promiscuous mode disabled on %u\n",
eth_dev->data->port_id);
}
rte_spinlock_unlock(&avp->lock);
}
static void
avp_dev_info_get(struct rte_eth_dev *eth_dev,
struct rte_eth_dev_info *dev_info)
{
struct avp_dev *avp = AVP_DEV_PRIVATE_TO_HW(eth_dev->data->dev_private);
dev_info->pci_dev = RTE_ETH_DEV_TO_PCI(eth_dev);
dev_info->max_rx_queues = avp->max_rx_queues;
dev_info->max_tx_queues = avp->max_tx_queues;
dev_info->min_rx_bufsize = AVP_MIN_RX_BUFSIZE;
dev_info->max_rx_pktlen = avp->max_rx_pkt_len;
dev_info->max_mac_addrs = AVP_MAX_MAC_ADDRS;
if (avp->host_features & RTE_AVP_FEATURE_VLAN_OFFLOAD) {
dev_info->rx_offload_capa = DEV_RX_OFFLOAD_VLAN_STRIP;
dev_info->tx_offload_capa = DEV_TX_OFFLOAD_VLAN_INSERT;
}
}
static int
avp_vlan_offload_set(struct rte_eth_dev *eth_dev, int mask)
{
struct avp_dev *avp = AVP_DEV_PRIVATE_TO_HW(eth_dev->data->dev_private);
if (mask & ETH_VLAN_STRIP_MASK) {
if (avp->host_features & RTE_AVP_FEATURE_VLAN_OFFLOAD) {
if (eth_dev->data->dev_conf.rxmode.hw_vlan_strip)
avp->features |= RTE_AVP_FEATURE_VLAN_OFFLOAD;
else
avp->features &= ~RTE_AVP_FEATURE_VLAN_OFFLOAD;
} else {
PMD_DRV_LOG(ERR, "VLAN strip offload not supported\n");
}
}
if (mask & ETH_VLAN_FILTER_MASK) {
if (eth_dev->data->dev_conf.rxmode.hw_vlan_filter)
PMD_DRV_LOG(ERR, "VLAN filter offload not supported\n");
}
if (mask & ETH_VLAN_EXTEND_MASK) {
if (eth_dev->data->dev_conf.rxmode.hw_vlan_extend)
PMD_DRV_LOG(ERR, "VLAN extend offload not supported\n");
}
return 0;
}
static int
avp_dev_stats_get(struct rte_eth_dev *eth_dev, struct rte_eth_stats *stats)
{
struct avp_dev *avp = AVP_DEV_PRIVATE_TO_HW(eth_dev->data->dev_private);
unsigned int i;
for (i = 0; i < avp->num_rx_queues; i++) {
struct avp_queue *rxq = avp->dev_data->rx_queues[i];
if (rxq) {
stats->ipackets += rxq->packets;
stats->ibytes += rxq->bytes;
stats->ierrors += rxq->errors;
stats->q_ipackets[i] += rxq->packets;
stats->q_ibytes[i] += rxq->bytes;
stats->q_errors[i] += rxq->errors;
}
}
for (i = 0; i < avp->num_tx_queues; i++) {
struct avp_queue *txq = avp->dev_data->tx_queues[i];
if (txq) {
stats->opackets += txq->packets;
stats->obytes += txq->bytes;
stats->oerrors += txq->errors;
stats->q_opackets[i] += txq->packets;
stats->q_obytes[i] += txq->bytes;
stats->q_errors[i] += txq->errors;
}
}
return 0;
}
static void
avp_dev_stats_reset(struct rte_eth_dev *eth_dev)
{
struct avp_dev *avp = AVP_DEV_PRIVATE_TO_HW(eth_dev->data->dev_private);
unsigned int i;
for (i = 0; i < avp->num_rx_queues; i++) {
struct avp_queue *rxq = avp->dev_data->rx_queues[i];
if (rxq) {
rxq->bytes = 0;
rxq->packets = 0;
rxq->errors = 0;
}
}
for (i = 0; i < avp->num_tx_queues; i++) {
struct avp_queue *txq = avp->dev_data->tx_queues[i];
if (txq) {
txq->bytes = 0;
txq->packets = 0;
txq->errors = 0;
}
}
}
RTE_PMD_REGISTER_PCI(net_avp, rte_avp_pmd);
RTE_PMD_REGISTER_PCI_TABLE(net_avp, pci_id_avp_map);
RTE_INIT(avp_init_log);
static void
avp_init_log(void)
{
avp_logtype_driver = rte_log_register("pmd.net.avp.driver");
if (avp_logtype_driver >= 0)
rte_log_set_level(avp_logtype_driver, RTE_LOG_NOTICE);
}
| 27.788678 | 88 | 0.70597 | [
"object"
] |
2caba972f5fe46edff002cc5a3ee912207eda8a4 | 68,677 | h | C | c++/src/kj/common.h | MixusMinimax/capnproto | 48db1a9cda33bad8a89f8b0285a7843f19b27ee6 | [
"MIT"
] | 1 | 2021-02-04T05:06:31.000Z | 2021-02-04T05:06:31.000Z | c++/src/kj/common.h | MixusMinimax/capnproto | 48db1a9cda33bad8a89f8b0285a7843f19b27ee6 | [
"MIT"
] | null | null | null | c++/src/kj/common.h | MixusMinimax/capnproto | 48db1a9cda33bad8a89f8b0285a7843f19b27ee6 | [
"MIT"
] | 1 | 2021-10-01T16:31:10.000Z | 2021-10-01T16:31:10.000Z | // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// Header that should be #included by everyone.
//
// This defines very simple utilities that are widely applicable.
#pragma once
#if defined(__GNUC__) || defined(__clang__)
#define KJ_BEGIN_SYSTEM_HEADER _Pragma("GCC system_header")
#elif defined(_MSC_VER)
#define KJ_BEGIN_SYSTEM_HEADER __pragma(warning(push, 0))
#define KJ_END_SYSTEM_HEADER __pragma(warning(pop))
#endif
#ifndef KJ_BEGIN_SYSTEM_HEADER
#define KJ_BEGIN_SYSTEM_HEADER
#endif
#ifndef KJ_END_SYSTEM_HEADER
#define KJ_END_SYSTEM_HEADER
#endif
#if !defined(KJ_HEADER_WARNINGS) || !KJ_HEADER_WARNINGS
#define KJ_BEGIN_HEADER KJ_BEGIN_SYSTEM_HEADER
#define KJ_END_HEADER KJ_END_SYSTEM_HEADER
#else
#define KJ_BEGIN_HEADER
#define KJ_END_HEADER
#endif
#ifdef __has_cpp_attribute
#define KJ_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)
#else
#define KJ_HAS_CPP_ATTRIBUTE(x) 0
#endif
#ifdef __has_feature
#define KJ_HAS_COMPILER_FEATURE(x) __has_feature(x)
#else
#define KJ_HAS_COMPILER_FEATURE(x) 0
#endif
KJ_BEGIN_HEADER
#ifndef KJ_NO_COMPILER_CHECK
// Technically, __cplusplus should be 201402L for C++14, but GCC 4.9 -- which is supported -- still
// had it defined to 201300L even with -std=c++14.
#if __cplusplus < 201300L && !__CDT_PARSER__ && !_MSC_VER
#error "This code requires C++14. Either your compiler does not support it or it is not enabled."
#ifdef __GNUC__
// Compiler claims compatibility with GCC, so presumably supports -std.
#error "Pass -std=c++14 on the compiler command line to enable C++14."
#endif
#endif
#ifdef __GNUC__
#if __clang__
#if __clang_major__ < 5
#warning "This library requires at least Clang 5.0."
#elif __cplusplus >= 201402L && !__has_include(<initializer_list>)
#warning "Your compiler supports C++14 but your C++ standard library does not. If your "\
"system has libc++ installed (as should be the case on e.g. Mac OSX), try adding "\
"-stdlib=libc++ to your CXXFLAGS."
#endif
#else
#if __GNUC__ < 5
#warning "This library requires at least GCC 5.0."
#endif
#endif
#elif defined(_MSC_VER)
#if _MSC_VER < 1910 && !defined(__clang__)
#error "You need Visual Studio 2017 or better to compile this code."
#endif
#else
#warning "I don't recognize your compiler. As of this writing, Clang, GCC, and Visual Studio "\
"are the only known compilers with enough C++14 support for this library. "\
"#define KJ_NO_COMPILER_CHECK to make this warning go away."
#endif
#endif
#include <stddef.h>
#include <initializer_list>
#if __linux__ && __cplusplus > 201200L
// Hack around stdlib bug with C++14 that exists on some Linux systems.
// Apparently in this mode the C library decides not to define gets() but the C++ library still
// tries to import it into the std namespace. This bug has been fixed at the source but is still
// widely present in the wild e.g. on Ubuntu 14.04.
#undef _GLIBCXX_HAVE_GETS
#endif
#if defined(_MSC_VER)
#ifndef NOMINMAX
#define NOMINMAX 1
#endif
#include <intrin.h> // __popcnt
#endif
// =======================================================================================
namespace kj {
typedef unsigned int uint;
typedef unsigned char byte;
// =======================================================================================
// Common macros, especially for common yet compiler-specific features.
// Detect whether RTTI and exceptions are enabled, assuming they are unless we have specific
// evidence to the contrary. Clients can always define KJ_NO_RTTI or KJ_NO_EXCEPTIONS explicitly
// to override these checks.
// TODO: Ideally we'd use __cpp_exceptions/__cpp_rtti not being defined as the first pass since
// that is the standard compliant way. However, it's unclear how to use those macros (or any
// others) to distinguish between the compiler supporting feature detection and the feature being
// disabled vs the compiler not supporting feature detection at all.
#if defined(__has_feature)
#if !defined(KJ_NO_RTTI) && !__has_feature(cxx_rtti)
#define KJ_NO_RTTI 1
#endif
#if !defined(KJ_NO_EXCEPTIONS) && !__has_feature(cxx_exceptions)
#define KJ_NO_EXCEPTIONS 1
#endif
#elif defined(__GNUC__)
#if !defined(KJ_NO_RTTI) && !__GXX_RTTI
#define KJ_NO_RTTI 1
#endif
#if !defined(KJ_NO_EXCEPTIONS) && !__EXCEPTIONS
#define KJ_NO_EXCEPTIONS 1
#endif
#elif defined(_MSC_VER)
#if !defined(KJ_NO_RTTI) && !defined(_CPPRTTI)
#define KJ_NO_RTTI 1
#endif
#if !defined(KJ_NO_EXCEPTIONS) && !defined(_CPPUNWIND)
#define KJ_NO_EXCEPTIONS 1
#endif
#endif
#if !defined(KJ_DEBUG) && !defined(KJ_NDEBUG)
// Heuristically decide whether to enable debug mode. If DEBUG or NDEBUG is defined, use that.
// Otherwise, fall back to checking whether optimization is enabled.
#if defined(DEBUG) || defined(_DEBUG)
#define KJ_DEBUG
#elif defined(NDEBUG)
#define KJ_NDEBUG
#elif __OPTIMIZE__
#define KJ_NDEBUG
#else
#define KJ_DEBUG
#endif
#endif
#define KJ_DISALLOW_COPY(classname) \
classname(const classname&) = delete; \
classname& operator=(const classname&) = delete
// Deletes the implicit copy constructor and assignment operator.
#ifdef __GNUC__
#define KJ_LIKELY(condition) __builtin_expect(condition, true)
#define KJ_UNLIKELY(condition) __builtin_expect(condition, false)
// Branch prediction macros. Evaluates to the condition given, but also tells the compiler that we
// expect the condition to be true/false enough of the time that it's worth hard-coding branch
// prediction.
#else
#define KJ_LIKELY(condition) (condition)
#define KJ_UNLIKELY(condition) (condition)
#endif
#if defined(KJ_DEBUG) || __NO_INLINE__
#define KJ_ALWAYS_INLINE(...) inline __VA_ARGS__
// Don't force inline in debug mode.
#else
#if defined(_MSC_VER) && !defined(__clang__)
#define KJ_ALWAYS_INLINE(...) __forceinline __VA_ARGS__
#else
#define KJ_ALWAYS_INLINE(...) inline __VA_ARGS__ __attribute__((always_inline))
#endif
// Force a function to always be inlined. Apply only to the prototype, not to the definition.
#endif
#if defined(_MSC_VER) && !defined(__clang__)
#define KJ_NOINLINE __declspec(noinline)
#else
#define KJ_NOINLINE __attribute__((noinline))
#endif
#if defined(_MSC_VER) && !__clang__
#define KJ_NORETURN(prototype) __declspec(noreturn) prototype
#define KJ_UNUSED
#define KJ_WARN_UNUSED_RESULT
// TODO(msvc): KJ_WARN_UNUSED_RESULT can use _Check_return_ on MSVC, but it's a prefix, so
// wrapping the whole prototype is needed. http://msdn.microsoft.com/en-us/library/jj159529.aspx
// Similarly, KJ_UNUSED could use __pragma(warning(suppress:...)), but again that's a prefix.
#else
#define KJ_NORETURN(prototype) prototype __attribute__((noreturn))
#define KJ_UNUSED __attribute__((unused))
#define KJ_WARN_UNUSED_RESULT __attribute__((warn_unused_result))
#endif
#if KJ_HAS_CPP_ATTRIBUTE(clang::lifetimebound)
// If this is generating too many false-positives, the user is responsible for disabling the
// problematic warning at the compiler switch level or by suppressing the place where the
// false-positive is reported through compiler-specific pragmas if available.
#define KJ_LIFETIMEBOUND [[clang::lifetimebound]]
#else
#define KJ_LIFETIMEBOUND
#endif
// Annotation that indicates the returned value is referencing a resource owned by this type (e.g.
// cStr() on a std::string). Unfortunately this lifetime can only be superficial currently & cannot
// track further. For example, there's no way to get `array.asPtr().slice(5, 6))` to warn if the
// last slice exceeds the lifetime of `array`. That's because in the general case `ArrayPtr::slice`
// can't have the lifetime bound annotation since it's not wrong to do something like:
// ArrayPtr<char> doSomething(ArrayPtr<char> foo) {
// ...
// return foo.slice(5, 6);
// }
// If `ArrayPtr::slice` had a lifetime bound then the compiler would warn about this perfectly
// legitimate method. Really there needs to be 2 more annotations. One to inherit the lifetime bound
// and another to inherit the lifetime bound from a parameter (which really could be the same thing
// by allowing a syntax like `[[clang::lifetimebound(*this)]]`.
// https://clang.llvm.org/docs/AttributeReference.html#lifetimebound
#if __clang__
#define KJ_UNUSED_MEMBER __attribute__((unused))
// Inhibits "unused" warning for member variables. Only Clang produces such a warning, while GCC
// complains if the attribute is set on members.
#else
#define KJ_UNUSED_MEMBER
#endif
#if __cplusplus > 201703L || (__clang__ && __clang_major__ >= 9 && __cplusplus >= 201103L)
// Technically this was only added to C++20 but Clang allows it for >= C++11 and spelunking the
// attributes manual indicates it first came in with Clang 9.
#define KJ_NO_UNIQUE_ADDRESS [[no_unique_address]]
#else
#define KJ_NO_UNIQUE_ADDRESS
#endif
#if KJ_HAS_COMPILER_FEATURE(thread_sanitizer) || defined(__SANITIZE_THREAD__)
#define KJ_DISABLE_TSAN __attribute__((no_sanitize("thread"), noinline))
#else
#define KJ_DISABLE_TSAN
#endif
#if __clang__
#define KJ_DEPRECATED(reason) \
__attribute__((deprecated(reason)))
#define KJ_UNAVAILABLE(reason) \
__attribute__((unavailable(reason)))
#elif __GNUC__
#define KJ_DEPRECATED(reason) \
__attribute__((deprecated))
#define KJ_UNAVAILABLE(reason)
#else
#define KJ_DEPRECATED(reason)
#define KJ_UNAVAILABLE(reason)
// TODO(msvc): Again, here, MSVC prefers a prefix, __declspec(deprecated).
#endif
#if KJ_TESTING_KJ // defined in KJ's own unit tests; others should not define this
#undef KJ_DEPRECATED
#define KJ_DEPRECATED(reason)
#endif
namespace _ { // private
KJ_NORETURN(void inlineRequireFailure(
const char* file, int line, const char* expectation, const char* macroArgs,
const char* message = nullptr));
KJ_NORETURN(void unreachable());
} // namespace _ (private)
#ifdef KJ_DEBUG
#if _MSC_VER && !defined(__clang__)
#define KJ_IREQUIRE(condition, ...) \
if (KJ_LIKELY(condition)); else ::kj::_::inlineRequireFailure( \
__FILE__, __LINE__, #condition, "" #__VA_ARGS__, __VA_ARGS__)
// Version of KJ_DREQUIRE() which is safe to use in headers that are #included by users. Used to
// check preconditions inside inline methods. KJ_IREQUIRE is particularly useful in that
// it will be enabled depending on whether the application is compiled in debug mode rather than
// whether libkj is.
#else
#define KJ_IREQUIRE(condition, ...) \
if (KJ_LIKELY(condition)); else ::kj::_::inlineRequireFailure( \
__FILE__, __LINE__, #condition, #__VA_ARGS__, ##__VA_ARGS__)
// Version of KJ_DREQUIRE() which is safe to use in headers that are #included by users. Used to
// check preconditions inside inline methods. KJ_IREQUIRE is particularly useful in that
// it will be enabled depending on whether the application is compiled in debug mode rather than
// whether libkj is.
#endif
#else
#define KJ_IREQUIRE(condition, ...)
#endif
#define KJ_IASSERT KJ_IREQUIRE
#define KJ_UNREACHABLE ::kj::_::unreachable();
// Put this on code paths that cannot be reached to suppress compiler warnings about missing
// returns.
#if __clang__
#define KJ_CLANG_KNOWS_THIS_IS_UNREACHABLE_BUT_GCC_DOESNT
#else
#define KJ_CLANG_KNOWS_THIS_IS_UNREACHABLE_BUT_GCC_DOESNT KJ_UNREACHABLE
#endif
#if __clang__
#define KJ_KNOWN_UNREACHABLE(code) \
do { \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wunreachable-code\"") \
code; \
_Pragma("clang diagnostic pop") \
} while (false)
// Suppress "unreachable code" warnings on intentionally unreachable code.
#else
// TODO(someday): Add support for non-clang compilers.
#define KJ_KNOWN_UNREACHABLE(code) do {code;} while(false)
#endif
#if KJ_HAS_CPP_ATTRIBUTE(fallthrough)
#define KJ_FALLTHROUGH [[fallthrough]]
#else
#define KJ_FALLTHROUGH
#endif
// #define KJ_STACK_ARRAY(type, name, size, minStack, maxStack)
//
// Allocate an array, preferably on the stack, unless it is too big. On GCC this will use
// variable-sized arrays. For other compilers we could just use a fixed-size array. `minStack`
// is the stack array size to use if variable-width arrays are not supported. `maxStack` is the
// maximum stack array size if variable-width arrays *are* supported.
#if __GNUC__ && !__clang__
#define KJ_STACK_ARRAY(type, name, size, minStack, maxStack) \
size_t name##_size = (size); \
bool name##_isOnStack = name##_size <= (maxStack); \
type name##_stack[kj::max(1, name##_isOnStack ? name##_size : 0)]; \
::kj::Array<type> name##_heap = name##_isOnStack ? \
nullptr : kj::heapArray<type>(name##_size); \
::kj::ArrayPtr<type> name = name##_isOnStack ? \
kj::arrayPtr(name##_stack, name##_size) : name##_heap
#else
#define KJ_STACK_ARRAY(type, name, size, minStack, maxStack) \
size_t name##_size = (size); \
bool name##_isOnStack = name##_size <= (minStack); \
type name##_stack[minStack]; \
::kj::Array<type> name##_heap = name##_isOnStack ? \
nullptr : kj::heapArray<type>(name##_size); \
::kj::ArrayPtr<type> name = name##_isOnStack ? \
kj::arrayPtr(name##_stack, name##_size) : name##_heap
#endif
#define KJ_CONCAT_(x, y) x##y
#define KJ_CONCAT(x, y) KJ_CONCAT_(x, y)
#define KJ_UNIQUE_NAME(prefix) KJ_CONCAT(prefix, __LINE__)
// Create a unique identifier name. We use concatenate __LINE__ rather than __COUNTER__ so that
// the name can be used multiple times in the same macro.
#if _MSC_VER && !defined(__clang__)
#define KJ_CONSTEXPR(...) __VA_ARGS__
// Use in cases where MSVC barfs on constexpr. A replacement keyword (e.g. "const") can be
// provided, or just leave blank to remove the keyword entirely.
//
// TODO(msvc): Remove this hack once MSVC fully supports constexpr.
#ifndef __restrict__
#define __restrict__ __restrict
// TODO(msvc): Would it be better to define a KJ_RESTRICT macro?
#endif
#pragma warning(disable: 4521 4522)
// This warning complains when there are two copy constructors, one for a const reference and
// one for a non-const reference. It is often quite necessary to do this in wrapper templates,
// therefore this warning is dumb and we disable it.
#pragma warning(disable: 4458)
// Warns when a parameter name shadows a class member. Unfortunately my code does this a lot,
// since I don't use a special name format for members.
#else // _MSC_VER
#define KJ_CONSTEXPR(...) constexpr
#endif
// =======================================================================================
// Template metaprogramming helpers.
template <typename T> struct NoInfer_ { typedef T Type; };
template <typename T> using NoInfer = typename NoInfer_<T>::Type;
// Use NoInfer<T>::Type in place of T for a template function parameter to prevent inference of
// the type based on the parameter value.
template <typename T> struct RemoveConst_ { typedef T Type; };
template <typename T> struct RemoveConst_<const T> { typedef T Type; };
template <typename T> using RemoveConst = typename RemoveConst_<T>::Type;
template <typename> struct IsLvalueReference_ { static constexpr bool value = false; };
template <typename T> struct IsLvalueReference_<T&> { static constexpr bool value = true; };
template <typename T>
inline constexpr bool isLvalueReference() { return IsLvalueReference_<T>::value; }
template <typename T> struct Decay_ { typedef T Type; };
template <typename T> struct Decay_<T&> { typedef typename Decay_<T>::Type Type; };
template <typename T> struct Decay_<T&&> { typedef typename Decay_<T>::Type Type; };
template <typename T> struct Decay_<T[]> { typedef typename Decay_<T*>::Type Type; };
template <typename T> struct Decay_<const T[]> { typedef typename Decay_<const T*>::Type Type; };
template <typename T, size_t s> struct Decay_<T[s]> { typedef typename Decay_<T*>::Type Type; };
template <typename T, size_t s> struct Decay_<const T[s]> { typedef typename Decay_<const T*>::Type Type; };
template <typename T> struct Decay_<const T> { typedef typename Decay_<T>::Type Type; };
template <typename T> struct Decay_<volatile T> { typedef typename Decay_<T>::Type Type; };
template <typename T> using Decay = typename Decay_<T>::Type;
template <bool b> struct EnableIf_;
template <> struct EnableIf_<true> { typedef void Type; };
template <bool b> using EnableIf = typename EnableIf_<b>::Type;
// Use like:
//
// template <typename T, typename = EnableIf<isValid<T>()>>
// void func(T&& t);
template <typename...> struct VoidSfinae_ { using Type = void; };
template <typename... Ts> using VoidSfinae = typename VoidSfinae_<Ts...>::Type;
// Note: VoidSfinae is std::void_t from C++17.
template <typename T>
T instance() noexcept;
// Like std::declval, but doesn't transform T into an rvalue reference. If you want that, specify
// instance<T&&>().
struct DisallowConstCopy {
// Inherit from this, or declare a member variable of this type, to prevent the class from being
// copyable from a const reference -- instead, it will only be copyable from non-const references.
// This is useful for enforcing transitive constness of contained pointers.
//
// For example, say you have a type T which contains a pointer. T has non-const methods which
// modify the value at that pointer, but T's const methods are designed to allow reading only.
// Unfortunately, if T has a regular copy constructor, someone can simply make a copy of T and
// then use it to modify the pointed-to value. However, if T inherits DisallowConstCopy, then
// callers will only be able to copy non-const instances of T. Ideally, there is some
// parallel type ImmutableT which is like a version of T that only has const methods, and can
// be copied from a const T.
//
// Note that due to C++ rules about implicit copy constructors and assignment operators, any
// type that contains or inherits from a type that disallows const copies will also automatically
// disallow const copies. Hey, cool, that's exactly what we want.
#if CAPNP_DEBUG_TYPES
// Alas! Declaring a defaulted non-const copy constructor tickles a bug which causes GCC and
// Clang to disagree on ABI, using different calling conventions to pass this type, leading to
// immediate segfaults. See:
// https://bugs.llvm.org/show_bug.cgi?id=23764
// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58074
//
// Because of this, we can't use this technique. We guard it by CAPNP_DEBUG_TYPES so that it
// still applies to the Cap'n Proto developers during internal testing.
DisallowConstCopy() = default;
DisallowConstCopy(DisallowConstCopy&) = default;
DisallowConstCopy(DisallowConstCopy&&) = default;
DisallowConstCopy& operator=(DisallowConstCopy&) = default;
DisallowConstCopy& operator=(DisallowConstCopy&&) = default;
#endif
};
#if _MSC_VER && !defined(__clang__)
#define KJ_CPCAP(obj) obj=::kj::cp(obj)
// TODO(msvc): MSVC refuses to invoke non-const versions of copy constructors in by-value lambda
// captures. Wrap your captured object in this macro to force the compiler to perform a copy.
// Example:
//
// struct Foo: DisallowConstCopy {};
// Foo foo;
// auto lambda = [KJ_CPCAP(foo)] {};
#else
#define KJ_CPCAP(obj) obj
// Clang and gcc both already perform copy capturing correctly with non-const copy constructors.
#endif
template <typename T>
struct DisallowConstCopyIfNotConst: public DisallowConstCopy {
// Inherit from this when implementing a template that contains a pointer to T and which should
// enforce transitive constness. If T is a const type, this has no effect. Otherwise, it is
// an alias for DisallowConstCopy.
};
template <typename T>
struct DisallowConstCopyIfNotConst<const T> {};
template <typename T> struct IsConst_ { static constexpr bool value = false; };
template <typename T> struct IsConst_<const T> { static constexpr bool value = true; };
template <typename T> constexpr bool isConst() { return IsConst_<T>::value; }
template <typename T> struct EnableIfNotConst_ { typedef T Type; };
template <typename T> struct EnableIfNotConst_<const T>;
template <typename T> using EnableIfNotConst = typename EnableIfNotConst_<T>::Type;
template <typename T> struct EnableIfConst_;
template <typename T> struct EnableIfConst_<const T> { typedef T Type; };
template <typename T> using EnableIfConst = typename EnableIfConst_<T>::Type;
template <typename T> struct RemoveConstOrDisable_ { struct Type; };
template <typename T> struct RemoveConstOrDisable_<const T> { typedef T Type; };
template <typename T> using RemoveConstOrDisable = typename RemoveConstOrDisable_<T>::Type;
template <typename T> struct IsReference_ { static constexpr bool value = false; };
template <typename T> struct IsReference_<T&> { static constexpr bool value = true; };
template <typename T> constexpr bool isReference() { return IsReference_<T>::value; }
template <typename From, typename To>
struct PropagateConst_ { typedef To Type; };
template <typename From, typename To>
struct PropagateConst_<const From, To> { typedef const To Type; };
template <typename From, typename To>
using PropagateConst = typename PropagateConst_<From, To>::Type;
namespace _ { // private
template <typename T>
T refIfLvalue(T&&);
} // namespace _ (private)
#define KJ_DECLTYPE_REF(exp) decltype(::kj::_::refIfLvalue(exp))
// Like decltype(exp), but if exp is an lvalue, produces a reference type.
//
// int i;
// decltype(i) i1(i); // i1 has type int.
// KJ_DECLTYPE_REF(i + 1) i2(i + 1); // i2 has type int.
// KJ_DECLTYPE_REF(i) i3(i); // i3 has type int&.
// KJ_DECLTYPE_REF(kj::mv(i)) i4(kj::mv(i)); // i4 has type int.
template <typename T, typename U> struct IsSameType_ { static constexpr bool value = false; };
template <typename T> struct IsSameType_<T, T> { static constexpr bool value = true; };
template <typename T, typename U> constexpr bool isSameType() { return IsSameType_<T, U>::value; }
template <typename T>
struct CanConvert_ {
static int sfinae(T);
static bool sfinae(...);
};
template <typename T, typename U>
constexpr bool canConvert() {
return sizeof(CanConvert_<U>::sfinae(instance<T>())) == sizeof(int);
}
#if __GNUC__ && !__clang__ && __GNUC__ < 5
template <typename T>
constexpr bool canMemcpy() {
// Returns true if T can be copied using memcpy instead of using the copy constructor or
// assignment operator.
// GCC 4 does not have __is_trivially_constructible and friends, and there doesn't seem to be
// any reliable alternative. __has_trivial_copy() and __has_trivial_assign() return the right
// thing at one point but later on they changed such that a deleted copy constructor was
// considered "trivial" (apparently technically correct, though useless). So, on GCC 4 we give up
// and assume we can't memcpy() at all, and must explicitly copy-construct everything.
return false;
}
#define KJ_ASSERT_CAN_MEMCPY(T)
#else
template <typename T>
constexpr bool canMemcpy() {
// Returns true if T can be copied using memcpy instead of using the copy constructor or
// assignment operator.
return __is_trivially_constructible(T, const T&) && __is_trivially_assignable(T, const T&);
}
#define KJ_ASSERT_CAN_MEMCPY(T) \
static_assert(kj::canMemcpy<T>(), "this code expects this type to be memcpy()-able");
#endif
template <typename T>
class Badge {
// A pattern for marking individual methods such that they can only be called from a specific
// caller class: Make the method public but give it a parameter of type `Badge<Caller>`. Only
// `Caller` can construct one, so only `Caller` can call the method.
//
// // We only allow calls from the class `Bar`.
// void foo(Badge<Bar>)
//
// The call site looks like:
//
// foo({});
//
// This pattern also works well for declaring private constructors, but still being able to use
// them with `kj::heap()`, etc.
//
// Idea from: https://awesomekling.github.io/Serenity-C++-patterns-The-Badge/
//
// Note that some forms of this idea make the copy constructor private as well, in order to
// prohibit `Badge<NotMe>(*(Badge<NotMe>*)nullptr)`. However, that would prevent badges from
// being passed through forwarding functions like `kj::heap()`, which would ruin one of the main
// use cases for this pattern in KJ. In any case, dereferencing a null pointer is UB; there are
// plenty of other ways to get access to private members if you're willing to go UB. For one-off
// debugging purposes, you might as well use `#define private public` at the top of the file.
private:
Badge() {}
friend T;
};
// =======================================================================================
// Equivalents to std::move() and std::forward(), since these are very commonly needed and the
// std header <utility> pulls in lots of other stuff.
//
// We use abbreviated names mv and fwd because these helpers (especially mv) are so commonly used
// that the cost of typing more letters outweighs the cost of being slightly harder to understand
// when first encountered.
template<typename T> constexpr T&& mv(T& t) noexcept { return static_cast<T&&>(t); }
template<typename T> constexpr T&& fwd(NoInfer<T>& t) noexcept { return static_cast<T&&>(t); }
template<typename T> constexpr T cp(T& t) noexcept { return t; }
template<typename T> constexpr T cp(const T& t) noexcept { return t; }
// Useful to force a copy, particularly to pass into a function that expects T&&.
template <typename T, typename U, bool takeT, bool uOK = true> struct ChooseType_;
template <typename T, typename U> struct ChooseType_<T, U, true, true> { typedef T Type; };
template <typename T, typename U> struct ChooseType_<T, U, true, false> { typedef T Type; };
template <typename T, typename U> struct ChooseType_<T, U, false, true> { typedef U Type; };
template <typename T, typename U>
using WiderType = typename ChooseType_<T, U, sizeof(T) >= sizeof(U)>::Type;
template <typename T, typename U>
inline constexpr auto min(T&& a, U&& b) -> WiderType<Decay<T>, Decay<U>> {
return a < b ? WiderType<Decay<T>, Decay<U>>(a) : WiderType<Decay<T>, Decay<U>>(b);
}
template <typename T, typename U>
inline constexpr auto max(T&& a, U&& b) -> WiderType<Decay<T>, Decay<U>> {
return a > b ? WiderType<Decay<T>, Decay<U>>(a) : WiderType<Decay<T>, Decay<U>>(b);
}
template <typename T, size_t s>
inline constexpr size_t size(T (&arr)[s]) { return s; }
template <typename T>
inline constexpr size_t size(T&& arr) { return arr.size(); }
// Returns the size of the parameter, whether the parameter is a regular C array or a container
// with a `.size()` method.
class MaxValue_ {
private:
template <typename T>
inline constexpr T maxSigned() const {
return (1ull << (sizeof(T) * 8 - 1)) - 1;
}
template <typename T>
inline constexpr T maxUnsigned() const {
return ~static_cast<T>(0u);
}
public:
#define _kJ_HANDLE_TYPE(T) \
inline constexpr operator signed T() const { return MaxValue_::maxSigned < signed T>(); } \
inline constexpr operator unsigned T() const { return MaxValue_::maxUnsigned<unsigned T>(); }
_kJ_HANDLE_TYPE(char)
_kJ_HANDLE_TYPE(short)
_kJ_HANDLE_TYPE(int)
_kJ_HANDLE_TYPE(long)
_kJ_HANDLE_TYPE(long long)
#undef _kJ_HANDLE_TYPE
inline constexpr operator char() const {
// `char` is different from both `signed char` and `unsigned char`, and may be signed or
// unsigned on different platforms. Ugh.
return char(-1) < 0 ? MaxValue_::maxSigned<char>()
: MaxValue_::maxUnsigned<char>();
}
};
class MinValue_ {
private:
template <typename T>
inline constexpr T minSigned() const {
return 1ull << (sizeof(T) * 8 - 1);
}
template <typename T>
inline constexpr T minUnsigned() const {
return 0u;
}
public:
#define _kJ_HANDLE_TYPE(T) \
inline constexpr operator signed T() const { return MinValue_::minSigned < signed T>(); } \
inline constexpr operator unsigned T() const { return MinValue_::minUnsigned<unsigned T>(); }
_kJ_HANDLE_TYPE(char)
_kJ_HANDLE_TYPE(short)
_kJ_HANDLE_TYPE(int)
_kJ_HANDLE_TYPE(long)
_kJ_HANDLE_TYPE(long long)
#undef _kJ_HANDLE_TYPE
inline constexpr operator char() const {
// `char` is different from both `signed char` and `unsigned char`, and may be signed or
// unsigned on different platforms. Ugh.
return char(-1) < 0 ? MinValue_::minSigned<char>()
: MinValue_::minUnsigned<char>();
}
};
static KJ_CONSTEXPR(const) MaxValue_ maxValue = MaxValue_();
// A special constant which, when cast to an integer type, takes on the maximum possible value of
// that type. This is useful to use as e.g. a parameter to a function because it will be robust
// in the face of changes to the parameter's type.
//
// `char` is not supported, but `signed char` and `unsigned char` are.
static KJ_CONSTEXPR(const) MinValue_ minValue = MinValue_();
// A special constant which, when cast to an integer type, takes on the minimum possible value
// of that type. This is useful to use as e.g. a parameter to a function because it will be robust
// in the face of changes to the parameter's type.
//
// `char` is not supported, but `signed char` and `unsigned char` are.
template <typename T>
inline bool operator==(T t, MaxValue_) { return t == Decay<T>(maxValue); }
template <typename T>
inline bool operator==(T t, MinValue_) { return t == Decay<T>(minValue); }
template <uint bits>
inline constexpr unsigned long long maxValueForBits() {
// Get the maximum integer representable in the given number of bits.
// 1ull << 64 is unfortunately undefined.
return (bits == 64 ? 0 : (1ull << bits)) - 1;
}
struct ThrowOverflow {
// Functor which throws an exception complaining about integer overflow. Usually this is used
// with the interfaces in units.h, but is defined here because Cap'n Proto wants to avoid
// including units.h when not using CAPNP_DEBUG_TYPES.
[[noreturn]] void operator()() const;
};
#if __GNUC__ || __clang__ || _MSC_VER
inline constexpr float inf() { return __builtin_huge_valf(); }
inline constexpr float nan() { return __builtin_nanf(""); }
#else
#error "Not sure how to support your compiler."
#endif
inline constexpr bool isNaN(float f) { return f != f; }
inline constexpr bool isNaN(double f) { return f != f; }
inline int popCount(unsigned int x) {
#if defined(_MSC_VER) && !defined(__clang__)
return __popcnt(x);
// Note: __popcnt returns unsigned int, but the value is clearly guaranteed to fit into an int
#else
return __builtin_popcount(x);
#endif
}
// =======================================================================================
// Useful fake containers
template <typename T>
class Range {
public:
inline constexpr Range(const T& begin, const T& end): begin_(begin), end_(end) {}
inline explicit constexpr Range(const T& end): begin_(0), end_(end) {}
class Iterator {
public:
Iterator() = default;
inline Iterator(const T& value): value(value) {}
inline const T& operator* () const { return value; }
inline const T& operator[](size_t index) const { return value + index; }
inline Iterator& operator++() { ++value; return *this; }
inline Iterator operator++(int) { return Iterator(value++); }
inline Iterator& operator--() { --value; return *this; }
inline Iterator operator--(int) { return Iterator(value--); }
inline Iterator& operator+=(ptrdiff_t amount) { value += amount; return *this; }
inline Iterator& operator-=(ptrdiff_t amount) { value -= amount; return *this; }
inline Iterator operator+ (ptrdiff_t amount) const { return Iterator(value + amount); }
inline Iterator operator- (ptrdiff_t amount) const { return Iterator(value - amount); }
inline ptrdiff_t operator- (const Iterator& other) const { return value - other.value; }
inline bool operator==(const Iterator& other) const { return value == other.value; }
inline bool operator!=(const Iterator& other) const { return value != other.value; }
inline bool operator<=(const Iterator& other) const { return value <= other.value; }
inline bool operator>=(const Iterator& other) const { return value >= other.value; }
inline bool operator< (const Iterator& other) const { return value < other.value; }
inline bool operator> (const Iterator& other) const { return value > other.value; }
private:
T value;
};
inline Iterator begin() const { return Iterator(begin_); }
inline Iterator end() const { return Iterator(end_); }
inline auto size() const -> decltype(instance<T>() - instance<T>()) { return end_ - begin_; }
private:
T begin_;
T end_;
};
template <typename T, typename U>
inline constexpr Range<WiderType<Decay<T>, Decay<U>>> range(T begin, U end) {
return Range<WiderType<Decay<T>, Decay<U>>>(begin, end);
}
template <typename T>
inline constexpr Range<Decay<T>> range(T begin, T end) { return Range<Decay<T>>(begin, end); }
// Returns a fake iterable container containing all values of T from `begin` (inclusive) to `end`
// (exclusive). Example:
//
// // Prints 1, 2, 3, 4, 5, 6, 7, 8, 9.
// for (int i: kj::range(1, 10)) { print(i); }
template <typename T>
inline constexpr Range<Decay<T>> zeroTo(T end) { return Range<Decay<T>>(end); }
// Returns a fake iterable container containing all values of T from zero (inclusive) to `end`
// (exclusive). Example:
//
// // Prints 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
// for (int i: kj::zeroTo(10)) { print(i); }
template <typename T>
inline constexpr Range<size_t> indices(T&& container) {
// Shortcut for iterating over the indices of a container:
//
// for (size_t i: kj::indices(myArray)) { handle(myArray[i]); }
return range<size_t>(0, kj::size(container));
}
template <typename T>
class Repeat {
public:
inline constexpr Repeat(const T& value, size_t count): value(value), count(count) {}
class Iterator {
public:
Iterator() = default;
inline Iterator(const T& value, size_t index): value(value), index(index) {}
inline const T& operator* () const { return value; }
inline const T& operator[](ptrdiff_t index) const { return value; }
inline Iterator& operator++() { ++index; return *this; }
inline Iterator operator++(int) { return Iterator(value, index++); }
inline Iterator& operator--() { --index; return *this; }
inline Iterator operator--(int) { return Iterator(value, index--); }
inline Iterator& operator+=(ptrdiff_t amount) { index += amount; return *this; }
inline Iterator& operator-=(ptrdiff_t amount) { index -= amount; return *this; }
inline Iterator operator+ (ptrdiff_t amount) const { return Iterator(value, index + amount); }
inline Iterator operator- (ptrdiff_t amount) const { return Iterator(value, index - amount); }
inline ptrdiff_t operator- (const Iterator& other) const { return index - other.index; }
inline bool operator==(const Iterator& other) const { return index == other.index; }
inline bool operator!=(const Iterator& other) const { return index != other.index; }
inline bool operator<=(const Iterator& other) const { return index <= other.index; }
inline bool operator>=(const Iterator& other) const { return index >= other.index; }
inline bool operator< (const Iterator& other) const { return index < other.index; }
inline bool operator> (const Iterator& other) const { return index > other.index; }
private:
T value;
size_t index;
};
inline Iterator begin() const { return Iterator(value, 0); }
inline Iterator end() const { return Iterator(value, count); }
inline size_t size() const { return count; }
inline const T& operator[](ptrdiff_t) const { return value; }
private:
T value;
size_t count;
};
template <typename T>
inline constexpr Repeat<Decay<T>> repeat(T&& value, size_t count) {
// Returns a fake iterable which contains `count` repeats of `value`. Useful for e.g. creating
// a bunch of spaces: `kj::repeat(' ', indent * 2)`
return Repeat<Decay<T>>(value, count);
}
template <typename Inner, class Mapping>
class MappedIterator: private Mapping {
// An iterator that wraps some other iterator and maps the values through a mapping function.
// The type `Mapping` must define a method `map()` which performs this mapping.
public:
template <typename... Params>
MappedIterator(Inner inner, Params&&... params)
: Mapping(kj::fwd<Params>(params)...), inner(inner) {}
inline auto operator->() const { return &Mapping::map(*inner); }
inline decltype(auto) operator* () const { return Mapping::map(*inner); }
inline decltype(auto) operator[](size_t index) const { return Mapping::map(inner[index]); }
inline MappedIterator& operator++() { ++inner; return *this; }
inline MappedIterator operator++(int) { return MappedIterator(inner++, *this); }
inline MappedIterator& operator--() { --inner; return *this; }
inline MappedIterator operator--(int) { return MappedIterator(inner--, *this); }
inline MappedIterator& operator+=(ptrdiff_t amount) { inner += amount; return *this; }
inline MappedIterator& operator-=(ptrdiff_t amount) { inner -= amount; return *this; }
inline MappedIterator operator+ (ptrdiff_t amount) const {
return MappedIterator(inner + amount, *this);
}
inline MappedIterator operator- (ptrdiff_t amount) const {
return MappedIterator(inner - amount, *this);
}
inline ptrdiff_t operator- (const MappedIterator& other) const { return inner - other.inner; }
inline bool operator==(const MappedIterator& other) const { return inner == other.inner; }
inline bool operator!=(const MappedIterator& other) const { return inner != other.inner; }
inline bool operator<=(const MappedIterator& other) const { return inner <= other.inner; }
inline bool operator>=(const MappedIterator& other) const { return inner >= other.inner; }
inline bool operator< (const MappedIterator& other) const { return inner < other.inner; }
inline bool operator> (const MappedIterator& other) const { return inner > other.inner; }
private:
Inner inner;
};
template <typename Inner, typename Mapping>
class MappedIterable: private Mapping {
// An iterable that wraps some other iterable and maps the values through a mapping function.
// The type `Mapping` must define a method `map()` which performs this mapping.
public:
template <typename... Params>
MappedIterable(Inner inner, Params&&... params)
: Mapping(kj::fwd<Params>(params)...), inner(inner) {}
typedef Decay<decltype(instance<Inner>().begin())> InnerIterator;
typedef MappedIterator<InnerIterator, Mapping> Iterator;
typedef Decay<decltype(instance<const Inner>().begin())> InnerConstIterator;
typedef MappedIterator<InnerConstIterator, Mapping> ConstIterator;
inline Iterator begin() { return { inner.begin(), (Mapping&)*this }; }
inline Iterator end() { return { inner.end(), (Mapping&)*this }; }
inline ConstIterator begin() const { return { inner.begin(), (const Mapping&)*this }; }
inline ConstIterator end() const { return { inner.end(), (const Mapping&)*this }; }
private:
Inner inner;
};
// =======================================================================================
// Manually invoking constructors and destructors
//
// ctor(x, ...) and dtor(x) invoke x's constructor or destructor, respectively.
// We want placement new, but we don't want to #include <new>. operator new cannot be defined in
// a namespace, and defining it globally conflicts with the definition in <new>. So we have to
// define a dummy type and an operator new that uses it.
namespace _ { // private
struct PlacementNew {};
} // namespace _ (private)
} // namespace kj
inline void* operator new(size_t, kj::_::PlacementNew, void* __p) noexcept {
return __p;
}
inline void operator delete(void*, kj::_::PlacementNew, void* __p) noexcept {}
namespace kj {
template <typename T, typename... Params>
inline void ctor(T& location, Params&&... params) {
new (_::PlacementNew(), &location) T(kj::fwd<Params>(params)...);
}
template <typename T>
inline void dtor(T& location) {
location.~T();
}
// =======================================================================================
// Maybe
//
// Use in cases where you want to indicate that a value may be null. Using Maybe<T&> instead of T*
// forces the caller to handle the null case in order to satisfy the compiler, thus reliably
// preventing null pointer dereferences at runtime.
//
// Maybe<T> can be implicitly constructed from T and from nullptr. Additionally, it can be
// implicitly constructed from T*, in which case the pointer is checked for nullness at runtime.
// To read the value of a Maybe<T>, do:
//
// KJ_IF_MAYBE(value, someFuncReturningMaybe()) {
// doSomething(*value);
// } else {
// maybeWasNull();
// }
//
// KJ_IF_MAYBE's first parameter is a variable name which will be defined within the following
// block. The variable will behave like a (guaranteed non-null) pointer to the Maybe's value,
// though it may or may not actually be a pointer.
//
// Note that Maybe<T&> actually just wraps a pointer, whereas Maybe<T> wraps a T and a boolean
// indicating nullness.
template <typename T>
class Maybe;
namespace _ { // private
template <typename T>
class NullableValue {
// Class whose interface behaves much like T*, but actually contains an instance of T and a
// boolean flag indicating nullness.
public:
inline NullableValue(NullableValue&& other)
: isSet(other.isSet) {
if (isSet) {
ctor(value, kj::mv(other.value));
}
}
inline NullableValue(const NullableValue& other)
: isSet(other.isSet) {
if (isSet) {
ctor(value, other.value);
}
}
inline NullableValue(NullableValue& other)
: isSet(other.isSet) {
if (isSet) {
ctor(value, other.value);
}
}
inline ~NullableValue()
#if _MSC_VER && !defined(__clang__)
// TODO(msvc): MSVC has a hard time with noexcept specifier expressions that are more complex
// than `true` or `false`. We had a workaround for VS2015, but VS2017 regressed.
noexcept(false)
#else
noexcept(noexcept(instance<T&>().~T()))
#endif
{
if (isSet) {
dtor(value);
}
}
inline T& operator*() & { return value; }
inline const T& operator*() const & { return value; }
inline T&& operator*() && { return kj::mv(value); }
inline const T&& operator*() const && { return kj::mv(value); }
inline T* operator->() { return &value; }
inline const T* operator->() const { return &value; }
inline operator T*() { return isSet ? &value : nullptr; }
inline operator const T*() const { return isSet ? &value : nullptr; }
template <typename... Params>
inline T& emplace(Params&&... params) {
if (isSet) {
isSet = false;
dtor(value);
}
ctor(value, kj::fwd<Params>(params)...);
isSet = true;
return value;
}
inline NullableValue(): isSet(false) {}
inline NullableValue(T&& t)
: isSet(true) {
ctor(value, kj::mv(t));
}
inline NullableValue(T& t)
: isSet(true) {
ctor(value, t);
}
inline NullableValue(const T& t)
: isSet(true) {
ctor(value, t);
}
template <typename U>
inline NullableValue(NullableValue<U>&& other)
: isSet(other.isSet) {
if (isSet) {
ctor(value, kj::mv(other.value));
}
}
template <typename U>
inline NullableValue(const NullableValue<U>& other)
: isSet(other.isSet) {
if (isSet) {
ctor(value, other.value);
}
}
template <typename U>
inline NullableValue(const NullableValue<U&>& other)
: isSet(other.isSet) {
if (isSet) {
ctor(value, *other.ptr);
}
}
inline NullableValue(decltype(nullptr)): isSet(false) {}
inline NullableValue& operator=(NullableValue&& other) {
if (&other != this) {
// Careful about throwing destructors/constructors here.
if (isSet) {
isSet = false;
dtor(value);
}
if (other.isSet) {
ctor(value, kj::mv(other.value));
isSet = true;
}
}
return *this;
}
inline NullableValue& operator=(NullableValue& other) {
if (&other != this) {
// Careful about throwing destructors/constructors here.
if (isSet) {
isSet = false;
dtor(value);
}
if (other.isSet) {
ctor(value, other.value);
isSet = true;
}
}
return *this;
}
inline NullableValue& operator=(const NullableValue& other) {
if (&other != this) {
// Careful about throwing destructors/constructors here.
if (isSet) {
isSet = false;
dtor(value);
}
if (other.isSet) {
ctor(value, other.value);
isSet = true;
}
}
return *this;
}
inline NullableValue& operator=(T&& other) { emplace(kj::mv(other)); return *this; }
inline NullableValue& operator=(T& other) { emplace(other); return *this; }
inline NullableValue& operator=(const T& other) { emplace(other); return *this; }
template <typename U>
inline NullableValue& operator=(NullableValue<U>&& other) {
if (other.isSet) {
emplace(kj::mv(other.value));
} else {
*this = nullptr;
}
return *this;
}
template <typename U>
inline NullableValue& operator=(const NullableValue<U>& other) {
if (other.isSet) {
emplace(other.value);
} else {
*this = nullptr;
}
return *this;
}
template <typename U>
inline NullableValue& operator=(const NullableValue<U&>& other) {
if (other.isSet) {
emplace(other.value);
} else {
*this = nullptr;
}
return *this;
}
inline NullableValue& operator=(decltype(nullptr)) {
if (isSet) {
isSet = false;
dtor(value);
}
return *this;
}
inline bool operator==(decltype(nullptr)) const { return !isSet; }
inline bool operator!=(decltype(nullptr)) const { return isSet; }
NullableValue(const T* t) = delete;
NullableValue& operator=(const T* other) = delete;
// We used to permit assigning a Maybe<T> directly from a T*, and the assignment would check for
// nullness. This turned out never to be useful, and sometimes to be dangerous.
private:
bool isSet;
#if _MSC_VER && !defined(__clang__)
#pragma warning(push)
#pragma warning(disable: 4624)
// Warns that the anonymous union has a deleted destructor when T is non-trivial. This warning
// seems broken.
#endif
union {
T value;
};
#if _MSC_VER && !defined(__clang__)
#pragma warning(pop)
#endif
friend class kj::Maybe<T>;
template <typename U>
friend NullableValue<U>&& readMaybe(Maybe<U>&& maybe);
};
template <typename T>
inline NullableValue<T>&& readMaybe(Maybe<T>&& maybe) { return kj::mv(maybe.ptr); }
template <typename T>
inline T* readMaybe(Maybe<T>& maybe) { return maybe.ptr; }
template <typename T>
inline const T* readMaybe(const Maybe<T>& maybe) { return maybe.ptr; }
template <typename T>
inline T* readMaybe(Maybe<T&>&& maybe) { return maybe.ptr; }
template <typename T>
inline T* readMaybe(const Maybe<T&>& maybe) { return maybe.ptr; }
template <typename T>
inline T* readMaybe(T* ptr) { return ptr; }
// Allow KJ_IF_MAYBE to work on regular pointers.
} // namespace _ (private)
#define KJ_IF_MAYBE(name, exp) if (auto name = ::kj::_::readMaybe(exp))
template <typename T>
class Maybe {
// A T, or nullptr.
// IF YOU CHANGE THIS CLASS: Note that there is a specialization of it in memory.h.
public:
Maybe(): ptr(nullptr) {}
Maybe(T&& t): ptr(kj::mv(t)) {}
Maybe(T& t): ptr(t) {}
Maybe(const T& t): ptr(t) {}
Maybe(Maybe&& other): ptr(kj::mv(other.ptr)) { other = nullptr; }
Maybe(const Maybe& other): ptr(other.ptr) {}
Maybe(Maybe& other): ptr(other.ptr) {}
template <typename U>
Maybe(Maybe<U>&& other) {
KJ_IF_MAYBE(val, kj::mv(other)) {
ptr.emplace(kj::mv(*val));
other = nullptr;
}
}
template <typename U>
Maybe(Maybe<U&>&& other) {
KJ_IF_MAYBE(val, other) {
ptr.emplace(*val);
other = nullptr;
}
}
template <typename U>
Maybe(const Maybe<U>& other) {
KJ_IF_MAYBE(val, other) {
ptr.emplace(*val);
}
}
Maybe(decltype(nullptr)): ptr(nullptr) {}
template <typename... Params>
inline T& emplace(Params&&... params) {
// Replace this Maybe's content with a new value constructed by passing the given parameters to
// T's constructor. This can be used to initialize a Maybe without copying or even moving a T.
// Returns a reference to the newly-constructed value.
return ptr.emplace(kj::fwd<Params>(params)...);
}
inline Maybe& operator=(T&& other) { ptr = kj::mv(other); return *this; }
inline Maybe& operator=(T& other) { ptr = other; return *this; }
inline Maybe& operator=(const T& other) { ptr = other; return *this; }
inline Maybe& operator=(Maybe&& other) { ptr = kj::mv(other.ptr); other = nullptr; return *this; }
inline Maybe& operator=(Maybe& other) { ptr = other.ptr; return *this; }
inline Maybe& operator=(const Maybe& other) { ptr = other.ptr; return *this; }
template <typename U>
Maybe& operator=(Maybe<U>&& other) {
KJ_IF_MAYBE(val, kj::mv(other)) {
ptr.emplace(kj::mv(*val));
other = nullptr;
} else {
ptr = nullptr;
}
return *this;
}
template <typename U>
Maybe& operator=(const Maybe<U>& other) {
KJ_IF_MAYBE(val, other) {
ptr.emplace(*val);
} else {
ptr = nullptr;
}
return *this;
}
inline Maybe& operator=(decltype(nullptr)) { ptr = nullptr; return *this; }
inline bool operator==(decltype(nullptr)) const { return ptr == nullptr; }
inline bool operator!=(decltype(nullptr)) const { return ptr != nullptr; }
inline bool operator==(const Maybe<T>& other) const {
if (ptr == nullptr) {
return other == nullptr;
} else {
return other.ptr != nullptr && *ptr == *other.ptr;
}
}
inline bool operator!=(const Maybe<T>& other) const { return !(*this == other); }
Maybe(const T* t) = delete;
Maybe& operator=(const T* other) = delete;
// We used to permit assigning a Maybe<T> directly from a T*, and the assignment would check for
// nullness. This turned out never to be useful, and sometimes to be dangerous.
T& orDefault(T& defaultValue) & {
if (ptr == nullptr) {
return defaultValue;
} else {
return *ptr;
}
}
const T& orDefault(const T& defaultValue) const & {
if (ptr == nullptr) {
return defaultValue;
} else {
return *ptr;
}
}
T&& orDefault(T&& defaultValue) && {
if (ptr == nullptr) {
return kj::mv(defaultValue);
} else {
return kj::mv(*ptr);
}
}
const T&& orDefault(const T&& defaultValue) const && {
if (ptr == nullptr) {
return kj::mv(defaultValue);
} else {
return kj::mv(*ptr);
}
}
template <typename F,
typename Result = decltype(instance<bool>() ? instance<T&>() : instance<F>()())>
Result orDefault(F&& lazyDefaultValue) & {
if (ptr == nullptr) {
return lazyDefaultValue();
} else {
return *ptr;
}
}
template <typename F,
typename Result = decltype(instance<bool>() ? instance<const T&>() : instance<F>()())>
Result orDefault(F&& lazyDefaultValue) const & {
if (ptr == nullptr) {
return lazyDefaultValue();
} else {
return *ptr;
}
}
template <typename F,
typename Result = decltype(instance<bool>() ? instance<T&&>() : instance<F>()())>
Result orDefault(F&& lazyDefaultValue) && {
if (ptr == nullptr) {
return lazyDefaultValue();
} else {
return kj::mv(*ptr);
}
}
template <typename F,
typename Result = decltype(instance<bool>() ? instance<const T&&>() : instance<F>()())>
Result orDefault(F&& lazyDefaultValue) const && {
if (ptr == nullptr) {
return lazyDefaultValue();
} else {
return kj::mv(*ptr);
}
}
template <typename Func>
auto map(Func&& f) & -> Maybe<decltype(f(instance<T&>()))> {
if (ptr == nullptr) {
return nullptr;
} else {
return f(*ptr);
}
}
template <typename Func>
auto map(Func&& f) const & -> Maybe<decltype(f(instance<const T&>()))> {
if (ptr == nullptr) {
return nullptr;
} else {
return f(*ptr);
}
}
template <typename Func>
auto map(Func&& f) && -> Maybe<decltype(f(instance<T&&>()))> {
if (ptr == nullptr) {
return nullptr;
} else {
return f(kj::mv(*ptr));
}
}
template <typename Func>
auto map(Func&& f) const && -> Maybe<decltype(f(instance<const T&&>()))> {
if (ptr == nullptr) {
return nullptr;
} else {
return f(kj::mv(*ptr));
}
}
private:
_::NullableValue<T> ptr;
template <typename U>
friend class Maybe;
template <typename U>
friend _::NullableValue<U>&& _::readMaybe(Maybe<U>&& maybe);
template <typename U>
friend U* _::readMaybe(Maybe<U>& maybe);
template <typename U>
friend const U* _::readMaybe(const Maybe<U>& maybe);
};
template <typename T>
class Maybe<T&> {
public:
constexpr Maybe(): ptr(nullptr) {}
constexpr Maybe(T& t): ptr(&t) {}
constexpr Maybe(T* t): ptr(t) {}
inline constexpr Maybe(PropagateConst<T, Maybe>& other): ptr(other.ptr) {}
// Allow const copy only if `T` itself is const. Otherwise allow only non-const copy, to
// protect transitive constness. Clang is happy for this constructor to be declared `= default`
// since, after evaluation of `PropagateConst`, it does end up being a default-able constructor.
// But, GCC and MSVC both complain about that, claiming this constructor cannot be declared
// default. I don't know who is correct, but whatever, we'll write out an implementation, fine.
//
// Note that we can't solve this by inheriting DisallowConstCopyIfNotConst<T> because we want
// to override the move constructor, and if we override the move constructor then we must define
// the copy constructor here.
inline constexpr Maybe(Maybe&& other): ptr(other.ptr) { other.ptr = nullptr; }
template <typename U>
inline constexpr Maybe(Maybe<U&>& other): ptr(other.ptr) {}
template <typename U>
inline constexpr Maybe(const Maybe<U&>& other): ptr(const_cast<const U*>(other.ptr)) {}
template <typename U>
inline constexpr Maybe(Maybe<U&>&& other): ptr(other.ptr) { other.ptr = nullptr; }
template <typename U>
inline constexpr Maybe(const Maybe<U&>&& other) = delete;
template <typename U, typename = EnableIf<canConvert<U*, T*>()>>
constexpr Maybe(Maybe<U>& other): ptr(other.ptr.operator U*()) {}
template <typename U, typename = EnableIf<canConvert<const U*, T*>()>>
constexpr Maybe(const Maybe<U>& other): ptr(other.ptr.operator const U*()) {}
inline constexpr Maybe(decltype(nullptr)): ptr(nullptr) {}
inline Maybe& operator=(T& other) { ptr = &other; return *this; }
inline Maybe& operator=(T* other) { ptr = other; return *this; }
inline Maybe& operator=(PropagateConst<T, Maybe>& other) { ptr = other.ptr; return *this; }
inline Maybe& operator=(Maybe&& other) { ptr = other.ptr; other.ptr = nullptr; return *this; }
template <typename U>
inline Maybe& operator=(Maybe<U&>& other) { ptr = other.ptr; return *this; }
template <typename U>
inline Maybe& operator=(const Maybe<const U&>& other) { ptr = other.ptr; return *this; }
template <typename U>
inline Maybe& operator=(Maybe<U&>&& other) { ptr = other.ptr; other.ptr = nullptr; return *this; }
template <typename U>
inline Maybe& operator=(const Maybe<U&>&& other) = delete;
inline bool operator==(decltype(nullptr)) const { return ptr == nullptr; }
inline bool operator!=(decltype(nullptr)) const { return ptr != nullptr; }
T& orDefault(T& defaultValue) {
if (ptr == nullptr) {
return defaultValue;
} else {
return *ptr;
}
}
const T& orDefault(const T& defaultValue) const {
if (ptr == nullptr) {
return defaultValue;
} else {
return *ptr;
}
}
template <typename Func>
auto map(Func&& f) -> Maybe<decltype(f(instance<T&>()))> {
if (ptr == nullptr) {
return nullptr;
} else {
return f(*ptr);
}
}
template <typename Func>
auto map(Func&& f) const -> Maybe<decltype(f(instance<const T&>()))> {
if (ptr == nullptr) {
return nullptr;
} else {
const T& ref = *ptr;
return f(ref);
}
}
private:
T* ptr;
template <typename U>
friend class Maybe;
template <typename U>
friend U* _::readMaybe(Maybe<U&>&& maybe);
template <typename U>
friend U* _::readMaybe(const Maybe<U&>& maybe);
};
// =======================================================================================
// ArrayPtr
//
// So common that we put it in common.h rather than array.h.
template <typename T>
class Array;
template <typename T>
class ArrayPtr: public DisallowConstCopyIfNotConst<T> {
// A pointer to an array. Includes a size. Like any pointer, it doesn't own the target data,
// and passing by value only copies the pointer, not the target.
public:
inline constexpr ArrayPtr(): ptr(nullptr), size_(0) {}
inline constexpr ArrayPtr(decltype(nullptr)): ptr(nullptr), size_(0) {}
inline constexpr ArrayPtr(T* ptr KJ_LIFETIMEBOUND, size_t size): ptr(ptr), size_(size) {}
inline constexpr ArrayPtr(T* begin KJ_LIFETIMEBOUND, T* end KJ_LIFETIMEBOUND)
: ptr(begin), size_(end - begin) {}
ArrayPtr<T>& operator=(Array<T>&&) = delete;
ArrayPtr<T>& operator=(decltype(nullptr)) {
ptr = nullptr;
size_ = 0;
return *this;
}
#if __GNUC__ && !__clang__ && __GNUC__ >= 9
// GCC 9 added a warning when we take an initializer_list as a constructor parameter and save a
// pointer to its content in a class member. GCC apparently imagines we're going to do something
// dumb like this:
// ArrayPtr<const int> ptr = { 1, 2, 3 };
// foo(ptr[1]); // undefined behavior!
// Any KJ programmer should be able to recognize that this is UB, because an ArrayPtr does not own
// its content. That's not what this constructor is for, tohugh. This constructor is meant to allow
// code like this:
// int foo(ArrayPtr<const int> p);
// // ... later ...
// foo({1, 2, 3});
// In this case, the initializer_list's backing array, like any temporary, lives until the end of
// the statement `foo({1, 2, 3});`. Therefore, it lives at least until the call to foo() has
// returned, which is exactly what we care about. This usage is fine! GCC is wrong to warn.
//
// Amusingly, Clang's implementation has a similar type that they call ArrayRef which apparently
// triggers this same GCC warning. My guess is that Clang will not introduce a similar warning
// given that it triggers on their own, legitimate code.
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Winit-list-lifetime"
#endif
inline KJ_CONSTEXPR() ArrayPtr(
::std::initializer_list<RemoveConstOrDisable<T>> init KJ_LIFETIMEBOUND)
: ptr(init.begin()), size_(init.size()) {}
#if __GNUC__ && !__clang__ && __GNUC__ >= 9
#pragma GCC diagnostic pop
#endif
template <size_t size>
inline constexpr ArrayPtr(KJ_LIFETIMEBOUND T (&native)[size]): ptr(native), size_(size) {
// Construct an ArrayPtr from a native C-style array.
//
// We disable this constructor for const char arrays because otherwise you would be able to
// implicitly convert a character literal to ArrayPtr<const char>, which sounds really great,
// except that the NUL terminator would be included, which probably isn't what you intended.
//
// TODO(someday): Maybe we should support character literals but explicitly chop off the NUL
// terminator. This could do the wrong thing if someone tries to construct an
// ArrayPtr<const char> from a non-NUL-terminated char array, but evidence suggests that all
// real use cases are in fact intending to remove the NUL terminator. It's convenient to be
// able to specify ArrayPtr<const char> as a parameter type and be able to accept strings
// as input in addition to arrays. Currently, you'll need overloading to support string
// literals in this case, but if you overload StringPtr, then you'll find that several
// conversions (e.g. from String and from a literal char array) become ambiguous! You end up
// having to overload for literal char arrays specifically which is cumbersome.
static_assert(!isSameType<T, const char>(),
"Can't implicitly convert literal char array to ArrayPtr because we don't know if "
"you meant to include the NUL terminator. We may change this in the future to "
"automatically drop the NUL terminator. For now, try explicitly converting to StringPtr, "
"which can in turn implicitly convert to ArrayPtr<const char>.");
static_assert(!isSameType<T, const char16_t>(), "see above");
static_assert(!isSameType<T, const char32_t>(), "see above");
}
inline operator ArrayPtr<const T>() const {
return ArrayPtr<const T>(ptr, size_);
}
inline ArrayPtr<const T> asConst() const {
return ArrayPtr<const T>(ptr, size_);
}
inline constexpr size_t size() const { return size_; }
inline const T& operator[](size_t index) const {
KJ_IREQUIRE(index < size_, "Out-of-bounds ArrayPtr access.");
return ptr[index];
}
inline T& operator[](size_t index) {
KJ_IREQUIRE(index < size_, "Out-of-bounds ArrayPtr access.");
return ptr[index];
}
inline T* begin() { return ptr; }
inline T* end() { return ptr + size_; }
inline T& front() { return *ptr; }
inline T& back() { return *(ptr + size_ - 1); }
inline constexpr const T* begin() const { return ptr; }
inline constexpr const T* end() const { return ptr + size_; }
inline const T& front() const { return *ptr; }
inline const T& back() const { return *(ptr + size_ - 1); }
inline ArrayPtr<const T> slice(size_t start, size_t end) const {
KJ_IREQUIRE(start <= end && end <= size_, "Out-of-bounds ArrayPtr::slice().");
return ArrayPtr<const T>(ptr + start, end - start);
}
inline ArrayPtr slice(size_t start, size_t end) {
KJ_IREQUIRE(start <= end && end <= size_, "Out-of-bounds ArrayPtr::slice().");
return ArrayPtr(ptr + start, end - start);
}
inline ArrayPtr<PropagateConst<T, byte>> asBytes() const {
// Reinterpret the array as a byte array. This is explicitly legal under C++ aliasing
// rules.
return { reinterpret_cast<PropagateConst<T, byte>*>(ptr), size_ * sizeof(T) };
}
inline ArrayPtr<PropagateConst<T, char>> asChars() const {
// Reinterpret the array as a char array. This is explicitly legal under C++ aliasing
// rules.
return { reinterpret_cast<PropagateConst<T, char>*>(ptr), size_ * sizeof(T) };
}
inline bool operator==(decltype(nullptr)) const { return size_ == 0; }
inline bool operator!=(decltype(nullptr)) const { return size_ != 0; }
inline bool operator==(const ArrayPtr& other) const {
if (size_ != other.size_) return false;
for (size_t i = 0; i < size_; i++) {
if (ptr[i] != other[i]) return false;
}
return true;
}
inline bool operator!=(const ArrayPtr& other) const { return !(*this == other); }
template <typename U>
inline bool operator==(const ArrayPtr<U>& other) const {
if (size_ != other.size()) return false;
for (size_t i = 0; i < size_; i++) {
if (ptr[i] != other[i]) return false;
}
return true;
}
template <typename U>
inline bool operator!=(const ArrayPtr<U>& other) const { return !(*this == other); }
template <typename... Attachments>
Array<T> attach(Attachments&&... attachments) const KJ_WARN_UNUSED_RESULT;
// Like Array<T>::attach(), but also promotes an ArrayPtr to an Array. Generally the attachment
// should be an object that actually owns the array that the ArrayPtr is pointing at.
//
// You must include kj/array.h to call this.
private:
T* ptr;
size_t size_;
};
template <typename T>
inline constexpr ArrayPtr<T> arrayPtr(T* ptr KJ_LIFETIMEBOUND, size_t size) {
// Use this function to construct ArrayPtrs without writing out the type name.
return ArrayPtr<T>(ptr, size);
}
template <typename T>
inline constexpr ArrayPtr<T> arrayPtr(T* begin KJ_LIFETIMEBOUND, T* end KJ_LIFETIMEBOUND) {
// Use this function to construct ArrayPtrs without writing out the type name.
return ArrayPtr<T>(begin, end);
}
// =======================================================================================
// Casts
template <typename To, typename From>
To implicitCast(From&& from) {
// `implicitCast<T>(value)` casts `value` to type `T` only if the conversion is implicit. Useful
// for e.g. resolving ambiguous overloads without sacrificing type-safety.
return kj::fwd<From>(from);
}
template <typename To, typename From>
Maybe<To&> dynamicDowncastIfAvailable(From& from) {
// If RTTI is disabled, always returns nullptr. Otherwise, works like dynamic_cast. Useful
// in situations where dynamic_cast could allow an optimization, but isn't strictly necessary
// for correctness. It is highly recommended that you try to arrange all your dynamic_casts
// this way, as a dynamic_cast that is necessary for correctness implies a flaw in the interface
// design.
// Force a compile error if To is not a subtype of From. Cross-casting is rare; if it is needed
// we should have a separate cast function like dynamicCrosscastIfAvailable().
if (false) {
kj::implicitCast<From*>(kj::implicitCast<To*>(nullptr));
}
#if KJ_NO_RTTI
return nullptr;
#else
return dynamic_cast<To*>(&from);
#endif
}
template <typename To, typename From>
To& downcast(From& from) {
// Down-cast a value to a sub-type, asserting that the cast is valid. In opt mode this is a
// static_cast, but in debug mode (when RTTI is enabled) a dynamic_cast will be used to verify
// that the value really has the requested type.
// Force a compile error if To is not a subtype of From.
if (false) {
kj::implicitCast<From*>(kj::implicitCast<To*>(nullptr));
}
#if !KJ_NO_RTTI
KJ_IREQUIRE(dynamic_cast<To*>(&from) != nullptr, "Value cannot be downcast() to requested type.");
#endif
return static_cast<To&>(from);
}
// =======================================================================================
// Defer
namespace _ { // private
template <typename Func>
class Deferred {
public:
inline Deferred(Func&& func): func(kj::fwd<Func>(func)), canceled(false) {}
inline ~Deferred() noexcept(false) { if (!canceled) func(); }
KJ_DISALLOW_COPY(Deferred);
// This move constructor is usually optimized away by the compiler.
inline Deferred(Deferred&& other): func(kj::fwd<Func>(other.func)), canceled(false) {
other.canceled = true;
}
private:
Func func;
bool canceled;
};
} // namespace _ (private)
template <typename Func>
_::Deferred<Func> defer(Func&& func) {
// Returns an object which will invoke the given functor in its destructor. The object is not
// copyable but is movable with the semantics you'd expect. Since the return type is private,
// you need to assign to an `auto` variable.
//
// The KJ_DEFER macro provides slightly more convenient syntax for the common case where you
// want some code to run at current scope exit.
return _::Deferred<Func>(kj::fwd<Func>(func));
}
#define KJ_DEFER(code) auto KJ_UNIQUE_NAME(_kjDefer) = ::kj::defer([&](){code;})
// Run the given code when the function exits, whether by return or exception.
} // namespace kj
KJ_END_HEADER
| 37.426158 | 108 | 0.686474 | [
"object",
"transform"
] |
2cb135d7706f7dbbfbb9a126b84486b37b761d7b | 574 | h | C | t1_math/trigonometry/polar.h | depthBuffer/T1- | 9fdebf931e8dd5edaa7613cc0dd435f8f00106e4 | [
"Apache-2.0"
] | null | null | null | t1_math/trigonometry/polar.h | depthBuffer/T1- | 9fdebf931e8dd5edaa7613cc0dd435f8f00106e4 | [
"Apache-2.0"
] | null | null | null | t1_math/trigonometry/polar.h | depthBuffer/T1- | 9fdebf931e8dd5edaa7613cc0dd435f8f00106e4 | [
"Apache-2.0"
] | null | null | null | #ifndef MATH_TRIGONOMETRY_POLAR_H
#define MATH_TRIGONOMETRY_POLAR_H
#include "../linear_algebra/vector.h"
namespace math
{
/*
Polar coordinates w/ relevant conversion for
converting to and from cartesian coordinates.
*/
struct polar
{
float r; // distance coordinate from origin.
float theta; // counter-clockwise rotation from x-axis.
polar(float r, float theta);
// convert from cartesian.
polar(vec2 cartesian);
// convert to cartesian.
vec2 ToCartesian();
};
}
#endif | 21.259259 | 64 | 0.635889 | [
"vector"
] |
2cb197d7e69007a35fca047ccd61a02e97d1175a | 26,471 | c | C | base/ntsetup/cobra/utils/main/poolmem.c | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | base/ntsetup/cobra/utils/main/poolmem.c | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | base/ntsetup/cobra/utils/main/poolmem.c | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /*++
Copyright (c) 1996 Microsoft Corporation
Module Name:
poolmem.c
Abstract:
poolmem provides a managed allocation scheme in which large blocks of memory are
allocated (pools) and then divided up by request into low overhead memory chunks
upon request. poolmem provides for easy creation/clean-up of memory, freeing the
developer for more important tasks.
Author:
Marc R. Whitten (marcw) 13-Feb-1997
Revision History:
marcw 2-Sep-1999 Moved over from Win9xUpg project.
jimschm 28-Sep-1998 Debug message fixes
--*/
#include "pch.h"
#ifdef UNICODE
#error UNICODE not allowed
#endif
//
// Includes
//
#include "utilsp.h"
#define DBG_POOLMEM "Poolmem"
//
// Strings
//
// None
//
// Constants
//
//
// Tree Memory Allocation structure.
//
#ifdef DEBUG
#define VALIDDOGTAG 0x021371
#define FREEDOGTAG 0x031073
#endif
#define MAX_POOL_NAME 32
//
// Macros
//
// None
//
// Types
//
typedef struct _PMBLOCK PMBLOCK, *PPMBLOCK;
struct _PMBLOCK {
UINT_PTR Index; // Tracks into RawMemory.
SIZE_T Size; // the size in bytes of RawMemory.
PPMBLOCK NextBlock; // A pointer to the next block in the pool chain.
PPMBLOCK PrevBlock; // A pointer to the prev block in the pool chain.
DWORD UseCount; // The number of allocations currently referring
// to this block.
PBYTE RawMemory; // The actual bytes of allocable memory in this block.
};
typedef struct _ALLOCATION ALLOCATION, * PALLOCATION;
struct _ALLOCATION {
#ifdef DEBUG
DWORD DogTag; // A signature to ensure validity.
SIZE_T Size;
PALLOCATION Next; // The next allocation in the list.
PALLOCATION Prev; // The previous allocation in the list.
#endif
PPMBLOCK ParentBlock; // A reference to the block from which this allocation
// was created.
};
typedef enum {
FREE_NOT_CALLED,
FREE_CALLED,
WHO_CARES
} FREESTATE;
typedef struct _POOLHEADER {
PPMBLOCK PoolHead; // The active memory block in this pool.
SIZE_T MinimumBlockSize; // minimum size to allocate when a new block is needed.
#ifdef DEBUG
CHAR Name[MAX_POOL_NAME];
SIZE_T TotalAllocationRequestBytes;
SIZE_T CurrentAllocationSize;
SIZE_T MaxAllocationSize;
SIZE_T CurrentlyAllocatedMemory;
SIZE_T MaximumAllocatedMemory;
UINT NumAllocationRequests;
UINT NumFreeRequests;
UINT NumBlockFrees;
UINT NumBlockClears;
UINT NumBlockAllocations;
PALLOCATION AllocationList; // A linked list of all of the allocations active in the
// pool.
FREESTATE FreeCalled; // A state variable indicating that PoolMemReleaseMemory()
// has been called at least once on this pool.
#endif
} POOLHEADER, *PPOOLHEADER;
//
// Globals
//
#ifdef DEBUG
DWORD g_PmDisplayed;
DWORD g_PmNotDisplayed;
UINT g_PoolCurrPools = 0;
SIZE_T g_PoolCurrTotalAlloc = 0;
SIZE_T g_PoolCurrActiveAlloc = 0;
SIZE_T g_PoolCurrUsedAlloc = 0;
UINT g_PoolMaxPools = 0;
SIZE_T g_PoolMaxTotalAlloc = 0;
SIZE_T g_PoolMaxActiveAlloc = 0;
SIZE_T g_PoolMaxUsedAlloc = 0;
#endif
//
// Macro expansion list
//
// None
//
// Private function prototypes
//
// None
//
// Macro expansion definition
//
// None
//
// Code
//
BOOL
pPmAddMemory (
IN PMHANDLE Handle,
IN SIZE_T Size
)
/*++
Routine Description:
pPmAddMemory is the function responsible for actually growing the size of
the pool by adding a new block of memory. This function is used by
PmCreatePool and PmGetMemory.
when called, this function attempts to allocate at least poolHeader ->
MinimumBlockSize bytes of memory. If the requested size is actually larger
than the minimum, the requested size is allocated instead. This is consistent
with PoolMem's main purpose: An efficient allocator for larger numbers of small
objects. If PoolMem is being used to allocate very large objects, the benefits
are lost and poolmem becomes a very inefficient allocator.
Arguments:
Handle - A Handle to a Pool of Memory.
Size - Size to allocate.
Return Value:
returns TRUE if memory was successfully added, FALSE otherwise.
--*/
{
PBYTE allocedMemory;
PPMBLOCK newBlock;
PPOOLHEADER poolHeader = (PPOOLHEADER) Handle;
SIZE_T sizeNeeded;
MYASSERT(poolHeader != NULL);
//
// Determine size needed and attempt to allocate memory.
//
if (Size + sizeof(PMBLOCK) > poolHeader->MinimumBlockSize) {
sizeNeeded = Size + sizeof(PMBLOCK);
}
else {
sizeNeeded = poolHeader->MinimumBlockSize;
}
MYASSERT (g_TrackFile);
allocedMemory = MemAlloc(g_hHeap,0,sizeNeeded);
if (allocedMemory) {
#ifdef DEBUG
g_PoolCurrTotalAlloc += sizeNeeded;
if (g_PoolMaxTotalAlloc < g_PoolCurrTotalAlloc) {
g_PoolMaxTotalAlloc = g_PoolCurrTotalAlloc;
}
g_PoolCurrActiveAlloc += (sizeNeeded - sizeof(PMBLOCK));
if (g_PoolMaxActiveAlloc < g_PoolCurrActiveAlloc) {
g_PoolMaxActiveAlloc = g_PoolCurrActiveAlloc;
}
#endif
//
// Use the beginning of the alloc'ed block as the poolblock structure.
//
newBlock = (PPMBLOCK) allocedMemory;
newBlock->Size = sizeNeeded - sizeof(PMBLOCK);
newBlock->RawMemory = allocedMemory + sizeof(PMBLOCK);
newBlock->Index = 0;
newBlock->UseCount = 0;
//
// Link the block into the list.
//
if (poolHeader->PoolHead) {
poolHeader->PoolHead->PrevBlock = newBlock;
}
newBlock->NextBlock = poolHeader->PoolHead;
newBlock->PrevBlock = NULL;
poolHeader->PoolHead = newBlock;
#ifdef DEBUG
//
// Keep track of pool statistics.
//
poolHeader->CurrentlyAllocatedMemory += sizeNeeded;
poolHeader->MaximumAllocatedMemory =
max(poolHeader->MaximumAllocatedMemory,poolHeader->CurrentlyAllocatedMemory);
poolHeader->NumBlockAllocations++;
#endif
}
//
// Assuming allocedMemory is non-NULL, we have succeeded.
//
return allocedMemory != NULL;
}
PMHANDLE
RealPmCreatePoolEx (
IN DWORD BlockSize OPTIONAL
)
/*++
Routine Description:
Initializes a new memory pool and returns a handle to it.
Arguments:
None.
Return Value:
If the function completes succssessfully, it returns a valid PMHANDLE, otherwise,
it returns NULL.
--*/
{
BOOL ableToAddMemory;
PPOOLHEADER header = NULL;
EnterCriticalSection (&g_PmCs);
__try {
//
// Allocate the header of this pool.
//
header = MemAlloc(g_hHeap,0,sizeof(POOLHEADER));
#ifdef DEBUG
g_PoolCurrTotalAlloc += sizeof(POOLHEADER);
if (g_PoolMaxTotalAlloc < g_PoolCurrTotalAlloc) {
g_PoolMaxTotalAlloc = g_PoolCurrTotalAlloc;
}
#endif
//
// Allocation was successful. Now, initialize the pool.
//
header->MinimumBlockSize = BlockSize?BlockSize:POOLMEMORYBLOCKSIZE;
header->PoolHead = NULL;
#ifdef DEBUG
//
// Statistics for the debug version.
//
header->TotalAllocationRequestBytes = 0;
header->CurrentAllocationSize = 0;
header->MaxAllocationSize = 0;
header->CurrentlyAllocatedMemory = 0;
header->MaximumAllocatedMemory = 0;
header->NumAllocationRequests = 0;
header->NumFreeRequests = 0;
header->NumBlockFrees = 0;
header->NumBlockClears = 0;
header->NumBlockAllocations = 0;
header->Name[0] = 0;
#endif
//
// Actually add some memory to the pool.
//
ableToAddMemory = pPmAddMemory(header,0);
if (!ableToAddMemory) {
//
// Unable to add memory to the pool.
//
MemFree(g_hHeap,0,header);
#ifdef DEBUG
g_PoolCurrTotalAlloc -= sizeof(POOLHEADER);
#endif
header = NULL;
DEBUGMSG((DBG_ERROR,"PoolMem: Unable to initialize memory pool."));
}
#ifdef DEBUG
//
// These are 'cookie' variables that hold tracking information when dogtag checking
// is enabled.
//
g_PmNotDisplayed = 12;
g_PmDisplayed = 24;
if (ableToAddMemory) {
header->AllocationList = NULL; //lint !e613
header->FreeCalled = FREE_NOT_CALLED; //lint !e613
}
#endif
} __finally {
LeaveCriticalSection (&g_PmCs);
}
#ifdef DEBUG
if (header) {
g_PoolCurrPools ++;
if (g_PoolMaxPools < g_PoolCurrPools) {
g_PoolMaxPools = g_PoolCurrPools;
}
}
#endif
return (PMHANDLE) header;
}
VOID
pDeregisterPoolAllocations (
PPOOLHEADER PoolHeader
)
{
#ifdef DEBUG
PALLOCATION p,cur;
if (PoolHeader->FreeCalled == WHO_CARES) {
return;
}
p = PoolHeader->AllocationList;
while (p) {
cur = p;
p = p->Next;
g_PoolCurrUsedAlloc -= cur->Size;
DebugUnregisterAllocation(POOLMEM_POINTER,cur);
}
PoolHeader->AllocationList = NULL;
#endif
}
VOID
PmEmptyPool (
IN PMHANDLE Handle
)
/*++
Routine Description:
PmEmptyPool resets the index pointer of the index block back
to zero, so the next allocation will come from the already allocated
active block.
Calling this function invalidates all pointers previously allocated from
the active block.
Arguments:
Handle - Specifies the pool to reset
Return Value:
None.
--*/
{
PPOOLHEADER poolHeader = (PPOOLHEADER) Handle;
if (!Handle) {
return;
}
EnterCriticalSection (&g_PmCs);
__try {
poolHeader->PoolHead->UseCount = 0;
poolHeader->PoolHead->Index = 0;
#ifdef DEBUG
poolHeader->NumBlockClears++;
#endif
#ifdef DEBUG
pDeregisterPoolAllocations(poolHeader);
#endif
} __finally {
LeaveCriticalSection (&g_PmCs);
}
}
VOID
PmSetMinimumGrowthSize (
IN PMHANDLE Handle,
IN SIZE_T Size
)
/*++
Routine Description:
Sets the minimum growth size for a memory pool. This value is used when new blocks
are actually added to the pool. The PoolMem allocator will attempt to allocate at
least this minimum size.
Arguments:
Handle - A valid PMHANDLE.
Size - The minimum size in bytes to grow the pool by on each allocation.
Return Value:
None.
--*/
{
PPOOLHEADER poolHeader = (PPOOLHEADER) Handle;
MYASSERT(Handle != NULL);
poolHeader->MinimumBlockSize = max(Size,0);
}
VOID
PmDestroyPool (
PMHANDLE Handle
)
/*++
Routine Description:
PmDestroyPool completely cleans up the memory pool identified by Handle. It
simply walks the list of memory blocks associated with the memory pool, freeing each of them.
Arguments:
Handle - A valid PMHANDLE.
Return Value:
None.
--*/
{
PPMBLOCK nextBlock;
PPMBLOCK blockToFree;
PPOOLHEADER poolHeader;
if (!Handle) {
return;
}
poolHeader = (PPOOLHEADER) Handle;
#ifdef DEBUG
if (poolHeader->NumAllocationRequests) {
CHAR FloatWorkaround[32];
_gcvt (
((DOUBLE) (poolHeader->TotalAllocationRequestBytes)) / poolHeader->NumAllocationRequests,
8,
FloatWorkaround
);
//
// Spew the statistics of this pool to the debug log.
//
DEBUGMSG ((
DBG_POOLMEM,
"Pool Statistics for %s\n"
"\n"
"Requested Size in Bytes\n"
" Average: %s\n"
" Maximum: %u\n"
"\n"
"Pool Size in Bytes\n"
" Current: %u\n"
" Maximum: %u\n"
"\n"
"Allocation Requests\n"
" Caller Requests: %u\n"
" Block Allocations: %u\n"
"\n"
"Free Requests\n"
" Caller Requests: %u\n"
" Block Frees: %u\n"
" Block Clears: %u",
poolHeader->Name[0] ? poolHeader->Name : "[Unnamed Pool]",
FloatWorkaround,
poolHeader->MaxAllocationSize,
poolHeader->CurrentlyAllocatedMemory,
poolHeader->MaximumAllocatedMemory,
poolHeader->NumAllocationRequests,
poolHeader->NumBlockAllocations,
poolHeader->NumFreeRequests,
poolHeader->NumBlockFrees,
poolHeader->NumBlockClears
));
} else if (poolHeader->Name[0]) {
DEBUGMSG ((
DBG_POOLMEM,
"Pool %s was allocated but was never used",
poolHeader->Name
));
}
#endif
//
// Walk the list, freeing as we go.
//
blockToFree = poolHeader-> PoolHead;
while (blockToFree != NULL) {
nextBlock = blockToFree->NextBlock;
#ifdef DEBUG
g_PoolCurrTotalAlloc -= (blockToFree->Size + sizeof(PMBLOCK));
g_PoolCurrActiveAlloc -= blockToFree->Size;
#endif
MemFree(g_hHeap,0,blockToFree);
blockToFree = nextBlock;
}
//
// Also, deallocate the poolheader itself.
//
#ifdef DEBUG
g_PoolCurrTotalAlloc -= sizeof (POOLHEADER);
g_PoolCurrPools --;
#endif
MemFree(g_hHeap,0,poolHeader);
}
PVOID
RealPmGetMemory (
IN PMHANDLE Handle,
IN SIZE_T Size,
IN DWORD AlignSize
)
/*++
Routine Description:
RealPmGetMemory is the worker routine that processes all requests to retrieve memory
from a pool. Other calls eventually decay into a call to this common routine. This routine
attempts to service the request out of the current memory block, or, if it cannot, out of
a newly allocated block.
Arguments:
Handle - A valid PMHANDLE.
Size - Contains the size in bytes that the caller needs from the pool.
AlignSize - Provides an alignment value. The returned memory will be aligned on <alignsize> byte
boundaries.
Return Value:
The allocated memory, or, NULL if no memory could be allocated.
--*/
{
BOOL haveEnoughMemory = TRUE;
PVOID rMemory = NULL;
PPOOLHEADER poolHeader = (PPOOLHEADER) Handle;
PPMBLOCK currentBlock;
PALLOCATION allocation;
SIZE_T sizeNeeded;
UINT_PTR padLength;
MYASSERT(poolHeader != NULL);
MYASSERT(Size);
EnterCriticalSection (&g_PmCs);
__try {
//
// Assume that the current block of memory will be sufficient.
//
currentBlock = poolHeader->PoolHead;
#ifdef DEBUG
//
// Update stats.
//
poolHeader->CurrentAllocationSize += Size;
poolHeader->MaxAllocationSize = max(poolHeader->MaxAllocationSize,poolHeader->CurrentAllocationSize);
poolHeader->NumAllocationRequests++;
poolHeader->TotalAllocationRequestBytes += Size;
#endif
//
// Determine if more memory is needed, attempt to add if needed. Note that the size
// must include the size of an ALLOCATION struct in addition to the size required
// by the callee. Note the references to AlignSize in the test below. This is to ensure
// that there is enough memory to allocate after taking into acount data alignment.
//
sizeNeeded = Size + sizeof(ALLOCATION);
if (currentBlock->Size - currentBlock->Index < sizeNeeded + AlignSize) {
haveEnoughMemory = pPmAddMemory(poolHeader,sizeNeeded + AlignSize);
//
// Make sure that the currentBlock is correctly set
//
currentBlock = poolHeader->PoolHead;
}
//
// If there is enough memory available, return it.
//
if (haveEnoughMemory) {
if (AlignSize) {
padLength = (UINT_PTR) currentBlock + sizeof(PMBLOCK)
+ currentBlock->Index + sizeof(ALLOCATION);
currentBlock->Index += (AlignSize - (padLength % AlignSize)) % AlignSize;
}
//
// Save a reference to this block in the memorys ALLOCATION structure.
// This will be used to decrease the use count on a block when releasing
// memory.
//
allocation = (PALLOCATION) &(currentBlock->RawMemory[currentBlock->Index]);
allocation->ParentBlock = currentBlock;
#ifdef DEBUG
//
// Track this memory.
//
allocation->DogTag = VALIDDOGTAG;
allocation->Size = Size;
allocation->Next = poolHeader->AllocationList;
allocation->Prev = NULL;
if (poolHeader->AllocationList) {
poolHeader->AllocationList->Prev = allocation;
}
poolHeader->AllocationList = allocation;
if (poolHeader->FreeCalled != WHO_CARES) {
g_PoolCurrUsedAlloc += Size;
if (g_PoolMaxUsedAlloc < g_PoolCurrUsedAlloc) {
g_PoolMaxUsedAlloc = g_PoolCurrUsedAlloc;
}
DebugRegisterAllocationEx (
POOLMEM_POINTER,
allocation,
g_TrackFile,
g_TrackLine,
g_TrackAlloc
);
}
#endif
//
// Ok, get a reference to the actual memory to return to the user.
//
rMemory = (PVOID)
&(currentBlock->RawMemory[currentBlock->Index + sizeof(ALLOCATION)]);
//
// Update memory block data fields.
//
currentBlock->Index += sizeNeeded;
currentBlock->UseCount++;
}
else {
DEBUGMSG((DBG_ERROR,
"GetPoolMemory Failed. Size: %u",Size));
}
} __finally {
LeaveCriticalSection (&g_PmCs);
}
return rMemory;
}
VOID
PmReleaseMemory (
IN PMHANDLE Handle,
IN PCVOID Memory
)
/*++
Routine Description:
PmReleaseMemory notifies the Pool that a piece of memory is no longer needed.
if all memory within a non-active block (i.e. not the first block) is released,
that block will be freed. If all memory is released within an active block, that blocks
stats are simply cleared, effectively reclaiming its space.
Arguments:
Handle - A Handle to a Pool of Memory.
Memory - Contains the address of the memory that is no longer needed.
Return Value:
None.
--*/
{
PALLOCATION allocation;
PPOOLHEADER poolHeader = (PPOOLHEADER) Handle;
MYASSERT(poolHeader != NULL && Memory != NULL);
EnterCriticalSection (&g_PmCs);
__try {
//
// Get a reference to the ALLOCATION struct that precedes the actual memory.
//
allocation = (PALLOCATION) Memory - 1;
#ifdef DEBUG
//
// Update stats.
//
poolHeader->NumFreeRequests++; //lint !e613
poolHeader->CurrentAllocationSize -= allocation->Size;
#endif
#ifdef DEBUG
if (poolHeader->FreeCalled == FREE_NOT_CALLED) { //lint !e613
poolHeader->FreeCalled = FREE_CALLED; //lint !e613
}
//
// Check the dog tag on the allocation to provide sanity checking on the memory passed in.
//
if (allocation->DogTag != VALIDDOGTAG) {
if (allocation->DogTag == FREEDOGTAG) {
DEBUGMSG((
DBG_WHOOPS,
"Poolmem Error! This dogtag has already been freed! Pool: %s",
poolHeader->Name
));
} else {
DEBUGMSG ((
DBG_WHOOPS,
"Poolmem Error! Unknown value found in allocation dogtag. Pool: %s",
poolHeader->Name
));
MYASSERT (FALSE); //lint !e506
}
__leave;
} else {
allocation->DogTag = FREEDOGTAG;
}
if (allocation->Next) {
allocation->Next->Prev = allocation->Prev;
}
if (poolHeader->AllocationList == allocation) { //lint !e613
poolHeader->AllocationList = allocation->Next; //lint !e613
} else {
allocation->Prev->Next = allocation->Next;
}
if (poolHeader->FreeCalled != WHO_CARES) { //lint !e613
g_PoolCurrUsedAlloc -= allocation->Size;
DebugUnregisterAllocation(POOLMEM_POINTER,allocation);
}
#endif
//
// Check to make sure this memory has not previously been freed.
//
if (allocation->ParentBlock == NULL) {
DEBUGMSG((
DBG_WHOOPS,
"PoolMem Error! previously freed memory passed to PoolMemReleaseMemory. Pool: %s",
poolHeader->Name
));
__leave;
}
//
// Update the use count on this allocations parent block.
//
allocation->ParentBlock->UseCount--;
if (allocation->ParentBlock->UseCount == 0) {
//
// This was the last allocation still referring to the parent block.
//
if (allocation->ParentBlock != poolHeader->PoolHead) { //lint !e613
//
// Since the parent block isn't the active block, simply delete it.
//
#ifdef DEBUG
//
// Adjust stats.
//
poolHeader->NumBlockFrees++; //lint !e613
poolHeader->CurrentlyAllocatedMemory -=
allocation->ParentBlock->Size + sizeof(PMBLOCK); //lint !e613
#endif
if (allocation->ParentBlock->NextBlock) {
allocation->ParentBlock->NextBlock->PrevBlock =
allocation->ParentBlock->PrevBlock;
}
allocation->ParentBlock->PrevBlock->NextBlock =
allocation->ParentBlock->NextBlock;
#ifdef DEBUG
g_PoolCurrTotalAlloc -= (allocation->ParentBlock->Size + sizeof(PMBLOCK));
g_PoolCurrActiveAlloc -= allocation->ParentBlock->Size;
#endif
MemFree(g_hHeap,0,allocation->ParentBlock);
}
else {
//
// Since this is the active block, reset it.
//
allocation->ParentBlock->Index = 0;
allocation->ParentBlock = NULL;
#ifdef DEBUG
poolHeader->NumBlockClears++; //lint !e613
#endif
}
}
else {
allocation->ParentBlock = NULL;
}
} __finally {
LeaveCriticalSection (&g_PmCs);
}
}
#ifdef DEBUG
PMHANDLE
RealPmCreateNamedPoolEx (
IN PCSTR Name,
IN DWORD BlockSize OPTIONAL
)
{
PMHANDLE pool;
PPOOLHEADER poolHeader;
pool = RealPmCreatePoolEx (BlockSize);
if (pool) {
poolHeader = (PPOOLHEADER) pool;
StringCopyByteCountA (poolHeader->Name, Name, MAX_POOL_NAME);
MYASSERT (!poolHeader->TotalAllocationRequestBytes);
}
return pool;
}
#endif
PSTR
PmDuplicateMultiSzA (
IN PMHANDLE Handle,
IN PCSTR MultiSzToCopy
)
{
PSTR rString = (PSTR)MultiSzToCopy;
SIZE_T size;
if (MultiSzToCopy == NULL) {
return NULL;
}
while (rString [0] != 0) {
rString = GetEndOfStringA (rString) + 1; //lint !e613
}
size = (rString - MultiSzToCopy + 1) * sizeof(CHAR);
rString = PmGetAlignedMemory(Handle, size);
memcpy (rString, MultiSzToCopy, size);
return rString;
}
PWSTR
PmDuplicateMultiSzW (
IN PMHANDLE Handle,
IN PCWSTR MultiSzToCopy
)
{
PWSTR rString = (PWSTR)MultiSzToCopy;
SIZE_T size;
if (MultiSzToCopy == NULL) {
return NULL;
}
while (rString [0] != 0) {
rString = GetEndOfStringW (rString) + 1;
}
size = (rString - MultiSzToCopy + 1) * sizeof(WCHAR);
rString = PmGetAlignedMemory(Handle, size);
memcpy (rString, MultiSzToCopy, size);
return rString;
}
#ifdef DEBUG
VOID
PmDisableTracking (
IN PMHANDLE Handle
)
/*++
Routine Description:
PmDisableTracking suppresses the debug output caused by a pool
that has a mix of freed and non-freed blocks.
Arguments:
Handle - A Handle to a Pool of Memory.
Return Value:
None.
--*/
{
PPOOLHEADER poolHeader = (PPOOLHEADER) Handle;
MYASSERT(poolHeader != NULL);
poolHeader->FreeCalled = WHO_CARES;
}
VOID
PmDumpStatistics (
VOID
)
{
DEBUGMSG ((
DBG_STATS,
"Pools usage:\nPeak : Pools:%-3d Total:%-8d Usable:%-8d Used:%-8d\nCurrent: Pools:%-3d Total:%-8d Usable:%-8d Leak:%-8d",
g_PoolMaxPools,
g_PoolMaxTotalAlloc,
g_PoolMaxActiveAlloc,
g_PoolMaxUsedAlloc,
g_PoolCurrPools,
g_PoolCurrTotalAlloc,
g_PoolCurrActiveAlloc,
g_PoolCurrUsedAlloc
));
}
#endif
| 23.719534 | 132 | 0.571833 | [
"3d"
] |
2cbbe0052c9e62e50f3219cc6d04da37889ef076 | 1,610 | h | C | kernel/system_tree/system_tree_root.h | martin-hughes/project_azalea | 28aa0183cde350073cf0167df3f51435ea409c8b | [
"MIT"
] | 13 | 2017-12-20T00:02:38.000Z | 2022-01-07T11:18:36.000Z | kernel/system_tree/system_tree_root.h | martin-hughes/project_azalea | 28aa0183cde350073cf0167df3f51435ea409c8b | [
"MIT"
] | 21 | 2016-09-21T16:50:39.000Z | 2020-04-12T12:58:19.000Z | kernel/system_tree/system_tree_root.h | martin-hughes/project_azalea | 28aa0183cde350073cf0167df3f51435ea409c8b | [
"MIT"
] | 6 | 2017-12-20T00:02:27.000Z | 2019-03-21T16:28:24.000Z | /// @file
/// @brief Declare the root of the system tree.
#pragma once
#include "system_tree/system_tree_branch.h"
#include "system_tree/system_tree_simple_branch.h"
/// @brief A simple System Tree Branch class for the root of the tree
///
/// The root of the tree contains all other elements of the tree. This object contains a single branch which itself
/// contains all the elements in the tree. This allows us to easily refer to the root of the tree with the pathname
/// '\\'
class system_tree_root : public ISystemTreeBranch
{
public:
/// @brief Standard constructor
system_tree_root();
/// @brief Standard destructor
virtual ~system_tree_root();
// Overrides from ISystemTreeBranch
virtual ERR_CODE get_child(const std::string &name, std::shared_ptr<ISystemTreeLeaf> &child) override;
virtual ERR_CODE add_child(const std::string &name, std::shared_ptr<ISystemTreeLeaf> child) override;
virtual ERR_CODE create_child(const std::string &name, std::shared_ptr<ISystemTreeLeaf> &child) override;
virtual ERR_CODE rename_child(const std::string &old_name, const std::string &new_name) override;
virtual ERR_CODE delete_child(const std::string &name) override;
virtual std::pair<ERR_CODE, uint64_t> num_children() override;
virtual std::pair<ERR_CODE, std::vector<std::string>>
enum_children(std::string start_from, uint64_t max_count) override;
private:
/// Used to ensure that only one instance of the root of the tree exists at once.
static uint32_t number_of_instances;
/// The actual root of the system tree
std::shared_ptr<system_tree_simple_branch> root;
};
| 40.25 | 115 | 0.763354 | [
"object",
"vector"
] |
2cbc70aaa7c37cfc221449ab24a0f3c96c3416f6 | 9,702 | h | C | server/deps/nodejs/include/aliased_buffer.h | ZackaryH8/altv-js-module | afc4be85967850016357dade2fdcad717c1ce882 | [
"MIT"
] | 57 | 2022-01-23T11:43:38.000Z | 2022-03-18T09:56:50.000Z | server/deps/nodejs/include/aliased_buffer.h | ZackaryH8/altv-js-module | afc4be85967850016357dade2fdcad717c1ce882 | [
"MIT"
] | 8 | 2020-06-22T07:58:15.000Z | 2021-11-15T13:55:08.000Z | server/deps/nodejs/include/aliased_buffer.h | ZackaryH8/altv-js-module | afc4be85967850016357dade2fdcad717c1ce882 | [
"MIT"
] | 2 | 2020-08-20T16:08:00.000Z | 2021-11-01T14:57:30.000Z | #ifndef SRC_ALIASED_BUFFER_H_
#define SRC_ALIASED_BUFFER_H_
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#include <cinttypes>
#include "util-inl.h"
#include "v8.h"
namespace node {
typedef size_t AliasedBufferIndex;
/**
* Do not use this class directly when creating instances of it - use the
* Aliased*Array defined at the end of this file instead.
*
* This class encapsulates the technique of having a native buffer mapped to
* a JS object. Writes to the native buffer can happen efficiently without
* going through JS, and the data is then available to user's via the exposed
* JS object.
*
* While this technique is computationally efficient, it is effectively a
* write to JS program state w/out going through the standard
* (monitored) API. Thus any VM capabilities to detect the modification are
* circumvented.
*
* The encapsulation herein provides a placeholder where such writes can be
* observed. Any notification APIs will be left as a future exercise.
*/
template <class NativeT,
class V8T,
// SFINAE NativeT to be scalar
typename = std::enable_if_t<std::is_scalar<NativeT>::value>>
class AliasedBufferBase {
public:
AliasedBufferBase(v8::Isolate* isolate,
const size_t count,
const AliasedBufferIndex* index = nullptr)
: isolate_(isolate), count_(count), byte_offset_(0), index_(index) {
CHECK_GT(count, 0);
if (index != nullptr) {
// Will be deserialized later.
return;
}
const v8::HandleScope handle_scope(isolate_);
const size_t size_in_bytes =
MultiplyWithOverflowCheck(sizeof(NativeT), count);
// allocate v8 ArrayBuffer
v8::Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(
isolate_, size_in_bytes);
buffer_ = static_cast<NativeT*>(ab->GetBackingStore()->Data());
// allocate v8 TypedArray
v8::Local<V8T> js_array = V8T::New(ab, byte_offset_, count);
js_array_ = v8::Global<V8T>(isolate, js_array);
}
/**
* Create an AliasedBufferBase over a sub-region of another aliased buffer.
* The two will share a v8::ArrayBuffer instance &
* a native buffer, but will each read/write to different sections of the
* native buffer.
*
* Note that byte_offset must by aligned by sizeof(NativeT).
*/
// TODO(refack): refactor into a non-owning `AliasedBufferBaseView`
AliasedBufferBase(
v8::Isolate* isolate,
const size_t byte_offset,
const size_t count,
const AliasedBufferBase<uint8_t, v8::Uint8Array>& backing_buffer,
const AliasedBufferIndex* index = nullptr)
: isolate_(isolate),
count_(count),
byte_offset_(byte_offset),
index_(index) {
if (index != nullptr) {
// Will be deserialized later.
return;
}
const v8::HandleScope handle_scope(isolate_);
v8::Local<v8::ArrayBuffer> ab = backing_buffer.GetArrayBuffer();
// validate that the byte_offset is aligned with sizeof(NativeT)
CHECK_EQ(byte_offset & (sizeof(NativeT) - 1), 0);
// validate this fits inside the backing buffer
CHECK_LE(MultiplyWithOverflowCheck(sizeof(NativeT), count),
ab->ByteLength() - byte_offset);
buffer_ = reinterpret_cast<NativeT*>(
const_cast<uint8_t*>(backing_buffer.GetNativeBuffer() + byte_offset));
v8::Local<V8T> js_array = V8T::New(ab, byte_offset, count);
js_array_ = v8::Global<V8T>(isolate, js_array);
}
AliasedBufferBase(const AliasedBufferBase& that)
: isolate_(that.isolate_),
count_(that.count_),
byte_offset_(that.byte_offset_),
buffer_(that.buffer_) {
DCHECK_NULL(index_);
js_array_ = v8::Global<V8T>(that.isolate_, that.GetJSArray());
}
AliasedBufferIndex Serialize(v8::Local<v8::Context> context,
v8::SnapshotCreator* creator) {
DCHECK_NULL(index_);
return creator->AddData(context, GetJSArray());
}
inline void Deserialize(v8::Local<v8::Context> context) {
DCHECK_NOT_NULL(index_);
v8::Local<V8T> arr =
context->GetDataFromSnapshotOnce<V8T>(*index_).ToLocalChecked();
// These may not hold true for AliasedBuffers that have grown, so should
// be removed when we expand the snapshot support.
DCHECK_EQ(count_, arr->Length());
DCHECK_EQ(byte_offset_, arr->ByteOffset());
uint8_t* raw =
static_cast<uint8_t*>(arr->Buffer()->GetBackingStore()->Data());
buffer_ = reinterpret_cast<NativeT*>(raw + byte_offset_);
js_array_.Reset(isolate_, arr);
index_ = nullptr;
}
AliasedBufferBase& operator=(AliasedBufferBase&& that) noexcept {
DCHECK_NULL(index_);
this->~AliasedBufferBase();
isolate_ = that.isolate_;
count_ = that.count_;
byte_offset_ = that.byte_offset_;
buffer_ = that.buffer_;
js_array_.Reset(isolate_, that.js_array_.Get(isolate_));
that.buffer_ = nullptr;
that.js_array_.Reset();
return *this;
}
/**
* Helper class that is returned from operator[] to support assignment into
* a specified location.
*/
class Reference {
public:
Reference(AliasedBufferBase<NativeT, V8T>* aliased_buffer, size_t index)
: aliased_buffer_(aliased_buffer), index_(index) {}
Reference(const Reference& that)
: aliased_buffer_(that.aliased_buffer_),
index_(that.index_) {
}
inline Reference& operator=(const NativeT& val) {
aliased_buffer_->SetValue(index_, val);
return *this;
}
inline Reference& operator=(const Reference& val) {
return *this = static_cast<NativeT>(val);
}
operator NativeT() const {
return aliased_buffer_->GetValue(index_);
}
inline Reference& operator+=(const NativeT& val) {
const NativeT current = aliased_buffer_->GetValue(index_);
aliased_buffer_->SetValue(index_, current + val);
return *this;
}
inline Reference& operator+=(const Reference& val) {
return this->operator+=(static_cast<NativeT>(val));
}
inline Reference& operator-=(const NativeT& val) {
const NativeT current = aliased_buffer_->GetValue(index_);
aliased_buffer_->SetValue(index_, current - val);
return *this;
}
private:
AliasedBufferBase<NativeT, V8T>* aliased_buffer_;
size_t index_;
};
/**
* Get the underlying v8 TypedArray overlayed on top of the native buffer
*/
v8::Local<V8T> GetJSArray() const {
DCHECK_NULL(index_);
return js_array_.Get(isolate_);
}
void Release() {
DCHECK_NULL(index_);
js_array_.Reset();
}
/**
* Get the underlying v8::ArrayBuffer underlying the TypedArray and
* overlaying the native buffer
*/
v8::Local<v8::ArrayBuffer> GetArrayBuffer() const {
return GetJSArray()->Buffer();
}
/**
* Get the underlying native buffer. Note that all reads/writes should occur
* through the GetValue/SetValue/operator[] methods
*/
inline const NativeT* GetNativeBuffer() const {
DCHECK_NULL(index_);
return buffer_;
}
/**
* Synonym for GetBuffer()
*/
inline const NativeT* operator * () const {
return GetNativeBuffer();
}
/**
* Set position index to given value.
*/
inline void SetValue(const size_t index, NativeT value) {
DCHECK_LT(index, count_);
DCHECK_NULL(index_);
buffer_[index] = value;
}
/**
* Get value at position index
*/
inline const NativeT GetValue(const size_t index) const {
DCHECK_NULL(index_);
DCHECK_LT(index, count_);
return buffer_[index];
}
/**
* Effectively, a synonym for GetValue/SetValue
*/
Reference operator[](size_t index) {
DCHECK_NULL(index_);
return Reference(this, index);
}
NativeT operator[](size_t index) const {
return GetValue(index);
}
size_t Length() const {
return count_;
}
// Should only be used to extend the array.
// Should only be used on an owning array, not one created as a sub array of
// an owning `AliasedBufferBase`.
void reserve(size_t new_capacity) {
DCHECK_NULL(index_);
DCHECK_GE(new_capacity, count_);
DCHECK_EQ(byte_offset_, 0);
const v8::HandleScope handle_scope(isolate_);
const size_t old_size_in_bytes = sizeof(NativeT) * count_;
const size_t new_size_in_bytes = MultiplyWithOverflowCheck(sizeof(NativeT),
new_capacity);
// allocate v8 new ArrayBuffer
v8::Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(
isolate_, new_size_in_bytes);
// allocate new native buffer
NativeT* new_buffer = static_cast<NativeT*>(ab->GetBackingStore()->Data());
// copy old content
memcpy(new_buffer, buffer_, old_size_in_bytes);
// allocate v8 TypedArray
v8::Local<V8T> js_array = V8T::New(ab, byte_offset_, new_capacity);
// move over old v8 TypedArray
js_array_ = std::move(v8::Global<V8T>(isolate_, js_array));
buffer_ = new_buffer;
count_ = new_capacity;
}
private:
v8::Isolate* isolate_ = nullptr;
size_t count_ = 0;
size_t byte_offset_ = 0;
NativeT* buffer_ = nullptr;
v8::Global<V8T> js_array_;
// Deserialize data
const AliasedBufferIndex* index_ = nullptr;
};
typedef AliasedBufferBase<int32_t, v8::Int32Array> AliasedInt32Array;
typedef AliasedBufferBase<uint8_t, v8::Uint8Array> AliasedUint8Array;
typedef AliasedBufferBase<uint32_t, v8::Uint32Array> AliasedUint32Array;
typedef AliasedBufferBase<double, v8::Float64Array> AliasedFloat64Array;
typedef AliasedBufferBase<uint64_t, v8::BigUint64Array> AliasedBigUint64Array;
} // namespace node
#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#endif // SRC_ALIASED_BUFFER_H_
| 30.702532 | 79 | 0.680787 | [
"object"
] |
2cbd43bfe5448486123be472df7613009b5e708f | 2,340 | h | C | libs/sfm/feature_set.h | lemony-fresh/mve | d90cc2c813fef026f7732c5a26f6c15973a36042 | [
"BSD-3-Clause"
] | 1 | 2019-05-30T13:19:21.000Z | 2019-05-30T13:19:21.000Z | libs/sfm/feature_set.h | lemony-fresh/mve | d90cc2c813fef026f7732c5a26f6c15973a36042 | [
"BSD-3-Clause"
] | null | null | null | libs/sfm/feature_set.h | lemony-fresh/mve | d90cc2c813fef026f7732c5a26f6c15973a36042 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2015, Simon Fuhrmann
* TU Darmstadt - Graphics, Capture and Massively Parallel Computing
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD 3-Clause license. See the LICENSE.txt file for details.
*/
#ifndef SFM_FEATURE_SET_HEADER
#define SFM_FEATURE_SET_HEADER
#include <vector>
#include "math/vector.h"
#include "util/aligned_memory.h"
#include "sfm/sift.h"
#include "sfm/surf.h"
#include "sfm/defines.h"
SFM_NAMESPACE_BEGIN
/**
* The FeatureSet holds per-feature information for a single view, and
* allows to transparently compute and match multiple feature types.
*/
class FeatureSet
{
public:
/** Bitmask with feature types. */
enum FeatureTypes
{
FEATURE_SIFT = 1 << 0,
FEATURE_SURF = 1 << 1,
FEATURE_ALL = 0xFF
};
/** Options for feature detection and matching. */
struct Options
{
Options (void);
FeatureTypes feature_types;
Sift::Options sift_opts;
Surf::Options surf_opts;
};
public:
FeatureSet (void);
explicit FeatureSet (Options const& options);
void set_options (Options const& options);
/** Computes the features specified in the options. */
void compute_features (mve::ByteImage::Ptr image);
/** Clear descriptor data. */
void clear_descriptors (void);
public:
/** Image dimension used for feature computation. */
int width, height;
/** Per-feature image position. */
std::vector<math::Vec2f> positions;
/** Per-feature image color. */
std::vector<math::Vec3uc> colors;
/** The SIFT descriptors. */
Sift::Descriptors sift_descriptors;
/** The SURF descriptors. */
Surf::Descriptors surf_descriptors;
private:
void compute_sift (mve::ByteImage::ConstPtr image);
void compute_surf (mve::ByteImage::ConstPtr image);
private:
Options opts;
};
/* ------------------------ Implementation ------------------------ */
inline
FeatureSet::Options::Options (void)
: feature_types(FEATURE_SIFT)
{
}
inline
FeatureSet::FeatureSet (void)
{
}
inline
FeatureSet::FeatureSet (Options const& options)
: opts(options)
{
}
inline void
FeatureSet::set_options (Options const& options)
{
this->opts = options;
}
SFM_NAMESPACE_END
#endif /* SFM_FEATURE_SET_HEADER */
| 21.869159 | 70 | 0.669231 | [
"vector"
] |
2cbf165fceaf3e56934f6dc20fcec8a58ba8af9b | 8,682 | h | C | common/Encoding_intl.h | o-netusa/cppbase | a74c2b1a7eb33fb6cdd7fd54d90f58ae588d269e | [
"Apache-2.0"
] | 9 | 2021-07-24T18:42:28.000Z | 2022-03-23T15:36:28.000Z | common/Encoding_intl.h | o-netusa/cppbase | a74c2b1a7eb33fb6cdd7fd54d90f58ae588d269e | [
"Apache-2.0"
] | null | null | null | common/Encoding_intl.h | o-netusa/cppbase | a74c2b1a7eb33fb6cdd7fd54d90f58ae588d269e | [
"Apache-2.0"
] | 3 | 2021-07-24T17:47:32.000Z | 2021-09-23T02:47:49.000Z | /**************************************************************************
* @file: Encoding_intl.h
* @brief: Encoding utilities based on
* https://github.com/chronoxor/CppCommon/blob/master/include/string/encoding.h
*
* Copyright (c) 2021 O-Net Technologies (Group) Limited.
*************************************************************************/
#include <algorithm>
#include <cassert>
#include <codecvt>
#include <locale>
#include <vector>
namespace cppbase { namespace encoding {
std::string ToUTF8(std::wstring_view wstr)
{
#if defined(__CYGWIN__) || defined(__MINGW32__) || defined(__MINGW64__)
std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert;
return convert.to_bytes((char16_t*)wstr.data(), (char16_t*)wstr.data() + wstr.size());
#elif defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
std::wstring_convert<std::codecvt_utf8<wchar_t> > convert;
return convert.to_bytes(wstr.data(), wstr.data() + wstr.size());
#elif defined(_WIN32) || defined(_WIN64)
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t> > convert;
return convert.to_bytes(wstr.data(), wstr.data() + wstr.size());
#endif
}
std::wstring FromUTF8(std::string_view str)
{
#if defined(__CYGWIN__) || defined(__MINGW32__) || defined(__MINGW64__)
std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert;
auto tmp = convert.from_bytes(str.data(), str.data() + str.size());
return std::wstring(tmp.data(), tmp.data() + tmp.size());
#elif defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)
std::wstring_convert<std::codecvt_utf8<wchar_t> > convert;
return convert.from_bytes(str.data(), str.data() + str.size());
#elif defined(_WIN32) || defined(_WIN64)
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t> > convert;
return convert.from_bytes(str.data(), str.data() + str.size());
#endif
}
std::u16string UTF8toUTF16(std::string_view str)
{
#if defined(_MSC_VER)
std::wstring_convert<std::codecvt_utf8_utf16<uint16_t>, uint16_t> convert;
auto tmp = convert.from_bytes(str.data(), str.data() + str.size());
return std::u16string(tmp.data(), tmp.data() + tmp.size());
#else
std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert;
return convert.from_bytes(str.data(), str.data() + str.size());
#endif
}
std::u32string UTF8toUTF32(std::string_view str)
{
#if defined(_MSC_VER)
std::wstring_convert<std::codecvt_utf8<uint32_t>, uint32_t> convert;
auto tmp = convert.from_bytes(str.data(), str.data() + str.size());
return std::u32string(tmp.data(), tmp.data() + tmp.size());
#else
std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> convert;
return convert.from_bytes(str.data(), str.data() + str.size());
#endif
}
std::string UTF16toUTF8(std::u16string_view str)
{
#if defined(_MSC_VER)
std::wstring_convert<std::codecvt_utf8_utf16<uint16_t>, uint16_t> convert;
return convert.to_bytes((uint16_t*)str.data(), (uint16_t*)str.data() + str.size());
#else
std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert;
return convert.to_bytes(str.data(), str.data() + str.size());
#endif
}
std::u32string UTF16toUTF32(std::u16string_view str)
{
std::string bytes;
bytes.reserve(str.size() * 2);
for (const char16_t ch : str)
{
bytes.push_back((uint8_t)(ch / 256));
bytes.push_back((uint8_t)(ch % 256));
}
#if defined(_MSC_VER)
std::wstring_convert<std::codecvt_utf16<uint32_t>, uint32_t> convert;
auto tmp = convert.from_bytes(bytes);
return std::u32string(tmp.data(), tmp.data() + tmp.size());
#else
std::wstring_convert<std::codecvt_utf16<char32_t>, char32_t> convert;
return convert.from_bytes(bytes);
#endif
}
std::string UTF32toUTF8(std::u32string_view str)
{
#if defined(_MSC_VER)
std::wstring_convert<std::codecvt_utf8<uint32_t>, uint32_t> convert;
return convert.to_bytes((uint32_t*)str.data(), (uint32_t*)str.data() + str.size());
#else
std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> convert;
return convert.to_bytes(str.data(), str.data() + str.size());
#endif
}
std::u16string UTF32toUTF16(std::u32string_view str)
{
#if defined(_MSC_VER)
std::wstring_convert<std::codecvt_utf16<uint32_t>, uint32_t> convert;
std::string bytes = convert.to_bytes((uint32_t*)str.data(), (uint32_t*)str.data() + str.size());
#else
std::wstring_convert<std::codecvt_utf16<char32_t>, char32_t> convert;
std::string bytes = convert.to_bytes(str.data(), str.data() + str.size());
#endif
std::u16string result;
result.reserve(bytes.size() / 2);
for (size_t i = 0; i < bytes.size(); i += 2)
result.push_back((char16_t)((uint8_t)(bytes[i]) * 256 + (uint8_t)(bytes[i + 1])));
return result;
}
std::string Base64Encode(std::string_view str)
{
const char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const size_t mods[] = {0, 2, 1};
size_t ilength = str.length();
size_t olength = 4 * ((ilength + 2) / 3);
std::string result;
result.resize(olength, 0);
for (size_t i = 0, j = 0; i < ilength;)
{
uint32_t octet_a = i < ilength ? (uint8_t)str[i++] : 0;
uint32_t octet_b = i < ilength ? (uint8_t)str[i++] : 0;
uint32_t octet_c = i < ilength ? (uint8_t)str[i++] : 0;
uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
result[j++] = base64[(triple >> 3 * 6) & 0x3F];
result[j++] = base64[(triple >> 2 * 6) & 0x3F];
result[j++] = base64[(triple >> 1 * 6) & 0x3F];
result[j++] = base64[(triple >> 0 * 6) & 0x3F];
}
for (size_t i = 0; i < mods[ilength % 3]; ++i)
result[result.size() - 1 - i] = '=';
return result;
}
std::string Base64Decode(std::string_view str)
{
static const unsigned char base64[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3e, 0x00,
0x00, 0x00, 0x3f, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
0x19, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21,
0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30,
0x31, 0x32, 0x33, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00};
size_t ilength = str.length();
if (ilength % 4 != 0)
return "";
size_t olength = ilength / 4 * 3;
if (str[ilength - 1] == '=')
olength--;
if (str[ilength - 2] == '=')
olength--;
std::string result;
result.resize(olength, 0);
for (size_t i = 0, j = 0; i < ilength;)
{
uint32_t sextet_a = str[i] == '=' ? 0 & i++ : base64[(uint8_t)str[i++]];
uint32_t sextet_b = str[i] == '=' ? 0 & i++ : base64[(uint8_t)str[i++]];
uint32_t sextet_c = str[i] == '=' ? 0 & i++ : base64[(uint8_t)str[i++]];
uint32_t sextet_d = str[i] == '=' ? 0 & i++ : base64[(uint8_t)str[i++]];
uint32_t triple =
(sextet_a << 3 * 6) + (sextet_b << 2 * 6) + (sextet_c << 1 * 6) + (sextet_d << 0 * 6);
if (j < olength)
result[j++] = (triple >> 2 * 8) & 0xFF;
if (j < olength)
result[j++] = (triple >> 1 * 8) & 0xFF;
if (j < olength)
result[j++] = (triple >> 0 * 8) & 0xFF;
}
return result;
}
}} // namespace cppbase::encoding | 39.285068 | 100 | 0.621631 | [
"vector"
] |
2cbfbaa9a9bcf98e5042d49c7e6e25bcbd38a42f | 2,235 | h | C | Project/Temp/StagingArea/Data/il2cppOutput/System_System_Text_RegularExpressions_PatternCompi3979537293MethodDeclarations.h | Yuunagi-Yu/NumberDisk | f1cf414dbfe8d0094d3ef11b37839f6caf58ae9f | [
"MIT"
] | null | null | null | Project/Temp/StagingArea/Data/il2cppOutput/System_System_Text_RegularExpressions_PatternCompi3979537293MethodDeclarations.h | Yuunagi-Yu/NumberDisk | f1cf414dbfe8d0094d3ef11b37839f6caf58ae9f | [
"MIT"
] | null | null | null | Project/Temp/StagingArea/Data/il2cppOutput/System_System_Text_RegularExpressions_PatternCompi3979537293MethodDeclarations.h | Yuunagi-Yu/NumberDisk | f1cf414dbfe8d0094d3ef11b37839f6caf58ae9f | [
"MIT"
] | null | null | null | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include <assert.h>
#include <exception>
// System.Text.RegularExpressions.PatternCompiler/PatternLinkStack
struct PatternLinkStack_t3979537293;
// System.Object
struct Il2CppObject;
#include "codegen/il2cpp-codegen.h"
#include "mscorlib_System_Object2689449295.h"
// System.Void System.Text.RegularExpressions.PatternCompiler/PatternLinkStack::.ctor()
extern "C" void PatternLinkStack__ctor_m2604966645 (PatternLinkStack_t3979537293 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void System.Text.RegularExpressions.PatternCompiler/PatternLinkStack::set_BaseAddress(System.Int32)
extern "C" void PatternLinkStack_set_BaseAddress_m781925478 (PatternLinkStack_t3979537293 * __this, int32_t ___value0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Int32 System.Text.RegularExpressions.PatternCompiler/PatternLinkStack::get_OffsetAddress()
extern "C" int32_t PatternLinkStack_get_OffsetAddress_m1332100949 (PatternLinkStack_t3979537293 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void System.Text.RegularExpressions.PatternCompiler/PatternLinkStack::set_OffsetAddress(System.Int32)
extern "C" void PatternLinkStack_set_OffsetAddress_m1842146404 (PatternLinkStack_t3979537293 * __this, int32_t ___value0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Int32 System.Text.RegularExpressions.PatternCompiler/PatternLinkStack::GetOffset(System.Int32)
extern "C" int32_t PatternLinkStack_GetOffset_m2889934101 (PatternLinkStack_t3979537293 * __this, int32_t ___target_addr0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Object System.Text.RegularExpressions.PatternCompiler/PatternLinkStack::GetCurrent()
extern "C" Il2CppObject * PatternLinkStack_GetCurrent_m2994645935 (PatternLinkStack_t3979537293 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void System.Text.RegularExpressions.PatternCompiler/PatternLinkStack::SetCurrent(System.Object)
extern "C" void PatternLinkStack_SetCurrent_m3503232602 (PatternLinkStack_t3979537293 * __this, Il2CppObject * ___l0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
| 60.405405 | 169 | 0.844743 | [
"object"
] |
2cc49e562fd7f1951df37224c8133c462f259d65 | 5,616 | h | C | test/performance-regression/full-apps/qmcpack/src/SQD/SphericalPotential/RadialPotential.h | JKChenFZ/hclib | 50970656ac133477c0fbe80bb674fe88a19d7177 | [
"BSD-3-Clause"
] | 55 | 2015-07-28T01:32:58.000Z | 2022-02-27T16:27:46.000Z | test/performance-regression/full-apps/qmcpack/src/SQD/SphericalPotential/RadialPotential.h | JKChenFZ/hclib | 50970656ac133477c0fbe80bb674fe88a19d7177 | [
"BSD-3-Clause"
] | 66 | 2015-06-15T20:38:19.000Z | 2020-08-26T00:11:43.000Z | test/performance-regression/full-apps/qmcpack/src/SQD/SphericalPotential/RadialPotential.h | JKChenFZ/hclib | 50970656ac133477c0fbe80bb674fe88a19d7177 | [
"BSD-3-Clause"
] | 26 | 2015-10-26T22:11:51.000Z | 2021-03-02T22:09:15.000Z | //////////////////////////////////////////////////////////////////
// (c) Copyright 2003 by Jeongnim Kim and Jordan Vincent
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// National Center for Supercomputing Applications &
// Materials Computation Center
// University of Illinois, Urbana-Champaign
// Urbana, IL 61801
// e-mail: jnkim@ncsa.uiuc.edu
// Tel: 217-244-6319 (NCSA) 217-333-3324 (MCC)
//
// Supported by
// National Center for Supercomputing Applications, UIUC
// Materials Computation Center, UIUC
//////////////////////////////////////////////////////////////////
// -*- C++ -*-
#ifndef OHMMSHF_RADIALPOTENTIALBASE_H
#define OHMMSHF_RADIALPOTENTIALBASE_H
#include "SQD/HFConfiguration.h"
#include "OhmmsData/libxmldefs.h"
class Clebsch_Gordan;
/**
*@defgroup RadialPotential
*@brief Classes to define potentials on a radial grid.
*
*A radial potential is defined on a radial grid,
*OneDimGridBase<T> and RadialPotentialSet are used to represent
*the LHS of Radial Schrodinger Equation.
*/
namespace ohmmshf
{
/**
*@ingroup RadialPotential
*@class RadialPotentialBase
*@brief An abstract base class for a Radial Potential.
*
*Inherited classes implement the member function evaluate
*to calculate matrix elements for a Hamiltonian term.
*/
struct RadialPotentialBase
{
typedef SphericalOrbitalTraits::BasisSetType BasisSetType;
typedef SphericalOrbitalTraits::value_type value_type;
typedef SphericalOrbitalTraits::RadialGrid_t RadialGrid_t;
typedef SphericalOrbitalTraits::RadialOrbital_t RadialOrbital_t;
typedef SphericalOrbitalTraits::RadialOrbitalSet_t RadialOrbitalSet_t;
///lower-bound for eigenvalues
value_type MinEigenValue;
///upper-bound for eigenvalues
value_type MaxEigenValue;
///the core charge at infinity
value_type Qinfty;
///the cutoff radius
value_type Rcut;
///storage for an external potential
RadialOrbital_t* Vext;
///storage for a temporary integrand
RadialOrbital_t* integrand;
///constructor
RadialPotentialBase()
: MinEigenValue(0.0), MaxEigenValue(0.0), Qinfty(0.0), Rcut(1.0)
, Vext(0), integrand(0)
{}
///destructor
virtual ~RadialPotentialBase();
/**
*@param psi the wavefunction
*@param V the potential
*@param norb the number of orbitals
*@return The sum of the matrix elements of a Radial Potential \f$V(r)\f$
*@brief Calculates and assigns the values of a Randial Potential for
*each orbital.
*
\f[
\sum_{k=0}^{N_{orb}} \langle k|V(r)|k \rangle = \sum_{k=0}^{N_{orb}}
\int_0^{\infty} dr \: \psi_k^*(r)V(r)\psi_k(r)
\f]
*/
virtual
value_type evaluate(const BasisSetType& psi,
RadialOrbitalSet_t& V,
int norb) = 0;
/**
*@param n the principal quantum number
*@param l the angular quantum number
*@return the number of radial nodes
*/
virtual int getNumOfNodes(int n, int l)=0;
/**
*@param RootFileName the name of file root
*@brief Output the internal storage of the potential.
*@note Only applies for the Hartree and Exchange potentials.
*/
virtual void getStorage(const BasisSetType& psi,
const std::string& RootFileName);
/**
*@param ig the grid index
*@return the value of the external potential
*/
inline
value_type getV(int ig) const
{
return (*Vext)(ig);
}
/**@return the pointer of the data **/
inline value_type* data() const
{
if(Vext)
return Vext->data();
else
return NULL;
}
/**
*@param cur the current xml node to process
*@return true if the input is valid
*/
virtual bool put(xmlNodePtr cur)
{
return true;
}
};
/**
*@ingroup RadialPotential
*@class HartreePotential
*@brief Implements the Hartree potential.
*/
struct HartreePotential: public RadialPotentialBase
{
///the Clebsch Gordan coefficient matrix
Clebsch_Gordan *CG_coeff;
///aux functors
RadialOrbital_t *Ykii_r;
RadialOrbital_t *Ykjj_r;
/**store the matrix elements
\f$\langle \psi_i \psi_j |V| \psi_i \psi_j \rangle \f$ */
Vector<value_type> storage;
HartreePotential(Clebsch_Gordan* cg, int norb);
~HartreePotential();
value_type evaluate(const BasisSetType& psi,
RadialOrbitalSet_t& V, int norb);
void getStorage(const BasisSetType& psi,
const std::string& RootFileName);
int getNumOfNodes(int n, int l)
{
return 0;
}
};
/**
*@ingroup RadialPotential
*@class ExchangePotential
*@brief Implements the exchange potential
*/
struct ExchangePotential: public RadialPotentialBase
{
///the Clebsch Gordan coefficient matrix
Clebsch_Gordan *CG_coeff;
RadialOrbital_t *Ykij_r;
/**store the matrix elements
\f$\langle \psi_i \psi_j |V| \psi_j \psi_i \rangle \f$ */
Vector<value_type> storage;
ExchangePotential(Clebsch_Gordan* cg, int norb);
~ExchangePotential();
value_type evaluate(const BasisSetType& psi,
RadialOrbitalSet_t& V, int norb);
void getStorage(const BasisSetType& psi,
const std::string& RootFileName);
int getNumOfNodes(int n, int l)
{
return 0;
}
};
}
#endif
/***************************************************************************
* $RCSfile$ $Author: jmcminis $
* $Revision: 5794 $ $Date: 2013-04-25 20:14:53 -0400 (Thu, 25 Apr 2013) $
* $Id: RadialPotential.h 5794 2013-04-26 00:14:53Z jmcminis $
***************************************************************************/
| 27.80198 | 77 | 0.63693 | [
"vector"
] |
2ccd29619adf48ddd69c3fb61f6691277a654854 | 891 | c | C | cmds/feats/j/_jack_of_all_trades.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 9 | 2021-07-05T15:24:54.000Z | 2022-02-25T19:44:15.000Z | cmds/feats/j/_jack_of_all_trades.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 4 | 2021-03-15T18:56:39.000Z | 2021-08-17T17:08:22.000Z | cmds/feats/j/_jack_of_all_trades.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 10 | 2021-03-13T00:18:03.000Z | 2022-03-29T15:02:42.000Z | #include <std.h>
#include <daemons.h>
inherit FEAT;
void create()
{
::create();
feat_type("permanent");
feat_category("Performance");
feat_name("jack of all trades");
feat_prereq("Bard L21");
feat_desc("With this feat, the bard treats all skills as class skills.");
permanent(1);
set_required_for(({}));
}
int prerequisites(object ob)
{
if(!objectp(ob)) { return 0; }
if((int)ob->query_class_level("bard") < 21)
{
dest_effect();
return 0;
}
return ::prerequisites(ob);
}
void execute_feat()
{
::execute_feat();
dest_effect();
}
void permanent_effects(object ob)
{
::permanent_effects(ob);
dest_effect();
return;
}
void reverse_permanent_effects(object ob)
{
::reverse_permanent_effects(ob);
dest_effect();
return;
}
void dest_effect()
{
::dest_effect();
remove_feat(TO);
return;
}
| 16.2 | 77 | 0.628507 | [
"object"
] |
2cce1e6e4ec076a3f02659de9fe35ef9f714f990 | 2,463 | h | C | wrappers/7.0.0/vtkTransferAttributesWrap.h | axkibe/node-vtk | 900ad7b5500f672519da5aa24c99aa5a96466ef3 | [
"BSD-3-Clause"
] | 6 | 2016-02-03T12:48:36.000Z | 2020-09-16T15:07:51.000Z | wrappers/7.0.0/vtkTransferAttributesWrap.h | axkibe/node-vtk | 900ad7b5500f672519da5aa24c99aa5a96466ef3 | [
"BSD-3-Clause"
] | 4 | 2016-02-13T01:30:43.000Z | 2020-03-30T16:59:32.000Z | wrappers/7.0.0/vtkTransferAttributesWrap.h | axkibe/node-vtk | 900ad7b5500f672519da5aa24c99aa5a96466ef3 | [
"BSD-3-Clause"
] | null | null | null | /* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */
#ifndef NATIVE_EXTENSION_VTK_VTKTRANSFERATTRIBUTESWRAP_H
#define NATIVE_EXTENSION_VTK_VTKTRANSFERATTRIBUTESWRAP_H
#include <nan.h>
#include <vtkSmartPointer.h>
#include <vtkTransferAttributes.h>
#include "vtkPassInputTypeAlgorithmWrap.h"
#include "../../plus/plus.h"
class VtkTransferAttributesWrap : public VtkPassInputTypeAlgorithmWrap
{
public:
using Nan::ObjectWrap::Wrap;
static void Init(v8::Local<v8::Object> exports);
static void InitPtpl();
static void ConstructorGetter(
v8::Local<v8::String> property,
const Nan::PropertyCallbackInfo<v8::Value>& info);
VtkTransferAttributesWrap(vtkSmartPointer<vtkTransferAttributes>);
VtkTransferAttributesWrap();
~VtkTransferAttributesWrap( );
static Nan::Persistent<v8::FunctionTemplate> ptpl;
private:
static void New(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void DirectMappingOff(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void DirectMappingOn(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void FillInputPortInformation(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void GetDirectMapping(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void GetSourceArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void GetSourceFieldType(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void GetTargetArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void GetTargetFieldType(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void IsA(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void SetDirectMapping(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void SetSourceArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void SetSourceFieldType(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void SetTargetArrayName(const Nan::FunctionCallbackInfo<v8::Value>& info);
static void SetTargetFieldType(const Nan::FunctionCallbackInfo<v8::Value>& info);
#ifdef VTK_NODE_PLUS_VTKTRANSFERATTRIBUTESWRAP_CLASSDEF
VTK_NODE_PLUS_VTKTRANSFERATTRIBUTESWRAP_CLASSDEF
#endif
};
#endif
| 43.210526 | 89 | 0.793341 | [
"object"
] |
2cd27619f73f67f3716e65852a874bb78af39e22 | 502 | h | C | Output.h | Hagen23/Monodomain-SPH | be825dfa78ba30ebdc42f799f9b87821bd62908f | [
"MIT"
] | null | null | null | Output.h | Hagen23/Monodomain-SPH | be825dfa78ba30ebdc42f799f9b87821bd62908f | [
"MIT"
] | null | null | null | Output.h | Hagen23/Monodomain-SPH | be825dfa78ba30ebdc42f799f9b87821bd62908f | [
"MIT"
] | 1 | 2019-03-15T09:31:00.000Z | 2019-03-15T09:31:00.000Z | /* Model output written to file */
#ifndef CARDIAC_WRITE_H
#define CARDIAC_WRITE_H
#include <fstream>
#include <string>
#include "Types.h"
#include "MonodomainSPH.h"
class Output
{
public:
void open_file(std::string format, std::string fileName = "");
void write_file(ARRAY2D& Vm, int tstep, int output_freq);
void write_file(Particle* Particles, int Number_particles, int tstep, int output_freq);
void close_file();
private:
bool isAscii;
std::ofstream outputFile;
};
#endif
| 20.916667 | 90 | 0.7251 | [
"model"
] |
2cd4d3040ba2de8ff0d4e25e7ee0b3aae10d97ac | 13,442 | c | C | openbsd/sys/arch/mvme88k/mvme88k/locore_c_routines.c | shisa/kame-shisa | 25dfcf220c0cd8192e475a602501206ccbd9263e | [
"BSD-3-Clause"
] | 1 | 2019-10-15T06:29:32.000Z | 2019-10-15T06:29:32.000Z | openbsd/sys/arch/mvme88k/mvme88k/locore_c_routines.c | shisa/kame-shisa | 25dfcf220c0cd8192e475a602501206ccbd9263e | [
"BSD-3-Clause"
] | null | null | null | openbsd/sys/arch/mvme88k/mvme88k/locore_c_routines.c | shisa/kame-shisa | 25dfcf220c0cd8192e475a602501206ccbd9263e | [
"BSD-3-Clause"
] | 3 | 2017-01-09T02:15:36.000Z | 2019-10-15T06:30:25.000Z | /* $OpenBSD: locore_c_routines.c,v 1.39 2004/01/08 14:29:46 miod Exp $ */
/*
* Mach Operating System
* Copyright (c) 1993-1991 Carnegie Mellon University
* Copyright (c) 1991 OMRON Corporation
* All Rights Reserved.
*
* Permission to use, copy, modify and distribute this software and its
* documentation is hereby granted, provided that both the copyright
* notice and this permission notice appear in all copies of the
* software, derivative works or modified versions, and any portions
* thereof, and that both notices appear in supporting documentation.
*
* CARNEGIE MELLON AND OMRON ALLOW FREE USE OF THIS SOFTWARE IN ITS "AS IS"
* CONDITION. CARNEGIE MELLON AND OMRON DISCLAIM ANY LIABILITY OF ANY KIND
* FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
*
* Carnegie Mellon requests users of this software to return to
*
* Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
* School of Computer Science
* Carnegie Mellon University
* Pittsburgh PA 15213-3890
*
* any improvements or extensions that they make and grant Carnegie the
* rights to redistribute these changes.
*/
#include "assym.h"
#include <sys/param.h>
#include <sys/types.h>
#include <sys/systm.h>
#include <machine/board.h> /* m188 bit defines */
#include <machine/cmmu.h> /* DMT_VALID */
#include <machine/asm.h> /* END_OF_VECTOR_LIST, etc. */
#include <machine/asm_macro.h> /* enable/disable interrupts */
#include <machine/cpu_number.h> /* cpu_number() */
#include <machine/locore.h>
#include <machine/prom.h>
#include <machine/trap.h>
#ifdef M88100
#include <machine/m88100.h>
#endif
#ifdef DDB
#include <ddb/db_output.h>
#endif /* DDB */
#if defined(DDB) && defined(JEFF_DEBUG)
#define DATA_DEBUG
#endif
#if DDB
#define DEBUG_MSG db_printf
#else
#define DEBUG_MSG printf
#endif /* DDB */
typedef struct {
unsigned word_one, word_two;
} m88k_exception_vector_area;
extern unsigned int *volatile int_mask_reg[MAX_CPUS]; /* in machdep.c */
extern unsigned master_cpu; /* in cmmu.c */
/* FORWARDS */
void setlevel(unsigned int);
void vector_init(m88k_exception_vector_area *, unsigned *);
#ifdef M88100
/*
* data access emulation for M88100 exceptions
*/
#define DMT_BYTE 1
#define DMT_HALF 2
#define DMT_WORD 4
const struct {
unsigned char offset;
unsigned char size;
} dmt_en_info[16] = {
{0, 0}, {3, DMT_BYTE}, {2, DMT_BYTE}, {2, DMT_HALF},
{1, DMT_BYTE}, {0, 0}, {0, 0}, {0, 0},
{0, DMT_BYTE}, {0, 0}, {0, 0}, {0, 0},
{0, DMT_HALF}, {0, 0}, {0, 0}, {0, DMT_WORD}
};
#ifdef DATA_DEBUG
int data_access_emulation_debug = 0;
#define DAE_DEBUG(stuff) \
do { \
if (data_access_emulation_debug != 0) { \
stuff; \
} \
} while (0)
#else
#define DAE_DEBUG(stuff)
#endif
void
dae_print(unsigned *eframe)
{
int x;
unsigned dmax, dmdx, dmtx;
if (!ISSET(eframe[EF_DMT0], DMT_VALID))
return;
for (x = 0; x < 3; x++) {
dmtx = eframe[EF_DMT0 + x * 3];
if (!ISSET(dmtx, DMT_VALID))
continue;
dmdx = eframe[EF_DMD0 + x * 3];
dmax = eframe[EF_DMA0 + x * 3];
if (ISSET(dmtx, DMT_WRITE))
printf("[DMT%d=%x: st.%c %x to %x as %d %s %s]\n",
x, dmtx, dmtx & DMT_DAS ? 's' : 'u', dmdx, dmax,
DMT_ENBITS(dmtx),
dmtx & DMT_DOUB1 ? "double": "not double",
dmtx & DMT_LOCKBAR ? "xmem": "not xmem");
else
printf("[DMT%d=%x: ld.%c r%d <- %x as %d %s %s]\n",
x, dmtx, dmtx & DMT_DAS ? 's' : 'u',
DMT_DREGBITS(dmtx), dmax, DMT_ENBITS(dmtx),
dmtx & DMT_DOUB1 ? "double": "not double",
dmtx & DMT_LOCKBAR ? "xmem": "not xmem");
}
}
void
data_access_emulation(unsigned *eframe)
{
int x;
unsigned dmax, dmdx, dmtx;
unsigned v, reg;
dmtx = eframe[EF_DMT0];
if (!ISSET(dmtx, DMT_VALID))
return;
for (x = 0; x < 3; x++) {
dmtx = eframe[EF_DMT0 + x * 3];
if (!ISSET(dmtx, DMT_VALID) || ISSET(dmtx, DMT_SKIP))
continue;
dmdx = eframe[EF_DMD0 + x * 3];
dmax = eframe[EF_DMA0 + x * 3];
DAE_DEBUG(
if (ISSET(dmtx, DMT_WRITE))
printf("[DMT%d=%x: st.%c %x to %x as %d %s %s]\n",
x, dmtx, dmtx & DMT_DAS ? 's' : 'u', dmdx, dmax,
DMT_ENBITS(dmtx),
dmtx & DMT_DOUB1 ? "double": "not double",
dmtx & DMT_LOCKBAR ? "xmem": "not xmem");
else
printf("[DMT%d=%x: ld.%c r%d <- %x as %d %s %s]\n",
x, dmtx, dmtx & DMT_DAS ? 's' : 'u',
DMT_DREGBITS(dmtx), dmax, DMT_ENBITS(dmtx),
dmtx & DMT_DOUB1 ? "double": "not double",
dmtx & DMT_LOCKBAR ? "xmem": "not xmem")
);
dmax += dmt_en_info[DMT_ENBITS(dmtx)].offset;
reg = DMT_DREGBITS(dmtx);
if (!ISSET(dmtx, DMT_LOCKBAR)) {
/* the fault is not during an XMEM */
if (x == 2 && ISSET(dmtx, DMT_DOUB1)) {
/* pipeline 2 (earliest stage) for a double */
if (ISSET(dmtx, DMT_WRITE)) {
/*
* STORE DOUBLE WILL BE REINITIATED
* BY rte
*/
} else {
/* EMULATE ld.d INSTRUCTION */
v = do_load_word(dmax, dmtx & DMT_DAS);
if (reg != 0)
eframe[EF_R0 + reg] = v;
v = do_load_word(dmax ^ 4,
dmtx & DMT_DAS);
if (reg != 31)
eframe[EF_R0 + reg + 1] = v;
}
} else {
/* not pipeline #2 with a double */
if (dmtx & DMT_WRITE) {
switch (dmt_en_info[DMT_ENBITS(dmtx)].size) {
case DMT_BYTE:
DAE_DEBUG(
DEBUG_MSG("[byte %x -> [%x(%c)]\n",
dmdx & 0xff, dmax,
ISSET(dmtx, DMT_DAS) ? 's' : 'u')
);
do_store_byte(dmax, dmdx,
dmtx & DMT_DAS);
break;
case DMT_HALF:
DAE_DEBUG(
DEBUG_MSG("[half %x -> [%x(%c)]\n",
dmdx & 0xffff, dmax,
ISSET(dmtx, DMT_DAS) ? 's' : 'u')
);
do_store_half(dmax, dmdx,
dmtx & DMT_DAS);
break;
case DMT_WORD:
DAE_DEBUG(
DEBUG_MSG("[word %x -> [%x(%c)]\n",
dmdx, dmax,
ISSET(dmtx, DMT_DAS) ? 's' : 'u')
);
do_store_word(dmax, dmdx,
dmtx & DMT_DAS);
break;
}
} else {
/* else it's a read */
switch (dmt_en_info[DMT_ENBITS(dmtx)].size) {
case DMT_BYTE:
v = do_load_byte(dmax,
dmtx & DMT_DAS);
if (!ISSET(dmtx, DMT_SIGNED))
v &= 0x000000ff;
break;
case DMT_HALF:
v = do_load_half(dmax,
dmtx & DMT_DAS);
if (!ISSET(dmtx, DMT_SIGNED))
v &= 0x0000ffff;
break;
case DMT_WORD:
v = do_load_word(dmax,
dmtx & DMT_DAS);
break;
}
DAE_DEBUG(
if (reg == 0)
DEBUG_MSG("[no write to r0 done]\n");
else
DEBUG_MSG("[r%d <- %x]\n", reg, v);
);
if (reg != 0)
eframe[EF_R0 + reg] = v;
}
}
} else {
/* if lockbar is set... it's part of an XMEM */
/*
* According to Motorola's "General Information",
* the DMT_DOUB1 bit is never set in this case, as it
* should be.
* If lockbar is set (as it is if we're here) and if
* the write is not set, then it's the same as if DOUB1
* was set...
*/
if (!ISSET(dmtx, DMT_WRITE)) {
if (x != 2) {
/* RERUN xmem WITH DMD(x+1) */
x++;
dmdx = eframe[EF_DMD0 + x * 3];
} else {
/* RERUN xmem WITH DMD2 */
}
if (dmt_en_info[DMT_ENBITS(dmtx)].size ==
DMT_WORD) {
v = do_xmem_word(dmax, dmdx,
dmtx & DMT_DAS);
} else {
v = do_xmem_byte(dmax, dmdx,
dmtx & DMT_DAS);
}
if (reg != 0)
eframe[EF_R0 + reg] = v;
} else {
if (x == 0) {
if (reg != 0)
eframe[EF_R0 + reg] = dmdx;
eframe[EF_SFIP] = eframe[EF_SNIP];
eframe[EF_SNIP] = eframe[EF_SXIP];
eframe[EF_SXIP] = 0;
/* xmem RERUN ON rte */
eframe[EF_DMT0] = 0;
return;
}
}
}
}
eframe[EF_DMT0] = 0;
}
#endif /* M88100 */
#define SIGSYS_MAX 501
#define SIGTRAP_MAX 510
#define EMPTY_BR 0xc0000000 /* empty "br" instruction */
#define NO_OP 0xf4005800 /* "or r0, r0, r0" */
#define BRANCH(FROM, TO) \
(EMPTY_BR | ((unsigned)(TO) - (unsigned)(FROM)) >> 2)
#define SET_VECTOR(NUM, VALUE) \
do { \
vector[NUM].word_one = NO_OP; \
vector[NUM].word_two = BRANCH(&vector[NUM].word_two, VALUE); \
} while (0)
/*
* vector_init(vector, vector_init_list)
*
* This routine sets up the m88k vector table for the running processor.
* It is called with a very little stack, and interrupts disabled,
* so don't call any other functions!
* XXX clean this - nivas
*/
void
vector_init(m88k_exception_vector_area *vector, unsigned *vector_init_list)
{
unsigned num;
unsigned vec;
extern void bugtrap(void);
extern void m88110_bugtrap(void);
for (num = 0; (vec = vector_init_list[num]) != END_OF_VECTOR_LIST;
num++) {
if (vec != UNKNOWN_HANDLER)
SET_VECTOR(num, vec);
}
/* Save BUG vector */
bugvec[0] = vector[MVMEPROM_VECTOR].word_one;
bugvec[1] = vector[MVMEPROM_VECTOR].word_two;
switch (cputyp) {
#ifdef M88110
case CPU_88110:
for (; num <= SIGSYS_MAX; num++)
SET_VECTOR(num, m88110_sigsys);
for (; num <= SIGTRAP_MAX; num++)
SET_VECTOR(num, m88110_sigtrap);
SET_VECTOR(450, m88110_syscall_handler);
SET_VECTOR(MVMEPROM_VECTOR, m88110_bugtrap);
SET_VECTOR(504, m88110_stepbpt);
SET_VECTOR(511, m88110_userbpt);
break;
#endif /* M88110 */
#ifdef M88100
case CPU_88100:
for (; num <= SIGSYS_MAX; num++)
SET_VECTOR(num, sigsys);
for (; num <= SIGTRAP_MAX; num++)
SET_VECTOR(num, sigtrap);
SET_VECTOR(450, syscall_handler);
SET_VECTOR(MVMEPROM_VECTOR, bugtrap);
SET_VECTOR(504, stepbpt);
SET_VECTOR(511, userbpt);
break;
#endif /* M88100 */
}
/* GCC will by default produce explicit trap 503 for division by zero */
SET_VECTOR(503, vector_init_list[T_ZERODIV]);
/* Save new BUG vector */
sysbugvec[0] = vector[MVMEPROM_VECTOR].word_one;
sysbugvec[1] = vector[MVMEPROM_VECTOR].word_two;
}
#ifdef MVME188
#if 0
unsigned int int_mask_shadow[MAX_CPUS] = {0, 0, 0, 0};
unsigned int blocked_interrupts_mask;
#endif
unsigned int m188_curspl[MAX_CPUS] = {0, 0, 0, 0};
unsigned int int_mask_val[INT_LEVEL] = {
MASK_LVL_0,
MASK_LVL_1,
MASK_LVL_2,
MASK_LVL_3,
MASK_LVL_4,
MASK_LVL_5,
MASK_LVL_6,
MASK_LVL_7
};
/*
* return next safe spl to reenable interrupts.
*/
unsigned int
safe_level(mask, curlevel)
unsigned mask;
unsigned curlevel;
{
int i;
for (i = curlevel; i < 8; i++)
if (!(int_mask_val[i] & mask))
return i;
panic("safe_level: no safe level for mask 0x%08x level %d found",
mask, curlevel);
/* NOTREACHED */
}
void
setlevel(unsigned int level)
{
unsigned int mask;
int cpu = cpu_number();
mask = int_mask_val[level];
if (cpu != master_cpu)
mask &= SLAVE_MASK;
#if 0
mask &= ISR_SOFTINT_EXCEPT_MASK(cpu);
mask &= ~blocked_interrupts_mask;
#endif
*int_mask_reg[cpu] = mask;
#if 0
int_mask_shadow[cpu] = mask;
#endif
m188_curspl[cpu] = level;
}
#endif /* MVME188 */
unsigned
getipl(void)
{
unsigned curspl;
m88k_psr_type psr; /* processor status register */
psr = disable_interrupts_return_psr();
switch (brdtyp) {
#ifdef MVME188
case BRD_188:
curspl = m188_curspl[cpu_number()];
break;
#endif /* MVME188 */
#if defined(MVME187) || defined(MVME197)
case BRD_187:
case BRD_8120:
case BRD_197:
curspl = *md.intr_mask & 0x07;
break;
#endif /* defined(MVME187) || defined(MVME197) */
}
set_psr(psr);
return curspl;
}
unsigned
setipl(unsigned level)
{
unsigned curspl;
m88k_psr_type psr; /* processor status register */
#ifdef DEBUG
if (level > 7) {
printf("setipl: invoked with invalid level %x\n", level);
level &= 0x07; /* and pray it will work */
}
#endif
psr = disable_interrupts_return_psr();
switch (brdtyp) {
#ifdef MVME188
case BRD_188:
curspl = m188_curspl[cpu_number()];
setlevel(level);
break;
#endif /* MVME188 */
#if defined(MVME187) || defined(MVME197)
case BRD_187:
case BRD_8120:
case BRD_197:
curspl = *md.intr_mask & 0x07;
*md.intr_mask = level;
break;
#endif /* defined(MVME187) || defined(MVME197) */
}
flush_pipeline();
/* The flush pipeline is required to make sure the above write gets
* through the data pipe and to the hardware; otherwise, the next
* bunch of instructions could execute at the wrong spl protection
*/
set_psr(psr);
return curspl;
}
unsigned
raiseipl(unsigned level)
{
unsigned curspl;
m88k_psr_type psr; /* processor status register */
#ifdef DEBUG
if (level > 7) {
printf("raiseipl: invoked with invalid level %x\n", level);
level &= 0x07; /* and pray it will work */
}
#endif
psr = disable_interrupts_return_psr();
switch (brdtyp) {
#ifdef MVME188
case BRD_188:
curspl = m188_curspl[cpu_number()];
if (curspl < level)
setlevel(level);
break;
#endif /* MVME188 */
#if defined(MVME187) || defined(MVME197)
case BRD_187:
case BRD_8120:
case BRD_197:
curspl = *md.intr_mask & 0x07;
if (curspl < level)
*md.intr_mask = level;
break;
#endif /* defined(MVME187) || defined(MVME197) */
}
flush_pipeline();
/* The flush pipeline is required to make sure the above write gets
* through the data pipe and to the hardware; otherwise, the next
* bunch of instructions could execute at the wrong spl protection
*/
set_psr(psr);
return curspl;
}
/* XXX Utterly bogus */
#if NCPUS > 1
#include <sys/simplelock.h>
void
simple_lock_init(lkp)
struct simplelock *volatile lkp;
{
lkp->lock_data = 0;
}
int
test_and_set(lock)
int *volatile lock;
{
#if 0
int oldlock = *lock;
if (*lock == 0) {
*lock = 1;
return 0;
}
#else
return *lock;
*lock = 1;
return 0;
#endif
}
#endif
| 23.135972 | 75 | 0.632793 | [
"vector"
] |
2cd601ed830ad7c919b69b77b2d4c60cfd0b9725 | 4,034 | h | C | vips.h | felixonmars/imgproxy | 2a45d435d9b38a30f1a551141f93970778b9d371 | [
"MIT"
] | null | null | null | vips.h | felixonmars/imgproxy | 2a45d435d9b38a30f1a551141f93970778b9d371 | [
"MIT"
] | 84 | 2021-05-10T08:46:44.000Z | 2022-03-28T07:06:43.000Z | vips.h | felixonmars/imgproxy | 2a45d435d9b38a30f1a551141f93970778b9d371 | [
"MIT"
] | null | null | null | #include <stdlib.h>
#include <vips/vips.h>
#include <vips/vips7compat.h>
#include <vips/vector.h>
enum ImgproxyImageTypes {
UNKNOWN = 0,
JPEG,
PNG,
WEBP,
GIF,
ICO,
SVG,
HEIC,
AVIF,
BMP,
TIFF
};
int vips_initialize();
void clear_image(VipsImage **in);
void g_free_go(void **buf);
void swap_and_clear(VipsImage **in, VipsImage *out);
int vips_type_find_load_go(int imgtype);
int vips_type_find_save_go(int imgtype);
int vips_jpegload_go(void *buf, size_t len, int shrink, VipsImage **out);
int vips_pngload_go(void *buf, size_t len, VipsImage **out);
int vips_webpload_go(void *buf, size_t len, double scale, int pages, VipsImage **out);
int vips_gifload_go(void *buf, size_t len, int pages, VipsImage **out);
int vips_svgload_go(void *buf, size_t len, double scale, VipsImage **out);
int vips_heifload_go(void *buf, size_t len, VipsImage **out);
int vips_bmpload_go(void *buf, size_t len, VipsImage **out);
int vips_tiffload_go(void *buf, size_t len, VipsImage **out);
int vips_get_orientation(VipsImage *image);
void vips_strip_meta(VipsImage *image);
int vips_support_smartcrop();
VipsBandFormat vips_band_format(VipsImage *in);
gboolean vips_support_webp_animation();
gboolean vips_is_animated(VipsImage * in);
int vips_image_get_array_int_go(VipsImage *image, const char *name, int **out, int *n);
void vips_image_set_array_int_go(VipsImage *image, const char *name, const int *array, int n);
gboolean vips_image_hasalpha_go(VipsImage * in);
int vips_addalpha_go(VipsImage *in, VipsImage **out);
int vips_copy_go(VipsImage *in, VipsImage **out);
int vips_cast_go(VipsImage *in, VipsImage **out, VipsBandFormat format);
int vips_rad2float_go(VipsImage *in, VipsImage **out);
int vips_resize_go(VipsImage *in, VipsImage **out, double scale);
int vips_resize_with_premultiply(VipsImage *in, VipsImage **out, double scale);
int vips_icc_is_srgb_iec61966(VipsImage *in);
int vips_has_embedded_icc(VipsImage *in);
int vips_icc_import_go(VipsImage *in, VipsImage **out);
int vips_icc_export_go(VipsImage *in, VipsImage **out);
int vips_icc_export_srgb(VipsImage *in, VipsImage **out);
int vips_icc_transform_go(VipsImage *in, VipsImage **out);
int vips_icc_remove(VipsImage *in, VipsImage **out);
int vips_colourspace_go(VipsImage *in, VipsImage **out, VipsInterpretation cs);
int vips_rot_go(VipsImage *in, VipsImage **out, VipsAngle angle);
int vips_flip_horizontal_go(VipsImage *in, VipsImage **out);
int vips_extract_area_go(VipsImage *in, VipsImage **out, int left, int top, int width, int height);
int vips_smartcrop_go(VipsImage *in, VipsImage **out, int width, int height);
int vips_trim(VipsImage *in, VipsImage **out, double threshold,
gboolean smart, double r, double g, double b,
gboolean equal_hor, gboolean equal_ver);
int vips_gaussblur_go(VipsImage *in, VipsImage **out, double sigma);
int vips_sharpen_go(VipsImage *in, VipsImage **out, double sigma);
int vips_flatten_go(VipsImage *in, VipsImage **out, double r, double g, double b);
int vips_replicate_go(VipsImage *in, VipsImage **out, int across, int down);
int vips_embed_go(VipsImage *in, VipsImage **out, int x, int y, int width, int height, double *bg, int bgn);
int vips_ensure_alpha(VipsImage *in, VipsImage **out);
int vips_apply_watermark(VipsImage *in, VipsImage *watermark, VipsImage **out, double opacity);
int vips_arrayjoin_go(VipsImage **in, VipsImage **out, int n);
int vips_strip(VipsImage *in, VipsImage **out);
int vips_jpegsave_go(VipsImage *in, void **buf, size_t *len, int quality, int interlace);
int vips_pngsave_go(VipsImage *in, void **buf, size_t *len, int interlace, int quantize, int colors);
int vips_webpsave_go(VipsImage *in, void **buf, size_t *len, int quality);
int vips_gifsave_go(VipsImage *in, void **buf, size_t *len);
int vips_avifsave_go(VipsImage *in, void **buf, size_t *len, int quality);
int vips_bmpsave_go(VipsImage *in, void **buf, size_t *len);
int vips_tiffsave_go(VipsImage *in, void **buf, size_t *len, int quality);
void vips_cleanup();
| 37.700935 | 108 | 0.758057 | [
"vector"
] |
2cd60cb057ad09706c4a140daa42319ea461af9f | 1,075 | h | C | src/ofxTitleBar.h | patriciogonzalezvivo/ofxComposer | 3473ffd78956fcb27286360b4e792eb66a5c7f07 | [
"MIT"
] | 20 | 2015-07-12T08:12:16.000Z | 2021-12-16T16:02:26.000Z | src/ofxTitleBar.h | pabloriera/ofxComposer | ecf86aad120b5848909d50601a1d5b40acbadf60 | [
"MIT"
] | 2 | 2016-05-28T15:50:44.000Z | 2018-01-08T05:58:47.000Z | src/ofxTitleBar.h | patriciogonzalezvivo/ofxComposer | 3473ffd78956fcb27286360b4e792eb66a5c7f07 | [
"MIT"
] | 6 | 2015-06-08T00:15:45.000Z | 2017-05-18T04:49:03.000Z | //
// ofxTitleBar.h
// GPUBurner
//
// Created by Patricio Gonzalez Vivo on 3/9/12.
// Copyright (c) 2012 http://www.PatricioGonzalezVivo.com All rights reserved.
//
#ifndef OFXTITLEBAR
#define OFXTITLEBAR
#include "ofMain.h"
enum ButtonType {
TOGGLE_BUTTON,
PUSH_BUTTON
};
struct ofxTitleBarButton{
char letter;
bool *state;
ButtonType type;
};
class ofxTitleBar {
public:
ofxTitleBar( ofRectangle* wBox, int* _windowsId );
void setTitle(string _title){ title = _title; };
void addButton( char letter, bool *variableToControl, ButtonType _type);
void draw();
ofEvent<int> close;
ofEvent<int> reset;
ofEvent<int> drag;
private:
void _mousePressed(ofMouseEventArgs &e);
void _mouseReleased(ofMouseEventArgs &e);
ofRectangle tittleBox;
ofRectangle *windowsBox;
string title;
vector<ofxTitleBarButton> buttons;
int *windowsId;
int letterWidth, letterHeight, offSetWidth;
int height;
};
#endif
| 19.196429 | 79 | 0.63907 | [
"vector"
] |
2cde2632799f6a780a3e40ec748160badc00a82a | 1,282 | h | C | include/util/stats.h | ShufengGong/piccolo | 112c56876ba8449836e40da466f657318398f56d | [
"Apache-2.0"
] | 5 | 2015-03-30T14:32:22.000Z | 2021-01-26T07:53:51.000Z | include/util/stats.h | ShufengGong/piccolo | 112c56876ba8449836e40da466f657318398f56d | [
"Apache-2.0"
] | 1 | 2020-07-28T10:13:10.000Z | 2020-07-28T10:13:10.000Z | include/util/stats.h | ShufengGong/piccolo | 112c56876ba8449836e40da466f657318398f56d | [
"Apache-2.0"
] | 2 | 2015-07-01T10:33:26.000Z | 2020-07-16T01:08:13.000Z | #ifndef UTIL_STATS_H_
#define UTIL_STATS_H_
#include <string>
#include <map>
#include <vector>
namespace piccolo {
// Simple wrapper around a string->double map.
struct Stats {
double& operator[](const std::string& key);
std::string ToString(std::string prefix);
void Merge(Stats &other);
private:
std::map<std::string, double> p_;
};
inline double& Stats::operator[](const std::string& key) {
return p_[key];
}
inline std::string Stats::ToString(std::string prefix) {
std::string out;
for (std::map<std::string, double>::iterator i = p_.begin(); i != p_.end();
++i) {
out += StringPrintf("%s -- %s : %.2f\n", prefix.c_str(), i->first.c_str(),
i->second);
}
return out;
}
inline void Stats::Merge(Stats &other) {
for (std::map<std::string, double>::iterator i = other.p_.begin();
i != other.p_.end(); ++i) {
p_[i->first] += i->second;
}
}
// Log-bucketed histogram.
class Histogram {
public:
Histogram() :
count(0) {
}
void add(double val);
std::string summary();
int bucketForVal(double v);
double valForBucket(int b);
int getCount() {
return count;
}
private:
int count;
std::vector<int> buckets;
static const double kMinVal;
static const double kLogBase;
};
}
#endif /* STATS_H_ */
| 19.134328 | 78 | 0.633385 | [
"vector"
] |
2ce2ec65554c6d46f2d435c66fd84315c50e9288 | 4,499 | h | C | libraries/src/PRT/Ivanic/Maths/VECTOR3D.h | kamarianakis/glGA-edu | 17f0b33c3ea8efcfa8be01d41343862ea4e6fae0 | [
"BSD-4-Clause-UC"
] | 9 | 2015-04-06T14:12:07.000Z | 2020-12-28T05:50:49.000Z | libraries/src/PRT/Ivanic/Maths/VECTOR3D.h | kamarianakis/glGA-edu | 17f0b33c3ea8efcfa8be01d41343862ea4e6fae0 | [
"BSD-4-Clause-UC"
] | 7 | 2020-10-06T16:34:12.000Z | 2020-12-06T17:29:22.000Z | libraries/src/PRT/Ivanic/Maths/VECTOR3D.h | kamarianakis/glGA-edu | 17f0b33c3ea8efcfa8be01d41343862ea4e6fae0 | [
"BSD-4-Clause-UC"
] | 71 | 2015-03-26T10:28:04.000Z | 2021-11-07T10:09:12.000Z | //////////////////////////////////////////////////////////////////////////////////////////
// VECTOR3D.h
// Class declaration for a 3d vector
// Downloaded from: www.paulsprojects.net
// Created: 20th July 2002
// Modified: 8th November 2002 - Changed Constructor layout
// - Some speed Improvements
// - Corrected Lerp
// 7th January 2003 - Added QuadraticInterpolate
//
// Copyright (c) 2006, Paul Baker
// Distributed under the New BSD Licence. (See accompanying file License.txt or copy at
// http://www.paulsprojects.net/NewBSDLicense.txt)
//////////////////////////////////////////////////////////////////////////////////////////
#ifndef VECTOR3D_H
#define VECTOR3D_H
class VECTOR3D
{
public:
//constructors
VECTOR3D(void) : x(0.0f), y(0.0f), z(0.0f)
{}
VECTOR3D(float newX, float newY, float newZ) : x(newX), y(newY), z(newZ)
{}
VECTOR3D(const float * rhs) : x(*rhs), y(*(rhs+1)), z(*(rhs+2))
{}
VECTOR3D(const VECTOR3D & rhs) : x(rhs.x), y(rhs.y), z(rhs.z)
{}
~VECTOR3D() {} //empty
void Set(float newX, float newY, float newZ)
{ x=newX; y=newY; z=newZ; }
//Accessors kept for compatibility
void SetX(float newX) {x = newX;}
void SetY(float newY) {y = newY;}
void SetZ(float newZ) {z = newZ;}
float GetX() const {return x;} //public accessor functions
float GetY() const {return y;} //inline, const
float GetZ() const {return z;}
void LoadZero(void)
{ x=y=z=0.0f; }
void LoadOne(void)
{ x=y=z=1.0f; }
//vector algebra
VECTOR3D CrossProduct(const VECTOR3D & rhs) const
{ return VECTOR3D(y*rhs.z - z*rhs.y, z*rhs.x - x*rhs.z, x*rhs.y - y*rhs.x); }
float DotProduct(const VECTOR3D & rhs) const
{ return x*rhs.x + y*rhs.y + z*rhs.z; }
void Normalize();
VECTOR3D GetNormalized() const;
float GetLength() const
{ return (float)sqrt((x*x)+(y*y)+(z*z)); }
float GetSquaredLength() const
{ return (x*x)+(y*y)+(z*z); }
//rotations
void RotateX(double angle);
VECTOR3D GetRotatedX(double angle) const;
void RotateY(double angle);
VECTOR3D GetRotatedY(double angle) const;
void RotateZ(double angle);
VECTOR3D GetRotatedZ(double angle) const;
void RotateAxis(double angle, const VECTOR3D & axis);
VECTOR3D GetRotatedAxis(double angle, const VECTOR3D & axis) const;
//pack to [0,1] for color
void PackTo01();
VECTOR3D GetPackedTo01() const;
//linear interpolate
VECTOR3D lerp(const VECTOR3D & v2, float factor) const
{ return (*this)*(1.0f-factor) + v2*factor; }
VECTOR3D QuadraticInterpolate(const VECTOR3D & v2, const VECTOR3D & v3, float factor) const
{ return (*this)*(1.0f-factor)*(1.0f-factor) + 2*v2*factor*(1.0f-factor) + v3*factor*factor;}
//overloaded operators
//binary operators
VECTOR3D operator+(const VECTOR3D & rhs) const
{ return VECTOR3D(x + rhs.x, y + rhs.y, z + rhs.z); }
VECTOR3D operator-(const VECTOR3D & rhs) const
{ return VECTOR3D(x - rhs.x, y - rhs.y, z - rhs.z); }
VECTOR3D operator*(const float rhs) const
{ return VECTOR3D(x*rhs, y*rhs, z*rhs); }
VECTOR3D operator/(const float rhs) const
{ return (rhs==0.0f) ? VECTOR3D(0.0f, 0.0f, 0.0f) : VECTOR3D(x / rhs, y / rhs, z / rhs); }
//multiply by a float, eg 3*v
friend VECTOR3D operator*(float scaleFactor, const VECTOR3D & rhs);
//Add, subtract etc, saving the construction of a temporary
void Add(const VECTOR3D & v2, VECTOR3D & result)
{
result.x=x+v2.x;
result.y=y+v2.y;
result.z=z+v2.z;
}
void Subtract(const VECTOR3D & v2, VECTOR3D & result)
{
result.x=x-v2.x;
result.y=y-v2.y;
result.z=z-v2.z;
}
bool operator==(const VECTOR3D & rhs) const;
bool operator!=(const VECTOR3D & rhs) const
{ return !((*this)==rhs); }
//self-add etc
void operator+=(const VECTOR3D & rhs)
{ x+=rhs.x; y+=rhs.y; z+=rhs.z; }
void operator-=(const VECTOR3D & rhs)
{ x-=rhs.x; y-=rhs.y; z-=rhs.z; }
void operator*=(const float rhs)
{ x*=rhs; y*=rhs; z*=rhs; }
void operator/=(const float rhs)
{ if(rhs==0.0f)
return;
else
{ x/=rhs; y/=rhs; z/=rhs; }
}
//unary operators
VECTOR3D operator-(void) const {return VECTOR3D(-x, -y, -z);}
VECTOR3D operator+(void) const {return *this;}
//cast to pointer to a (float *) for glVertex3fv etc
operator float* () const {return (float*) this;}
operator const float* () const {return (const float*) this;}
//member variables
float x;
float y;
float z;
};
#endif //VECTOR3D_H | 28.11875 | 95 | 0.614581 | [
"vector",
"3d"
] |
2ce673bd850e33f9fb3f363e687ddae0b9e94778 | 2,745 | h | C | AnimalCooking/MapState.h | TenByTen-Studios/AnimalCooking | 8bb22f426cdc819cefde16caa23d8eb045276be8 | [
"MIT"
] | null | null | null | AnimalCooking/MapState.h | TenByTen-Studios/AnimalCooking | 8bb22f426cdc819cefde16caa23d8eb045276be8 | [
"MIT"
] | 23 | 2020-03-02T16:43:28.000Z | 2020-04-16T09:58:08.000Z | AnimalCooking/MapState.h | TenByTen-Studios/AnimalCooking | 8bb22f426cdc819cefde16caa23d8eb045276be8 | [
"MIT"
] | null | null | null | #pragma once
#include "State.h"
#include "Entity.h"
#include <vector>
#include "NameAsker.h"
#include "MapInfoBoxViewer.h"
#include "ButtonPadNavigation.h"
#include "ButtonRendererHouse.h"
class MapState :public State {
public:
MapState(AnimalCooking* ac);
~MapState();
static void screenLoaderCallback(AnimalCooking* ac);
static void backButtonCallback(AnimalCooking* ac);
static void newGameCallback(AnimalCooking* ac);
static void loadGameCallback(AnimalCooking* ac);
static void nextScreenCallBack(AnimalCooking* ac);
static void previousScreenCallBack(AnimalCooking* ac);
void draw() override;
void update() override;
void chooseOption();
void askName();
void init();
void setState();
void hideChooseButtons();
void prepareNavPadFewProfiles(bool many);
void askProfile();
void removeProfile(const string& name);
void transitionEnd();
inline void setName(const string& n) { playerName_ = n; game_->setName(n); }
inline void setCurrentLevel(int nl) {
currentLevel_ = nl;
GETCMP2(playButton_, ButtonRendererHouse)->setLevel(levelinfos_->at(nl));
}
void nextScreen();
void previousScreen();
inline int getCurrentLevel() { return currentLevel_; }
inline void isNewGame() { isNewGame_ = true; }
inline void isNotNewGame() { isNewGame_ = false; }
inline bool isCurrentLevelUnlocked() { return levelinfos_->at(currentLevel_)->unlocked; }
void notEnoughStarsWarning();
void setActiveInfoBox(bool b);
private:
void configPadNavigation();
void placeHousesAndButtons();
void refreshHousesAndButtons();
SDLGame* game_;
Entity* newGameButton_;
Entity* loadGameButton_;
Entity* infoBox_;
Entity* playButton_;
Entity* nextScreenButton_;
Entity* PreviousScreenButton_;
Entity* returnButton_;
Entity* chooser;
Entity* nameAsker;
Entity* exit;
vector <Entity*> profileAskers;
vector <Texture*> profileTextures;
vector <Entity*> levelButtonsPool_;
vector<levelInfo*>* levelinfos_;
Entity* pad;
ButtonPadNavigation* padNavigation_;
vector<Texture*> bgText_;
Texture* playButtonText_;
std::string playerName_;
Texture* starScore_;
Texture* starScoreBackground_;
Texture* totalStars_;
Texture* panelStars_;
SDL_Rect starScoreRect_;
SDL_Rect starPanelRect_;
SDL_Rect totalStarsRect_;
SDL_Rect totalStarsRectAux_;
SDL_Rect starScoreBackGroundRect_;
Uint32 auxTime_;
bool starsWarningActive_;
bool phase_;
jute::jValue& jsonGeneral;
double casillaX;
double casillaY;
int currentLevel_;
int lastLevel_;
int maxLevels_;
int levelPacks_;
bool hasToBreak = false;
bool isNewGame_ = true;
bool gameStarted = false;
bool inMap = false;
bool transition_ = false;
int xTransition_ = 0;
float transitionVelocity_ = 40;
int transitionDirection_ = 0;
int currentMapScene_ = 0;
};
| 25.654206 | 90 | 0.769035 | [
"vector"
] |
2ceac1f5c1bd8741443b6e57a8d7cf8f85737d66 | 783 | h | C | tools/bytecode-debugger/InjectDebug.h | penguin-wwy/redex | 31baadec7ccddcadb5ddaf4947a63112f2eadc04 | [
"MIT"
] | null | null | null | tools/bytecode-debugger/InjectDebug.h | penguin-wwy/redex | 31baadec7ccddcadb5ddaf4947a63112f2eadc04 | [
"MIT"
] | null | null | null | tools/bytecode-debugger/InjectDebug.h | penguin-wwy/redex | 31baadec7ccddcadb5ddaf4947a63112f2eadc04 | [
"MIT"
] | null | null | null | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <vector>
#include "DexLoader.h"
/* Class used to inject debug information into a dex file.
*
* Uses Redex libraries to load a dex file into memory and output a new
* dex file. IODI will be used to add the required debug info items into the
* dex file.
*/
class InjectDebug {
public:
InjectDebug(const std::string& outdir,
const std::vector<std::string>& dex_files);
~InjectDebug();
void run();
private:
const ConfigFiles m_conf;
const std::vector<std::string> m_dex_files;
DexStore m_store;
void load_dex();
void write_dex();
};
| 21.75 | 76 | 0.696041 | [
"vector"
] |
2cec08b7ce335660dc63b477a038a0a2054ceafb | 1,497 | h | C | project2D/SeekFleeEntity.h | Jeffrey-W23/AIE-CodeFolio | c1820d0a228a6111011b2d10daf885753e6d302d | [
"MIT"
] | null | null | null | project2D/SeekFleeEntity.h | Jeffrey-W23/AIE-CodeFolio | c1820d0a228a6111011b2d10daf885753e6d302d | [
"MIT"
] | null | null | null | project2D/SeekFleeEntity.h | Jeffrey-W23/AIE-CodeFolio | c1820d0a228a6111011b2d10daf885753e6d302d | [
"MIT"
] | null | null | null | // #include, using, etc
#pragma once
#include "Entity.h"
//--------------------------------------------------------------------------------------
// SeekFleeEntity object. Inheritance from Entity.
//--------------------------------------------------------------------------------------
class SeekFleeEntity : public Entity
{
public:
//--------------------------------------------------------------------------------------
// Default Constructor.
//--------------------------------------------------------------------------------------
SeekFleeEntity();
//--------------------------------------------------------------------------------------
// Default Destructor
//--------------------------------------------------------------------------------------
~SeekFleeEntity();
//--------------------------------------------------------------------------------------
// Update: A function to update objects.
//
// Param:
// deltaTime: Pass in deltaTime. A number that updates per second.
//--------------------------------------------------------------------------------------
void Update(float deltaTime);
//--------------------------------------------------------------------------------------
// Draw: A function to render (or "draw") objects to the screen.
//
// Param:
// renderer2D: a pointer to Renderer2D for rendering objects to screen.
//--------------------------------------------------------------------------------------
void Draw(Renderer2D* m_2dRenderer);
}; | 40.459459 | 89 | 0.285237 | [
"render",
"object"
] |
2ceead70e0b4e5bb6ab453d2fb831e3b47c72fc4 | 6,127 | c | C | src/cache_invalidate.c | faizol/timescaledb | 9b91665162df58e8fe40ca80ad269eed3fe328b2 | [
"Apache-2.0"
] | 1 | 2018-11-02T18:17:33.000Z | 2018-11-02T18:17:33.000Z | src/cache_invalidate.c | faizol/timescaledb | 9b91665162df58e8fe40ca80ad269eed3fe328b2 | [
"Apache-2.0"
] | 4 | 2018-07-26T14:09:47.000Z | 2019-02-04T21:57:24.000Z | src/cache_invalidate.c | faizol/timescaledb | 9b91665162df58e8fe40ca80ad269eed3fe328b2 | [
"Apache-2.0"
] | 1 | 2019-03-15T18:11:32.000Z | 2019-03-15T18:11:32.000Z | /*
* This file and its contents are licensed under the Apache License 2.0.
* Please see the included NOTICE for copyright information and
* LICENSE-APACHE for a copy of the license.
*/
#include <postgres.h>
#include <access/xact.h>
#include <utils/lsyscache.h>
#include <utils/inval.h>
#include <catalog/namespace.h>
#include <nodes/nodes.h>
#include <miscadmin.h>
#include <utils/syscache.h>
#include "annotations.h"
#include "ts_catalog/catalog.h"
#include "compat/compat.h"
#include "extension.h"
#include "hypertable_cache.h"
#include "bgw/scheduler.h"
#include "cross_module_fn.h"
#include "cache_invalidate.h"
/*
* Notes on the way cache invalidation works.
*
* Since our caches are stored in per-process (per-backend memory), we need a
* way to signal all backends that they should invalidate their caches. For this
* we use the PostgreSQL relcache mechanism that propagates relation cache
* invalidation events to all backends. We register a callback with this
* mechanism to receive events on all backends whenever a relation cache entry
* is invalidated.
*
* To know which events should trigger invalidation of our caches, we use dummy
* (empty) tables. We can trigger relcache invalidation events for these tables
* to signal other backends. If the received table OID is a dummy table, we know
* that this is an event that we care about.
*
* Caches for catalog tables should be invalidated on:
*
* 1. INSERT/UPDATE/DELETE on a catalog table
* 2. Aborted transactions that taint the caches
*
* Generally, INSERTS do not warrant cache invalidation, unless it is an insert
* of a subobject that belongs to an object that might already be in the cache
* (e.g., a new dimension of a hypertable), or when replacing an existing entry
* (e.g., when replacing a negative hypertable entry with a positive one). Note,
* also, that INSERTS can taint the cache if the transaction that did the INSERT
* fails. This is why we also need to invalidate caches on transaction failure.
*/
void _cache_invalidate_init(void);
void _cache_invalidate_fini(void);
static inline void
cache_invalidate_relcache_all(void)
{
ts_hypertable_cache_invalidate_callback();
ts_bgw_job_cache_invalidate_callback();
}
static Oid hypertable_proxy_table_oid = InvalidOid;
static Oid bgw_proxy_table_oid = InvalidOid;
void
ts_cache_invalidate_set_proxy_tables(Oid hypertable_proxy_oid, Oid bgw_proxy_oid)
{
hypertable_proxy_table_oid = hypertable_proxy_oid;
bgw_proxy_table_oid = bgw_proxy_oid;
}
/*
* This function is called when any relcache is invalidated.
* Should route the invalidation to the correct cache.
*
* NOTE that the callback should not call any functions that could invoke the
* relcache or syscache to query information during the invalidation. That
* might lead to bad things happening.
*/
static void
cache_invalidate_relcache_callback(Datum arg, Oid relid)
{
if (!OidIsValid(relid))
{
cache_invalidate_relcache_all();
}
else if (ts_extension_is_proxy_table_relid(relid))
{
ts_extension_invalidate();
cache_invalidate_relcache_all();
ts_cache_invalidate_set_proxy_tables(InvalidOid, InvalidOid);
}
else if (relid == hypertable_proxy_table_oid)
{
ts_hypertable_cache_invalidate_callback();
}
else if (relid == bgw_proxy_table_oid)
{
ts_bgw_job_cache_invalidate_callback();
}
}
/* Registration for given cache ids happens in non-TSL code when the extension
* is created.
*
* Cache entries get invalidated when either the foreign server entry or the
* role entry in the PostgreSQL catalog changes.
*
* When the foreign server entry changes, connection paramaters might have
* changed. When the role entry changes, the certificate used for client
* authentication with backend data nodes might no longer be valid.
*/
static void
cache_invalidate_syscache_callback(Datum arg, int cacheid, uint32 hashvalue)
{
Assert(cacheid == FOREIGNSERVEROID || cacheid == AUTHOID);
ts_cm_functions->cache_syscache_invalidate(arg, cacheid, hashvalue);
}
TS_FUNCTION_INFO_V1(ts_timescaledb_invalidate_cache);
/*
* Force a cache invalidation for a catalog table.
*
* This function is used for debugging purposes and triggers a cache
* invalidation.
*
* The first argument should be the catalog table that has changed, warranting a
* cache invalidation.
*/
Datum
ts_timescaledb_invalidate_cache(PG_FUNCTION_ARGS)
{
ts_catalog_invalidate_cache(PG_GETARG_OID(0), CMD_UPDATE);
PG_RETURN_VOID();
}
static void
cache_invalidate_xact_end(XactEvent event, void *arg)
{
switch (event)
{
case XACT_EVENT_ABORT:
case XACT_EVENT_PARALLEL_ABORT:
/*
* Invalidate caches on aborted transactions to purge entries that
* have been added during the transaction and are now no longer
* valid. Note that we need not signal other backends of this
* change since the transaction hasn't been committed and other
* backends cannot have the invalid state.
*/
cache_invalidate_relcache_all();
break;
default:
break;
}
}
static void
cache_invalidate_subxact_end(SubXactEvent event, SubTransactionId mySubid,
SubTransactionId parentSubid, void *arg)
{
switch (event)
{
case SUBXACT_EVENT_ABORT_SUB:
/*
* Invalidate caches on aborted sub transactions. See notes above
* in cache_invalidate_xact_end.
*/
cache_invalidate_relcache_all();
break;
default:
break;
}
}
void
_cache_invalidate_init(void)
{
RegisterXactCallback(cache_invalidate_xact_end, NULL);
RegisterSubXactCallback(cache_invalidate_subxact_end, NULL);
CacheRegisterRelcacheCallback(cache_invalidate_relcache_callback, PointerGetDatum(NULL));
/* Specific syscache callbacks */
CacheRegisterSyscacheCallback(FOREIGNSERVEROID,
cache_invalidate_syscache_callback,
PointerGetDatum(NULL));
CacheRegisterSyscacheCallback(AUTHOID,
cache_invalidate_syscache_callback,
PointerGetDatum(NULL));
}
void
_cache_invalidate_fini(void)
{
UnregisterXactCallback(cache_invalidate_xact_end, NULL);
UnregisterSubXactCallback(cache_invalidate_subxact_end, NULL);
/* No way to unregister relcache callback */
}
| 30.182266 | 90 | 0.773299 | [
"object"
] |
82924636ffeb5dae083ab433d9d2b15b3658dc29 | 169,748 | h | C | components/bt/host/bluedroid/stack/include/stack/btm_api.h | huybk213/audio_ip_idf | 6a3fcdd1cda8e2d0fbff6dfc7013135c18c80bfc | [
"Apache-2.0"
] | null | null | null | components/bt/host/bluedroid/stack/include/stack/btm_api.h | huybk213/audio_ip_idf | 6a3fcdd1cda8e2d0fbff6dfc7013135c18c80bfc | [
"Apache-2.0"
] | null | null | null | components/bt/host/bluedroid/stack/include/stack/btm_api.h | huybk213/audio_ip_idf | 6a3fcdd1cda8e2d0fbff6dfc7013135c18c80bfc | [
"Apache-2.0"
] | null | null | null | /******************************************************************************
*
* Copyright (C) 1999-2012 Broadcom Corporation
*
* 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.
*
******************************************************************************/
/******************************************************************************
*
* This file contains the Bluetooth Manager (BTM) API function external
* definitions.
*
******************************************************************************/
#ifndef BTM_API_H
#define BTM_API_H
#include "common/bt_defs.h"
#include "common/bt_target.h"
#include "stack/hcidefs.h"
#if SDP_INCLUDED == TRUE
#include "stack/sdp_api.h"
#endif
#if SMP_INCLUDED == TRUE
#include "stack/smp_api.h"
#endif
/*****************************************************************************
** DEVICE CONTROL and COMMON
*****************************************************************************/
/*****************************
** Device Control Constants
******************************/
/* Maximum number of bytes allowed for vendor specific command parameters */
#define BTM_MAX_VENDOR_SPECIFIC_LEN HCI_COMMAND_SIZE
/* BTM application return status codes */
enum {
BTM_SUCCESS = 0, /* 0 Command succeeded */
BTM_CMD_STARTED, /* 1 Command started OK. */
BTM_BUSY, /* 2 Device busy with another command */
BTM_NO_RESOURCES, /* 3 No resources to issue command */
BTM_MODE_UNSUPPORTED, /* 4 Request for 1 or more unsupported modes */
BTM_ILLEGAL_VALUE, /* 5 Illegal parameter value */
BTM_WRONG_MODE, /* 6 Device in wrong mode for request */
BTM_UNKNOWN_ADDR, /* 7 Unknown remote BD address */
BTM_DEVICE_TIMEOUT, /* 8 Device timeout */
BTM_BAD_VALUE_RET, /* 9 A bad value was received from HCI */
BTM_ERR_PROCESSING, /* 10 Generic error */
BTM_NOT_AUTHORIZED, /* 11 Authorization failed */
BTM_DEV_RESET, /* 12 Device has been reset */
BTM_CMD_STORED, /* 13 request is stored in control block */
BTM_ILLEGAL_ACTION, /* 14 state machine gets illegal command */
BTM_DELAY_CHECK, /* 15 delay the check on encryption */
BTM_SCO_BAD_LENGTH, /* 16 Bad SCO over HCI data length */
BTM_SUCCESS_NO_SECURITY, /* 17 security passed, no security set */
BTM_FAILED_ON_SECURITY, /* 18 security failed */
BTM_REPEATED_ATTEMPTS, /* 19 repeated attempts for LE security requests */
BTM_MODE4_LEVEL4_NOT_SUPPORTED, /* 20 Secure Connections Only Mode can't be supported */
BTM_PEER_LE_DATA_LEN_UNSUPPORTED, /* 21 peer setting data length is unsupported*/
BTM_CONTROL_LE_DATA_LEN_UNSUPPORTED,/* 22 controller setting data length is unsupported*/
BTM_SET_PRIVACY_SUCCESS, /* 23 enable/disable local privacy success */
BTM_SET_PRIVACY_FAIL, /* 24 enable/disable local privacy failed*/
BTM_SET_STATIC_RAND_ADDR_FAIL, /* 25 Command failed */
BTM_INVALID_STATIC_RAND_ADDR, /* 26 invalid static rand addr */
BTM_SEC_DEV_REC_REMOVED, /* 27 Device record relate to the bd_addr is removed */
};
typedef uint8_t tBTM_STATUS;
#if (defined(BTA_HOST_INTERLEAVE_SEARCH) && BTA_HOST_INTERLEAVE_SEARCH == TRUE)
typedef enum {
BTM_BR_ONE, /*0 First state or BR/EDR scan 1*/
BTM_BLE_ONE, /*1BLE scan 1*/
BTM_BR_TWO, /*2 BR/EDR scan 2*/
BTM_BLE_TWO, /*3 BLE scan 2*/
BTM_FINISH, /*4 End of Interleave Scan, or normal scan*/
BTM_NO_INTERLEAVING /*5 No Interleaving*/
} btm_inq_state;
#endif
/*************************
** Device Control Types
**************************/
#define BTM_DEVICE_ROLE_BR 0x01
#define BTM_DEVICE_ROLE_DUAL 0x02
#define BTM_MAX_DEVICE_ROLE BTM_DEVICE_ROLE_DUAL
typedef UINT8 tBTM_DEVICE_ROLE;
/* Device name of peer (may be truncated to save space in BTM database) */
typedef UINT8 tBTM_BD_NAME[BTM_MAX_REM_BD_NAME_LEN + 1];
/* Structure returned with local version information */
typedef struct {
UINT8 hci_version;
UINT16 hci_revision;
UINT8 lmp_version;
UINT16 manufacturer;
UINT16 lmp_subversion;
} tBTM_VERSION_INFO;
/* Structure returned with Vendor Specific Command complete callback */
typedef struct {
UINT16 opcode;
UINT16 param_len;
UINT8 *p_param_buf;
} tBTM_VSC_CMPL;
#define BTM_VSC_CMPL_DATA_SIZE (BTM_MAX_VENDOR_SPECIFIC_LEN + sizeof(tBTM_VSC_CMPL))
/**************************************************
** Device Control and General Callback Functions
***************************************************/
/* Callback function for when device status changes. Appl must poll for
** what the new state is (BTM_IsDeviceUp). The event occurs whenever the stack
** has detected that the controller status has changed. This asynchronous event
** is enabled/disabled by calling BTM_RegisterForDeviceStatusNotif().
*/
enum {
BTM_DEV_STATUS_UP,
BTM_DEV_STATUS_DOWN,
BTM_DEV_STATUS_CMD_TOUT
};
typedef UINT8 tBTM_DEV_STATUS;
typedef struct {
UINT16 rx_len;
UINT16 tx_len;
}tBTM_LE_SET_PKT_DATA_LENGTH_PARAMS;
typedef struct {
UINT16 min_conn_int;
UINT16 max_conn_int;
UINT16 conn_int;
UINT16 slave_latency;
UINT16 supervision_tout;
}tBTM_LE_UPDATE_CONN_PRAMS;
typedef enum{
BTM_WHITELIST_REMOVE = 0X00,
BTM_WHITELIST_ADD = 0X01,
}tBTM_WL_OPERATION;
typedef void (tBTM_DEV_STATUS_CB) (tBTM_DEV_STATUS status);
/* Callback function for when a vendor specific event occurs. The length and
** array of returned parameter bytes are included. This asynchronous event
** is enabled/disabled by calling BTM_RegisterForVSEvents().
*/
typedef void (tBTM_VS_EVT_CB) (UINT8 len, UINT8 *p);
/* General callback function for notifying an application that a synchronous
** BTM function is complete. The pointer contains the address of any returned data.
*/
typedef void (tBTM_CMPL_CB) (void *p1);
typedef void (tBTM_INQ_DIS_CB) (uint32_t num_dis);
/* VSC callback function for notifying an application that a synchronous
** BTM function is complete. The pointer contains the address of any returned data.
*/
typedef void (tBTM_VSC_CMPL_CB) (tBTM_VSC_CMPL *p1);
/* Callback for apps to check connection and inquiry filters.
** Parameters are the BD Address of remote and the Dev Class of remote.
** If the app returns none zero, the connection or inquiry result will be dropped.
*/
typedef UINT8 (tBTM_FILTER_CB) (BD_ADDR bd_addr, DEV_CLASS dc);
typedef void (tBTM_UPDATE_CONN_PARAM_CBACK) (UINT8 status, BD_ADDR bd_addr, tBTM_LE_UPDATE_CONN_PRAMS *update_conn_params);
typedef void (tBTM_SET_PKT_DATA_LENGTH_CBACK) (UINT8 status, tBTM_LE_SET_PKT_DATA_LENGTH_PARAMS *data_length_params);
typedef void (tBTM_SET_RAND_ADDR_CBACK) (UINT8 status);
typedef void (tBTM_ADD_WHITELIST_CBACK) (UINT8 status, tBTM_WL_OPERATION wl_opration);
typedef void (tBTM_SET_LOCAL_PRIVACY_CBACK) (UINT8 status);
/*****************************************************************************
** DEVICE DISCOVERY - Inquiry, Remote Name, Discovery, Class of Device
*****************************************************************************/
/*******************************
** Device Discovery Constants
********************************/
/* Discoverable modes */
#define BTM_NON_DISCOVERABLE 0
#define BTM_LIMITED_DISCOVERABLE 1
#define BTM_GENERAL_DISCOVERABLE 2
#define BTM_DISCOVERABLE_MASK (BTM_LIMITED_DISCOVERABLE|BTM_GENERAL_DISCOVERABLE)
#define BTM_MAX_DISCOVERABLE BTM_GENERAL_DISCOVERABLE
/* high byte for BLE Discoverable modes */
#define BTM_BLE_NON_DISCOVERABLE 0x0000
#define BTM_BLE_LIMITED_DISCOVERABLE 0x0100
#define BTM_BLE_GENERAL_DISCOVERABLE 0x0200
#define BTM_BLE_MAX_DISCOVERABLE BTM_BLE_GENERAL_DISCOVERABLE
#define BTM_BLE_DISCOVERABLE_MASK (BTM_BLE_NON_DISCOVERABLE|BTM_BLE_LIMITED_DISCOVERABLE|BTM_BLE_GENERAL_DISCOVERABLE)
/* Connectable modes */
#define BTM_NON_CONNECTABLE 0
#define BTM_CONNECTABLE 1
#define BTM_CONNECTABLE_MASK (BTM_NON_CONNECTABLE | BTM_CONNECTABLE)
/* high byte for BLE Connectable modes */
#define BTM_BLE_NON_CONNECTABLE 0x0000
#define BTM_BLE_CONNECTABLE 0x0100
#define BTM_BLE_MAX_CONNECTABLE BTM_BLE_CONNECTABLE
#define BTM_BLE_CONNECTABLE_MASK (BTM_BLE_NON_CONNECTABLE | BTM_BLE_CONNECTABLE)
/* Inquiry modes
* Note: These modes are associated with the inquiry active values (BTM_*ACTIVE) */
#define BTM_INQUIRY_NONE 0
#define BTM_GENERAL_INQUIRY 0x01
#define BTM_LIMITED_INQUIRY 0x02
#define BTM_BR_INQUIRY_MASK (BTM_GENERAL_INQUIRY | BTM_LIMITED_INQUIRY)
/* high byte of inquiry mode for BLE inquiry mode */
#define BTM_BLE_INQUIRY_NONE 0x00
#define BTM_BLE_GENERAL_INQUIRY 0x10
#define BTM_BLE_LIMITED_INQUIRY 0x20
#define BTM_BLE_INQUIRY_MASK (BTM_BLE_GENERAL_INQUIRY|BTM_BLE_LIMITED_INQUIRY)
/* BTM_IsInquiryActive return values (Bit Mask)
* Note: These bit masks are associated with the inquiry modes (BTM_*_INQUIRY) */
#define BTM_INQUIRY_INACTIVE 0x0 /* no inquiry in progress */
#define BTM_GENERAL_INQUIRY_ACTIVE BTM_GENERAL_INQUIRY /* a general inquiry is in progress */
#define BTM_LIMITED_INQUIRY_ACTIVE BTM_LIMITED_INQUIRY /* a limited inquiry is in progress */
#define BTM_PERIODIC_INQUIRY_ACTIVE 0x8 /* a periodic inquiry is active */
#define BTM_SSP_INQUIRY_ACTIVE 0x4 /* SSP is active, so inquiry is disallowed (work around for FW bug) */
#define BTM_LE_GENERAL_INQUIRY_ACTIVE BTM_BLE_GENERAL_INQUIRY /* a general inquiry is in progress */
#define BTM_LE_LIMITED_INQUIRY_ACTIVE BTM_BLE_LIMITED_INQUIRY /* a limited inquiry is in progress */
/* inquiry activity mask */
#define BTM_BR_INQ_ACTIVE_MASK (BTM_GENERAL_INQUIRY_ACTIVE|BTM_LIMITED_INQUIRY_ACTIVE|BTM_PERIODIC_INQUIRY_ACTIVE) /* BR/EDR inquiry activity mask */
#define BTM_BLE_SCAN_ACTIVE_MASK 0x01F0 /* LE scan activity mask */
#define BTM_BLE_INQ_ACTIVE_MASK (BTM_LE_GENERAL_INQUIRY_ACTIVE|BTM_LE_LIMITED_INQUIRY_ACTIVE) /* LE inquiry activity mask*/
#define BTM_INQUIRY_ACTIVE_MASK (BTM_BR_INQ_ACTIVE_MASK | BTM_BLE_INQ_ACTIVE_MASK) /* inquiry activity mask */
/* Define scan types */
#define BTM_SCAN_TYPE_STANDARD 0
#define BTM_SCAN_TYPE_INTERLACED 1 /* 1.2 devices only */
/* Define inquiry results mode */
#define BTM_INQ_RESULT_STANDARD 0
#define BTM_INQ_RESULT_WITH_RSSI 1
#define BTM_INQ_RESULT_EXTENDED 2
#define BTM_INQ_RES_IGNORE_RSSI 0x7f /* RSSI value not supplied (ignore it) */
/* Inquiry Filter Condition types (see tBTM_INQ_PARMS) */
#define BTM_CLR_INQUIRY_FILTER 0 /* Inquiry Filtering is turned off */
#define BTM_FILTER_COND_DEVICE_CLASS HCI_FILTER_COND_DEVICE_CLASS /* Filter on device class */
#define BTM_FILTER_COND_BD_ADDR HCI_FILTER_COND_BD_ADDR /* Filter on device addr */
/* State of the remote name retrieval during inquiry operations.
** Used in the tBTM_INQ_INFO structure, and returned in the
** BTM_InqDbRead, BTM_InqDbFirst, and BTM_InqDbNext functions.
** The name field is valid when the state returned is
** BTM_INQ_RMT_NAME_DONE */
#define BTM_INQ_RMT_NAME_EMPTY 0
#define BTM_INQ_RMT_NAME_PENDING 1
#define BTM_INQ_RMT_NAME_DONE 2
#define BTM_INQ_RMT_NAME_FAILED 3
/*********************************
*** Class of Device constants ***
*********************************/
#define BTM_FORMAT_TYPE_1 0x00
/****************************
** minor device class field
*****************************/
/* 0x00 is used as unclassified for all minor device classes */
#define BTM_COD_MINOR_UNCLASSIFIED 0x00
/* minor device class field for Computer Major Class */
/* #define BTM_COD_MINOR_UNCLASSIFIED 0x00 */
#define BTM_COD_MINOR_DESKTOP_WORKSTATION 0x04
#define BTM_COD_MINOR_SERVER_COMPUTER 0x08
#define BTM_COD_MINOR_LAPTOP 0x0C
#define BTM_COD_MINOR_HANDHELD_PC_PDA 0x10 /* clam shell */
#define BTM_COD_MINOR_PALM_SIZE_PC_PDA 0x14
#define BTM_COD_MINOR_WEARABLE_COMPUTER 0x18 /* watch sized */
/* minor device class field for Phone Major Class */
/* #define BTM_COD_MINOR_UNCLASSIFIED 0x00 */
#define BTM_COD_MINOR_CELLULAR 0x04
#define BTM_COD_MINOR_CORDLESS 0x08
#define BTM_COD_MINOR_SMART_PHONE 0x0C
#define BTM_COD_MINOR_WIRED_MDM_V_GTWY 0x10 /* wired modem or voice gatway */
#define BTM_COD_MINOR_ISDN_ACCESS 0x14
/* minor device class field for LAN Access Point Major Class */
/* Load Factor Field bit 5-7 */
#define BTM_COD_MINOR_FULLY_AVAILABLE 0x00
#define BTM_COD_MINOR_1_17_UTILIZED 0x20
#define BTM_COD_MINOR_17_33_UTILIZED 0x40
#define BTM_COD_MINOR_33_50_UTILIZED 0x60
#define BTM_COD_MINOR_50_67_UTILIZED 0x80
#define BTM_COD_MINOR_67_83_UTILIZED 0xA0
#define BTM_COD_MINOR_83_99_UTILIZED 0xC0
#define BTM_COD_MINOR_NO_SERVICE_AVAILABLE 0xE0
/* sub-Field bit 2-4 */
/* #define BTM_COD_MINOR_UNCLASSIFIED 0x00 */
/* minor device class field for Audio/Video Major Class */
/* #define BTM_COD_MINOR_UNCLASSIFIED 0x00 */
#define BTM_COD_MINOR_CONFM_HEADSET 0x04
#define BTM_COD_MINOR_CONFM_HANDSFREE 0x08
#define BTM_COD_MINOR_MICROPHONE 0x10
#define BTM_COD_MINOR_LOUDSPEAKER 0x14
#define BTM_COD_MINOR_HEADPHONES 0x18
#define BTM_COD_MINOR_PORTABLE_AUDIO 0x1C
#define BTM_COD_MINOR_CAR_AUDIO 0x20
#define BTM_COD_MINOR_SET_TOP_BOX 0x24
#define BTM_COD_MINOR_HIFI_AUDIO 0x28
#define BTM_COD_MINOR_VCR 0x2C
#define BTM_COD_MINOR_VIDEO_CAMERA 0x30
#define BTM_COD_MINOR_CAMCORDER 0x34
#define BTM_COD_MINOR_VIDEO_MONITOR 0x38
#define BTM_COD_MINOR_VIDDISP_LDSPKR 0x3C
#define BTM_COD_MINOR_VIDEO_CONFERENCING 0x40
#define BTM_COD_MINOR_GAMING_TOY 0x48
/* minor device class field for Peripheral Major Class */
/* Bits 6-7 independently specify mouse, keyboard, or combo mouse/keyboard */
#define BTM_COD_MINOR_KEYBOARD 0x40
#define BTM_COD_MINOR_POINTING 0x80
#define BTM_COD_MINOR_COMBO 0xC0
/* Bits 2-5 OR'd with selection from bits 6-7 */
/* #define BTM_COD_MINOR_UNCLASSIFIED 0x00 */
#define BTM_COD_MINOR_JOYSTICK 0x04
#define BTM_COD_MINOR_GAMEPAD 0x08
#define BTM_COD_MINOR_REMOTE_CONTROL 0x0C
#define BTM_COD_MINOR_SENSING_DEVICE 0x10
#define BTM_COD_MINOR_DIGITIZING_TABLET 0x14
#define BTM_COD_MINOR_CARD_READER 0x18 /* e.g. SIM card reader */
#define BTM_COD_MINOR_DIGITAL_PAN 0x1C
#define BTM_COD_MINOR_HAND_SCANNER 0x20
#define BTM_COD_MINOR_HAND_GESTURAL_INPUT 0x24
/* minor device class field for Imaging Major Class */
/* Bits 5-7 independently specify display, camera, scanner, or printer */
#define BTM_COD_MINOR_DISPLAY 0x10
#define BTM_COD_MINOR_CAMERA 0x20
#define BTM_COD_MINOR_SCANNER 0x40
#define BTM_COD_MINOR_PRINTER 0x80
/* Bits 2-3 Reserved */
/* #define BTM_COD_MINOR_UNCLASSIFIED 0x00 */
/* minor device class field for Wearable Major Class */
/* Bits 2-7 meaningful */
#define BTM_COD_MINOR_WRIST_WATCH 0x04
#define BTM_COD_MINOR_PAGER 0x08
#define BTM_COD_MINOR_JACKET 0x0C
#define BTM_COD_MINOR_HELMET 0x10
#define BTM_COD_MINOR_GLASSES 0x14
/* minor device class field for Toy Major Class */
/* Bits 2-7 meaningful */
#define BTM_COD_MINOR_ROBOT 0x04
#define BTM_COD_MINOR_VEHICLE 0x08
#define BTM_COD_MINOR_DOLL_ACTION_FIGURE 0x0C
#define BTM_COD_MINOR_CONTROLLER 0x10
#define BTM_COD_MINOR_GAME 0x14
/* minor device class field for Health Major Class */
/* Bits 2-7 meaningful */
#define BTM_COD_MINOR_BLOOD_MONITOR 0x04
#define BTM_COD_MINOR_THERMOMETER 0x08
#define BTM_COD_MINOR_WEIGHING_SCALE 0x0C
#define BTM_COD_MINOR_GLUCOSE_METER 0x10
#define BTM_COD_MINOR_PULSE_OXIMETER 0x14
#define BTM_COD_MINOR_HEART_PULSE_MONITOR 0x18
#define BTM_COD_MINOR_HEALTH_DATA_DISPLAY 0x1C
#define BTM_COD_MINOR_STEP_COUNTER 0x20
#define BTM_COD_MINOR_BODY_COM_ANALYZER 0x24
#define BTM_COD_MINOR_PEAK_FLOW_MONITOR 0x28
#define BTM_COD_MINOR_MEDICATION_MONITOR 0x2C
#define BTM_COD_MINOR_KNEE_PROSTHESIS 0x30
#define BTM_COD_MINOR_ANKLE_PROSTHESIS 0x34
/***************************
** major device class field
****************************/
#define BTM_COD_MAJOR_MISCELLANEOUS 0x00
#define BTM_COD_MAJOR_COMPUTER 0x01
#define BTM_COD_MAJOR_PHONE 0x02
#define BTM_COD_MAJOR_LAN_ACCESS_PT 0x03
#define BTM_COD_MAJOR_AUDIO 0x04
#define BTM_COD_MAJOR_PERIPHERAL 0x05
#define BTM_COD_MAJOR_IMAGING 0x06
#define BTM_COD_MAJOR_WEARABLE 0x07
#define BTM_COD_MAJOR_TOY 0x08
#define BTM_COD_MAJOR_HEALTH 0x09
#define BTM_COD_MAJOR_UNCLASSIFIED 0x1F
/***************************
** service class fields
****************************/
#define BTM_COD_SERVICE_LMTD_DISCOVER 0x0020
#define BTM_COD_SERVICE_POSITIONING 0x0100
#define BTM_COD_SERVICE_NETWORKING 0x0200
#define BTM_COD_SERVICE_RENDERING 0x0400
#define BTM_COD_SERVICE_CAPTURING 0x0800
#define BTM_COD_SERVICE_OBJ_TRANSFER 0x1000
#define BTM_COD_SERVICE_AUDIO 0x2000
#define BTM_COD_SERVICE_TELEPHONY 0x4000
#define BTM_COD_SERVICE_INFORMATION 0x8000
/* class of device field macros */
#define BTM_COD_FORMAT_TYPE(u8, pd) {u8 = pd[2]&0x03;}
#define BTM_COD_MINOR_CLASS(u8, pd) {u8 = pd[2]&0xFC;}
#define BTM_COD_MAJOR_CLASS(u8, pd) {u8 = pd[1]&0x1F;}
#define BTM_COD_SERVICE_CLASS(u16, pd) {u16 = pd[0]; u16<<=8; u16 += pd[1]&0xE0;}
/* to set the fields (assumes that format type is always 0) */
#define FIELDS_TO_COD(pd, mn, mj, sv) {pd[2] = mn; pd[1] = \
mj+ ((sv)&BTM_COD_SERVICE_CLASS_LO_B); \
pd[0] = (sv) >> 8;}
/* the COD masks */
#define BTM_COD_FORMAT_TYPE_MASK 0x03
#define BTM_COD_MINOR_CLASS_MASK 0xFC
#define BTM_COD_MAJOR_CLASS_MASK 0x1F
#define BTM_COD_SERVICE_CLASS_LO_B 0x00E0
#define BTM_COD_SERVICE_CLASS_MASK 0xFFE0
/* BTM service definitions
** Used for storing EIR data to bit mask
*/
enum {
BTM_EIR_UUID_SERVCLASS_SERVICE_DISCOVERY_SERVER,
/* BTM_EIR_UUID_SERVCLASS_BROWSE_GROUP_DESCRIPTOR, */
/* BTM_EIR_UUID_SERVCLASS_PUBLIC_BROWSE_GROUP, */
BTM_EIR_UUID_SERVCLASS_SERIAL_PORT,
BTM_EIR_UUID_SERVCLASS_LAN_ACCESS_USING_PPP,
BTM_EIR_UUID_SERVCLASS_DIALUP_NETWORKING,
BTM_EIR_UUID_SERVCLASS_IRMC_SYNC,
BTM_EIR_UUID_SERVCLASS_OBEX_OBJECT_PUSH,
BTM_EIR_UUID_SERVCLASS_OBEX_FILE_TRANSFER,
BTM_EIR_UUID_SERVCLASS_IRMC_SYNC_COMMAND,
BTM_EIR_UUID_SERVCLASS_HEADSET,
BTM_EIR_UUID_SERVCLASS_CORDLESS_TELEPHONY,
BTM_EIR_UUID_SERVCLASS_AUDIO_SOURCE,
BTM_EIR_UUID_SERVCLASS_AUDIO_SINK,
BTM_EIR_UUID_SERVCLASS_AV_REM_CTRL_TARGET,
/* BTM_EIR_UUID_SERVCLASS_ADV_AUDIO_DISTRIBUTION, */
BTM_EIR_UUID_SERVCLASS_AV_REMOTE_CONTROL,
/* BTM_EIR_UUID_SERVCLASS_VIDEO_CONFERENCING, */
BTM_EIR_UUID_SERVCLASS_INTERCOM,
BTM_EIR_UUID_SERVCLASS_FAX,
BTM_EIR_UUID_SERVCLASS_HEADSET_AUDIO_GATEWAY,
/* BTM_EIR_UUID_SERVCLASS_WAP, */
/* BTM_EIR_UUID_SERVCLASS_WAP_CLIENT, */
BTM_EIR_UUID_SERVCLASS_PANU,
BTM_EIR_UUID_SERVCLASS_NAP,
BTM_EIR_UUID_SERVCLASS_GN,
BTM_EIR_UUID_SERVCLASS_DIRECT_PRINTING,
/* BTM_EIR_UUID_SERVCLASS_REFERENCE_PRINTING, */
BTM_EIR_UUID_SERVCLASS_IMAGING,
BTM_EIR_UUID_SERVCLASS_IMAGING_RESPONDER,
BTM_EIR_UUID_SERVCLASS_IMAGING_AUTO_ARCHIVE,
BTM_EIR_UUID_SERVCLASS_IMAGING_REF_OBJECTS,
BTM_EIR_UUID_SERVCLASS_HF_HANDSFREE,
BTM_EIR_UUID_SERVCLASS_AG_HANDSFREE,
BTM_EIR_UUID_SERVCLASS_DIR_PRT_REF_OBJ_SERVICE,
/* BTM_EIR_UUID_SERVCLASS_REFLECTED_UI, */
BTM_EIR_UUID_SERVCLASS_BASIC_PRINTING,
BTM_EIR_UUID_SERVCLASS_PRINTING_STATUS,
BTM_EIR_UUID_SERVCLASS_HUMAN_INTERFACE,
BTM_EIR_UUID_SERVCLASS_CABLE_REPLACEMENT,
BTM_EIR_UUID_SERVCLASS_HCRP_PRINT,
BTM_EIR_UUID_SERVCLASS_HCRP_SCAN,
/* BTM_EIR_UUID_SERVCLASS_COMMON_ISDN_ACCESS, */
/* BTM_EIR_UUID_SERVCLASS_VIDEO_CONFERENCING_GW, */
/* BTM_EIR_UUID_SERVCLASS_UDI_MT, */
/* BTM_EIR_UUID_SERVCLASS_UDI_TA, */
/* BTM_EIR_UUID_SERVCLASS_VCP, */
BTM_EIR_UUID_SERVCLASS_SAP,
BTM_EIR_UUID_SERVCLASS_PBAP_PCE,
BTM_EIR_UUID_SERVCLASS_PBAP_PSE,
/* BTM_EIR_UUID_SERVCLASS_TE_PHONE_ACCESS, */
/* BTM_EIR_UUID_SERVCLASS_ME_PHONE_ACCESS, */
BTM_EIR_UUID_SERVCLASS_PHONE_ACCESS,
BTM_EIR_UUID_SERVCLASS_HEADSET_HS,
BTM_EIR_UUID_SERVCLASS_PNP_INFORMATION,
/* BTM_EIR_UUID_SERVCLASS_GENERIC_NETWORKING, */
/* BTM_EIR_UUID_SERVCLASS_GENERIC_FILETRANSFER, */
/* BTM_EIR_UUID_SERVCLASS_GENERIC_AUDIO, */
/* BTM_EIR_UUID_SERVCLASS_GENERIC_TELEPHONY, */
/* BTM_EIR_UUID_SERVCLASS_UPNP_SERVICE, */
/* BTM_EIR_UUID_SERVCLASS_UPNP_IP_SERVICE, */
/* BTM_EIR_UUID_SERVCLASS_ESDP_UPNP_IP_PAN, */
/* BTM_EIR_UUID_SERVCLASS_ESDP_UPNP_IP_LAP, */
/* BTM_EIR_UUID_SERVCLASS_ESDP_UPNP_IP_L2CAP, */
BTM_EIR_UUID_SERVCLASS_VIDEO_SOURCE,
BTM_EIR_UUID_SERVCLASS_VIDEO_SINK,
/* BTM_EIR_UUID_SERVCLASS_VIDEO_DISTRIBUTION */
/* BTM_EIR_UUID_SERVCLASS_HDP_PROFILE */
BTM_EIR_UUID_SERVCLASS_MESSAGE_ACCESS,
BTM_EIR_UUID_SERVCLASS_MESSAGE_NOTIFICATION,
BTM_EIR_UUID_SERVCLASS_HDP_SOURCE,
BTM_EIR_UUID_SERVCLASS_HDP_SINK,
BTM_EIR_MAX_SERVICES
};
/* search result in EIR of inquiry database */
#define BTM_EIR_FOUND 0
#define BTM_EIR_NOT_FOUND 1
#define BTM_EIR_UNKNOWN 2
typedef UINT8 tBTM_EIR_SEARCH_RESULT;
#define BTM_EIR_FLAGS_TYPE HCI_EIR_FLAGS_TYPE /* 0x01 */
#define BTM_EIR_MORE_16BITS_UUID_TYPE HCI_EIR_MORE_16BITS_UUID_TYPE /* 0x02 */
#define BTM_EIR_COMPLETE_16BITS_UUID_TYPE HCI_EIR_COMPLETE_16BITS_UUID_TYPE /* 0x03 */
#define BTM_EIR_MORE_32BITS_UUID_TYPE HCI_EIR_MORE_32BITS_UUID_TYPE /* 0x04 */
#define BTM_EIR_COMPLETE_32BITS_UUID_TYPE HCI_EIR_COMPLETE_32BITS_UUID_TYPE /* 0x05 */
#define BTM_EIR_MORE_128BITS_UUID_TYPE HCI_EIR_MORE_128BITS_UUID_TYPE /* 0x06 */
#define BTM_EIR_COMPLETE_128BITS_UUID_TYPE HCI_EIR_COMPLETE_128BITS_UUID_TYPE /* 0x07 */
#define BTM_EIR_SHORTENED_LOCAL_NAME_TYPE HCI_EIR_SHORTENED_LOCAL_NAME_TYPE /* 0x08 */
#define BTM_EIR_COMPLETE_LOCAL_NAME_TYPE HCI_EIR_COMPLETE_LOCAL_NAME_TYPE /* 0x09 */
#define BTM_EIR_TX_POWER_LEVEL_TYPE HCI_EIR_TX_POWER_LEVEL_TYPE /* 0x0A */
#define BTM_EIR_URL_TYPE HCI_EIR_URL_TYPE /* 0x24 */
#define BTM_EIR_MANUFACTURER_SPECIFIC_TYPE HCI_EIR_MANUFACTURER_SPECIFIC_TYPE /* 0xFF */
#define BTM_EIR_TYPE_MAX_NUM 12 /* Max EIR types */
/* the following EIR tags are defined to OOB, not regular EIR data */
#define BTM_EIR_OOB_BD_ADDR_TYPE HCI_EIR_OOB_BD_ADDR_TYPE /* 6 bytes */
#define BTM_EIR_OOB_COD_TYPE HCI_EIR_OOB_COD_TYPE /* 3 bytes */
#define BTM_EIR_OOB_SSP_HASH_C_TYPE HCI_EIR_OOB_SSP_HASH_C_TYPE /* 16 bytes */
#define BTM_EIR_OOB_SSP_RAND_R_TYPE HCI_EIR_OOB_SSP_RAND_R_TYPE /* 16 bytes */
#define BTM_OOB_MANDATORY_SIZE 8 /* include 2 bytes length & 6 bytes bd_addr */
#define BTM_OOB_DATA_LEN_SIZE 2
#define BTM_OOB_BD_ADDR_SIZE 6
#define BTM_OOB_COD_SIZE BT_OOB_COD_SIZE
#define BTM_OOB_HASH_C_SIZE BT_OOB_HASH_C_SIZE
#define BTM_OOB_RAND_R_SIZE BT_OOB_RAND_R_SIZE
#if BLE_INCLUDED == TRUE
#define BTM_BLE_SEC_NONE 0
#define BTM_BLE_SEC_ENCRYPT 1 /* encrypt the link using current key */
#define BTM_BLE_SEC_ENCRYPT_NO_MITM 2
#define BTM_BLE_SEC_ENCRYPT_MITM 3
typedef UINT8 tBTM_BLE_SEC_ACT;
#endif
/************************************************************************************************
** BTM Services MACROS handle array of UINT32 bits for more than 32 services
*************************************************************************************************/
/* Determine the number of UINT32's necessary for services */
#define BTM_EIR_ARRAY_BITS 32 /* Number of bits in each array element */
#define BTM_EIR_SERVICE_ARRAY_SIZE (((UINT32)BTM_EIR_MAX_SERVICES / BTM_EIR_ARRAY_BITS) + \
(((UINT32)BTM_EIR_MAX_SERVICES % BTM_EIR_ARRAY_BITS) ? 1 : 0))
/* MACRO to set the service bit mask in a bit stream */
#define BTM_EIR_SET_SERVICE(p, service) (((UINT32 *)(p))[(((UINT32)(service)) / BTM_EIR_ARRAY_BITS)] |= \
((UINT32)1 << (((UINT32)(service)) % BTM_EIR_ARRAY_BITS)))
/* MACRO to clear the service bit mask in a bit stream */
#define BTM_EIR_CLR_SERVICE(p, service) (((UINT32 *)(p))[(((UINT32)(service)) / BTM_EIR_ARRAY_BITS)] &= \
~((UINT32)1 << (((UINT32)(service)) % BTM_EIR_ARRAY_BITS)))
/* MACRO to check the service bit mask in a bit stream */
#define BTM_EIR_HAS_SERVICE(p, service) ((((UINT32 *)(p))[(((UINT32)(service)) / BTM_EIR_ARRAY_BITS)] & \
((UINT32)1 << (((UINT32)(service)) % BTM_EIR_ARRAY_BITS))) >> (((UINT32)(service)) % BTM_EIR_ARRAY_BITS))
/* start of EIR in HCI buffer, 4 bytes = HCI Command(2) + Length(1) + FEC_Req(1) */
#define BTM_HCI_EIR_OFFSET (BT_HDR_SIZE + 4)
/***************************
** Device Discovery Types
****************************/
/* Definitions of the parameters passed to BTM_StartInquiry and
** BTM_SetPeriodicInquiryMode.
*/
typedef struct { /* contains the two device class condition fields */
DEV_CLASS dev_class;
DEV_CLASS dev_class_mask;
} tBTM_COD_COND;
typedef union { /* contains the inquiry filter condition */
BD_ADDR bdaddr_cond;
tBTM_COD_COND cod_cond;
} tBTM_INQ_FILT_COND;
typedef struct { /* contains the parameters passed to the inquiry functions */
UINT8 mode; /* general or limited */
UINT8 duration; /* duration of the inquiry (1.28 sec increments) */
UINT8 max_resps; /* maximum number of responses to return */
BOOLEAN report_dup; /* report duplicated inquiry response with higher RSSI value */
UINT8 filter_cond_type; /* new devices, BD ADDR, COD, or No filtering */
tBTM_INQ_FILT_COND filter_cond; /* filter value based on filter cond type */
#if (defined(BTA_HOST_INTERLEAVE_SEARCH) && BTA_HOST_INTERLEAVE_SEARCH == TRUE)
UINT8 intl_duration[4]; /*duration array storing the interleave scan's time portions*/
#endif
} tBTM_INQ_PARMS;
#define BTM_INQ_RESULT_BR 0x01
#define BTM_INQ_RESULT_BLE 0x02
#if (BLE_INCLUDED == TRUE)
#define BTM_BLE_EVT_CONN_ADV 0x00
#define BTM_BLE_EVT_CONN_DIR_ADV 0x01
#define BTM_BLE_EVT_DISC_ADV 0x02
#define BTM_BLE_EVT_NON_CONN_ADV 0x03
#define BTM_BLE_EVT_SCAN_RSP 0x04
typedef UINT8 tBTM_BLE_EVT_TYPE;
#endif
/* These are the fields returned in each device's response to the inquiry. It
** is returned in the results callback if registered.
*/
typedef struct {
UINT16 clock_offset;
BD_ADDR remote_bd_addr;
DEV_CLASS dev_class;
UINT8 page_scan_rep_mode;
UINT8 page_scan_per_mode;
UINT8 page_scan_mode;
INT8 rssi; /* Set to BTM_INQ_RES_IGNORE_RSSI if not valid */
UINT32 eir_uuid[BTM_EIR_SERVICE_ARRAY_SIZE];
BOOLEAN eir_complete_list;
tBT_DEVICE_TYPE device_type;
#if (BLE_INCLUDED == TRUE)
UINT8 inq_result_type;
UINT8 ble_addr_type;
tBTM_BLE_EVT_TYPE ble_evt_type;
UINT8 flag;
UINT8 adv_data_len;
UINT8 scan_rsp_len;
#endif
} tBTM_INQ_RESULTS;
/* This is the inquiry response information held in its database by BTM, and available
** to applications via BTM_InqDbRead, BTM_InqDbFirst, and BTM_InqDbNext.
*/
typedef struct {
tBTM_INQ_RESULTS results;
BOOLEAN appl_knows_rem_name; /* set by application if it knows the remote name of the peer device.
This is later used by application to determine if remote name request is
required to be done. Having the flag here avoid duplicate store of inquiry results */
#if ( BLE_INCLUDED == TRUE)
UINT16 remote_name_len;
tBTM_BD_NAME remote_name;
UINT8 remote_name_state;
UINT8 remote_name_type;
#endif
} tBTM_INQ_INFO;
/* Structure returned with inquiry complete callback */
typedef struct {
tBTM_STATUS status;
UINT8 num_resp; /* Number of results from the current inquiry */
} tBTM_INQUIRY_CMPL;
/* Structure returned with remote name request */
typedef struct {
UINT16 status;
BD_ADDR bd_addr;
UINT16 length;
BD_NAME remote_bd_name;
} tBTM_REMOTE_DEV_NAME;
typedef struct {
UINT8 pcm_intf_rate; /* PCM interface rate: 0: 128kbps, 1: 256 kbps;
2:512 bps; 3: 1024kbps; 4: 2048kbps */
UINT8 frame_type; /* frame type: 0: short; 1: long */
UINT8 sync_mode; /* sync mode: 0: slave; 1: master */
UINT8 clock_mode; /* clock mode: 0: slave; 1: master */
} tBTM_SCO_PCM_PARAM;
/****************************************
** Device Discovery Callback Functions
*****************************************/
/* Callback function for asynchronous notifications when the BTM inquiry DB
** changes. First param is inquiry database, second is if added to or removed
** from the inquiry database.
*/
typedef void (tBTM_INQ_DB_CHANGE_CB) (void *p1, BOOLEAN is_new);
/* Callback function for notifications when the BTM gets inquiry response.
** First param is inquiry results database, second is pointer of EIR.
*/
typedef void (tBTM_INQ_RESULTS_CB) (tBTM_INQ_RESULTS *p_inq_results, UINT8 *p_eir);
/*****************************************************************************
** ACL CHANNEL MANAGEMENT
*****************************************************************************/
/******************
** ACL Constants
*******************/
/* ACL modes */
#define BTM_ACL_MODE_NORMAL HCI_MODE_ACTIVE
#define BTM_ACL_MODE_HOLD HCI_MODE_HOLD
#define BTM_ACL_MODE_SNIFF HCI_MODE_SNIFF
#define BTM_ACL_MODE_PARK HCI_MODE_PARK
/* Returned with structure in role switch callback (tBTM_ROLE_SWITCH_CMPL) */
#define BTM_ROLE_MASTER HCI_ROLE_MASTER
#define BTM_ROLE_SLAVE HCI_ROLE_SLAVE
#define BTM_ROLE_UNDEFINED 0xff /* undefined value (error status) */
/* ACL Packet Types */
#define BTM_ACL_PKT_TYPES_MASK_DM1 HCI_PKT_TYPES_MASK_DM1
#define BTM_ACL_PKT_TYPES_MASK_DH1 HCI_PKT_TYPES_MASK_DH1
#define BTM_ACL_PKT_TYPES_MASK_DM3 HCI_PKT_TYPES_MASK_DM3
#define BTM_ACL_PKT_TYPES_MASK_DH3 HCI_PKT_TYPES_MASK_DH3
#define BTM_ACL_PKT_TYPES_MASK_DM5 HCI_PKT_TYPES_MASK_DM5
#define BTM_ACL_PKT_TYPES_MASK_DH5 HCI_PKT_TYPES_MASK_DH5
#define BTM_ACL_PKT_TYPES_MASK_NO_2_DH1 HCI_PKT_TYPES_MASK_NO_2_DH1
#define BTM_ACL_PKT_TYPES_MASK_NO_3_DH1 HCI_PKT_TYPES_MASK_NO_3_DH1
#define BTM_ACL_PKT_TYPES_MASK_NO_2_DH3 HCI_PKT_TYPES_MASK_NO_2_DH3
#define BTM_ACL_PKT_TYPES_MASK_NO_3_DH3 HCI_PKT_TYPES_MASK_NO_3_DH3
#define BTM_ACL_PKT_TYPES_MASK_NO_2_DH5 HCI_PKT_TYPES_MASK_NO_2_DH5
#define BTM_ACL_PKT_TYPES_MASK_NO_3_DH5 HCI_PKT_TYPES_MASK_NO_3_DH5
/***************
** ACL Types
****************/
/* Structure returned with Role Switch information (in tBTM_CMPL_CB callback function)
** in response to BTM_SwitchRole call.
*/
typedef struct {
UINT8 hci_status; /* HCI status returned with the event */
UINT8 role; /* BTM_ROLE_MASTER or BTM_ROLE_SLAVE */
BD_ADDR remote_bd_addr; /* Remote BD addr involved with the switch */
} tBTM_ROLE_SWITCH_CMPL;
/* Structure returned with QoS information (in tBTM_CMPL_CB callback function)
** in response to BTM_SetQoS call.
*/
typedef struct {
FLOW_SPEC flow;
UINT16 handle;
UINT8 status;
BD_ADDR rem_bda;
} tBTM_QOS_SETUP_CMPL;
/* Structure returned with read RSSI event (in tBTM_CMPL_CB callback function)
** in response to BTM_ReadRSSI call.
*/
typedef struct {
tBTM_STATUS status;
UINT8 hci_status;
INT8 rssi;
BD_ADDR rem_bda;
} tBTM_RSSI_RESULTS;
/* Structure returned with read current TX power event (in tBTM_CMPL_CB callback function)
** in response to BTM_ReadTxPower call.
*/
typedef struct {
tBTM_STATUS status;
UINT8 hci_status;
INT8 tx_power;
BD_ADDR rem_bda;
} tBTM_TX_POWER_RESULTS;
/* Structure returned with read link quality event (in tBTM_CMPL_CB callback function)
** in response to BTM_ReadLinkQuality call.
*/
typedef struct {
tBTM_STATUS status;
UINT8 hci_status;
UINT8 link_quality;
BD_ADDR rem_bda;
} tBTM_LINK_QUALITY_RESULTS;
/* Structure returned with set AFH channels event (in tBTM_CMPL_CB callback function)
** in response to BTM_SetAfhChannels call.
*/
typedef struct {
tBTM_STATUS status;
UINT8 hci_status;
} tBTM_SET_AFH_CHANNELS_RESULTS;
/* Structure returned with set BLE channels event (in tBTM_CMPL_CB callback function)
** in response to BTM_BleSetChannels call.
*/
typedef struct {
tBTM_STATUS status;
UINT8 hci_status;
} tBTM_BLE_SET_CHANNELS_RESULTS;
/* Structure returned with read inq tx power quality event (in tBTM_CMPL_CB callback function)
** in response to BTM_ReadInquiryRspTxPower call.
*/
typedef struct {
tBTM_STATUS status;
UINT8 hci_status;
INT8 tx_power;
} tBTM_INQ_TXPWR_RESULTS;
enum {
BTM_BL_CONN_EVT,
BTM_BL_DISCN_EVT,
BTM_BL_UPDATE_EVT,
BTM_BL_ROLE_CHG_EVT,
BTM_BL_COLLISION_EVT
};
typedef UINT8 tBTM_BL_EVENT;
typedef UINT16 tBTM_BL_EVENT_MASK;
#define BTM_BL_CONN_MASK 0x0001
#define BTM_BL_DISCN_MASK 0x0002
#define BTM_BL_UPDATE_MASK 0x0004
#define BTM_BL_ROLE_CHG_MASK 0x0008
/* Device features mask definitions */
#define BTM_FEATURE_BYTES_PER_PAGE HCI_FEATURE_BYTES_PER_PAGE
#define BTM_EXT_FEATURES_PAGE_MAX HCI_EXT_FEATURES_PAGE_MAX
/* the data type associated with BTM_BL_CONN_EVT */
typedef struct {
tBTM_BL_EVENT event; /* The event reported. */
BD_ADDR_PTR p_bda; /* The address of the newly connected device */
DEV_CLASS_PTR p_dc; /* The device class */
BD_NAME_PTR p_bdn; /* The device name */
UINT8 *p_features; /* pointer to the remote device's features page[0] (supported features page) */
BOOLEAN sc_downgrade; /* Secure connection downgrade state. */
#if BLE_INCLUDED == TRUE
UINT16 handle; /* connection handle */
tBT_TRANSPORT transport; /* link is LE or not */
#endif
} tBTM_BL_CONN_DATA;
/* the data type associated with BTM_BL_DISCN_EVT */
typedef struct {
tBTM_BL_EVENT event; /* The event reported. */
BD_ADDR_PTR p_bda; /* The address of the disconnected device */
#if BLE_INCLUDED == TRUE
UINT16 handle; /* disconnected connection handle */
tBT_TRANSPORT transport; /* link is LE link or not */
#endif
} tBTM_BL_DISCN_DATA;
/* Busy-Level shall have the inquiry_paging mask set when
* inquiry/paging is in progress, Else the number of ACL links */
#define BTM_BL_INQUIRY_PAGING_MASK 0x10
#define BTM_BL_INQUIRY_STARTED (BTM_BL_INQUIRY_PAGING_MASK | 0x1)
#define BTM_BL_INQUIRY_CANCELLED (BTM_BL_INQUIRY_PAGING_MASK | 0x2)
#define BTM_BL_INQUIRY_COMPLETE (BTM_BL_INQUIRY_PAGING_MASK | 0x3)
#define BTM_BL_PAGING_STARTED (BTM_BL_INQUIRY_PAGING_MASK | 0x4)
#define BTM_BL_PAGING_COMPLETE (BTM_BL_INQUIRY_PAGING_MASK | 0x5)
/* the data type associated with BTM_BL_UPDATE_EVT */
typedef struct {
tBTM_BL_EVENT event; /* The event reported. */
UINT8 busy_level;/* when paging or inquiring, level is 10.
* Otherwise, the number of ACL links. */
UINT8 busy_level_flags; /* Notifies actual inquiry/page activities */
} tBTM_BL_UPDATE_DATA;
/* the data type associated with BTM_BL_ROLE_CHG_EVT */
typedef struct {
tBTM_BL_EVENT event; /* The event reported. */
BD_ADDR_PTR p_bda; /* The address of the peer connected device */
UINT8 new_role;
UINT8 hci_status; /* HCI status returned with the event */
} tBTM_BL_ROLE_CHG_DATA;
typedef union {
tBTM_BL_EVENT event; /* The event reported. */
tBTM_BL_CONN_DATA conn; /* The data associated with BTM_BL_CONN_EVT */
tBTM_BL_DISCN_DATA discn; /* The data associated with BTM_BL_DISCN_EVT */
tBTM_BL_UPDATE_DATA update; /* The data associated with BTM_BL_UPDATE_EVT */
tBTM_BL_ROLE_CHG_DATA role_chg;/*The data associated with BTM_BL_ROLE_CHG_EVT */
} tBTM_BL_EVENT_DATA;
/* Callback function for notifications when the BTM busy level
** changes.
*/
typedef void (tBTM_BL_CHANGE_CB) (tBTM_BL_EVENT_DATA *p_data);
/***************************
** ACL Callback Functions
****************************/
/* Callback function for notifications when the BTM ACL connection DB
** changes. First param is BD address, second is if added or removed.
** Registered through BTM_AclRegisterForChanges call.
*/
#if BLE_INCLUDED == TRUE
typedef void (tBTM_ACL_DB_CHANGE_CB) (BD_ADDR p_bda, DEV_CLASS p_dc,
BD_NAME p_bdn, UINT8 *features,
BOOLEAN is_new, UINT16 handle,
tBT_TRANSPORT transport);
#else
typedef void (tBTM_ACL_DB_CHANGE_CB) (BD_ADDR p_bda, DEV_CLASS p_dc,
BD_NAME p_bdn, UINT8 *features,
BOOLEAN is_new);
#endif
/*****************************************************************************
** SCO CHANNEL MANAGEMENT
*****************************************************************************/
/******************
** SCO Constants
*******************/
/* Define an invalid SCO index and an invalid HCI handle */
#define BTM_INVALID_SCO_INDEX 0xFFFF
#define BTM_INVALID_HCI_HANDLE 0xFFFF
/* Define an invalid SCO disconnect reason */
#define BTM_INVALID_SCO_DISC_REASON 0xFFFF
/* Define first active SCO index */
#define BTM_FIRST_ACTIVE_SCO_INDEX BTM_MAX_SCO_LINKS
/* Define SCO packet types used in APIs */
#define BTM_SCO_PKT_TYPES_MASK_HV1 HCI_ESCO_PKT_TYPES_MASK_HV1
#define BTM_SCO_PKT_TYPES_MASK_HV2 HCI_ESCO_PKT_TYPES_MASK_HV2
#define BTM_SCO_PKT_TYPES_MASK_HV3 HCI_ESCO_PKT_TYPES_MASK_HV3
#define BTM_SCO_PKT_TYPES_MASK_EV3 HCI_ESCO_PKT_TYPES_MASK_EV3
#define BTM_SCO_PKT_TYPES_MASK_EV4 HCI_ESCO_PKT_TYPES_MASK_EV4
#define BTM_SCO_PKT_TYPES_MASK_EV5 HCI_ESCO_PKT_TYPES_MASK_EV5
#define BTM_SCO_PKT_TYPES_MASK_NO_2_EV3 HCI_ESCO_PKT_TYPES_MASK_NO_2_EV3
#define BTM_SCO_PKT_TYPES_MASK_NO_3_EV3 HCI_ESCO_PKT_TYPES_MASK_NO_3_EV3
#define BTM_SCO_PKT_TYPES_MASK_NO_2_EV5 HCI_ESCO_PKT_TYPES_MASK_NO_2_EV5
#define BTM_SCO_PKT_TYPES_MASK_NO_3_EV5 HCI_ESCO_PKT_TYPES_MASK_NO_3_EV5
#define BTM_SCO_LINK_ONLY_MASK (BTM_SCO_PKT_TYPES_MASK_HV1 | \
BTM_SCO_PKT_TYPES_MASK_HV2 | \
BTM_SCO_PKT_TYPES_MASK_HV3)
#define BTM_ESCO_LINK_ONLY_MASK (BTM_SCO_PKT_TYPES_MASK_EV3 | \
BTM_SCO_PKT_TYPES_MASK_EV4 | \
BTM_SCO_PKT_TYPES_MASK_EV5)
#define BTM_SCO_LINK_ALL_PKT_MASK (BTM_SCO_LINK_ONLY_MASK | \
BTM_ESCO_LINK_ONLY_MASK)
#define BTM_VALID_SCO_ALL_PKT_TYPE HCI_VALID_SCO_ALL_PKT_TYPE
/* Passed in BTM_CreateSco if the packet type parameter should be ignored */
#define BTM_IGNORE_SCO_PKT_TYPE 0
/***************
** SCO Types
****************/
#define BTM_LINK_TYPE_SCO HCI_LINK_TYPE_SCO
#define BTM_LINK_TYPE_ESCO HCI_LINK_TYPE_ESCO
typedef UINT8 tBTM_SCO_TYPE;
/*******************
** SCO Routing Path
********************/
#define BTM_SCO_ROUTE_PCM (0) // HCI_BRCM_SCO_ROUTE_PCM
#define BTM_SCO_ROUTE_HCI (1) // HCI_BRCM_SCO_ROUTE_HCI
typedef UINT8 tBTM_SCO_ROUTE_TYPE;
/*******************
** SCO Codec Types
********************/
// TODO(google) This should use common definitions
// in hci/include/hci_audio.h
#define BTM_SCO_CODEC_NONE 0x0000
#define BTM_SCO_CODEC_CVSD 0x0001
#define BTM_SCO_CODEC_MSBC 0x0002
typedef UINT16 tBTM_SCO_CODEC_TYPE;
/*******************
** SCO Air Mode Types
********************/
#define BTM_SCO_AIR_MODE_U_LAW 0
#define BTM_SCO_AIR_MODE_A_LAW 1
#define BTM_SCO_AIR_MODE_CVSD 2
#define BTM_SCO_AIR_MODE_TRANSPNT 3
#define BTM_SCO_AIR_MODE_UNKNOWN 0xFF
typedef UINT8 tBTM_SCO_AIR_MODE_TYPE;
/*******************
** SCO Voice Settings
********************/
#define BTM_VOICE_SETTING_CVSD ((UINT16) (HCI_INP_CODING_LINEAR | \
HCI_INP_DATA_FMT_2S_COMPLEMENT | \
HCI_INP_SAMPLE_SIZE_16BIT | \
HCI_AIR_CODING_FORMAT_CVSD))
#define BTM_VOICE_SETTING_TRANS ((UINT16) (HCI_INP_CODING_LINEAR | \
HCI_INP_DATA_FMT_2S_COMPLEMENT | \
HCI_INP_SAMPLE_SIZE_8BIT | \
HCI_AIR_CODING_FORMAT_TRANSPNT))
/*******************
** SCO Data Status
********************/
enum {
BTM_SCO_DATA_CORRECT,
BTM_SCO_DATA_PAR_ERR,
BTM_SCO_DATA_NONE,
BTM_SCO_DATA_PAR_LOST
};
typedef UINT8 tBTM_SCO_DATA_FLAG;
/***************************
** SCO Callback Functions
****************************/
typedef void (tBTM_SCO_CB) (UINT16 sco_inx);
typedef void (tBTM_SCO_DATA_CB) (UINT16 sco_inx, BT_HDR *p_data, tBTM_SCO_DATA_FLAG status);
/******************
** eSCO Constants
*******************/
#define BTM_64KBITS_RATE 0x00001f40 /* 64 kbits/sec data rate */
/* Retransmission effort */
#define BTM_ESCO_RETRANS_OFF 0
#define BTM_ESCO_RETRANS_POWER 1
#define BTM_ESCO_RETRANS_QUALITY 2
#define BTM_ESCO_RETRANS_DONTCARE 0xff
/* Max Latency Don't Care */
#define BTM_ESCO_MAX_LAT_DONTCARE 0xffff
/***************
** eSCO Types
****************/
/* tBTM_ESCO_CBACK event types */
#define BTM_ESCO_CHG_EVT 1
#define BTM_ESCO_CONN_REQ_EVT 2
typedef UINT8 tBTM_ESCO_EVT;
/* Passed into BTM_SetEScoMode() */
typedef struct {
UINT32 tx_bw;
UINT32 rx_bw;
UINT16 max_latency;
UINT16 voice_contfmt; /* Voice Settings or Content Format */
UINT16 packet_types;
UINT8 retrans_effort;
} tBTM_ESCO_PARAMS;
typedef struct {
UINT16 max_latency;
UINT16 packet_types;
UINT8 retrans_effort;
} tBTM_CHG_ESCO_PARAMS;
/* Returned by BTM_ReadEScoLinkParms() */
typedef struct {
UINT16 rx_pkt_len;
UINT16 tx_pkt_len;
BD_ADDR bd_addr;
UINT8 link_type; /* BTM_LINK_TYPE_SCO or BTM_LINK_TYPE_ESCO */
UINT8 tx_interval;
UINT8 retrans_window;
UINT8 air_mode;
} tBTM_ESCO_DATA;
typedef struct {
UINT16 sco_inx;
UINT16 rx_pkt_len;
UINT16 tx_pkt_len;
BD_ADDR bd_addr;
UINT8 hci_status;
UINT8 tx_interval;
UINT8 retrans_window;
} tBTM_CHG_ESCO_EVT_DATA;
typedef struct {
UINT16 sco_inx;
BD_ADDR bd_addr;
DEV_CLASS dev_class;
tBTM_SCO_TYPE link_type;
} tBTM_ESCO_CONN_REQ_EVT_DATA;
typedef union {
tBTM_CHG_ESCO_EVT_DATA chg_evt;
tBTM_ESCO_CONN_REQ_EVT_DATA conn_evt;
} tBTM_ESCO_EVT_DATA;
/***************************
** eSCO Callback Functions
****************************/
typedef void (tBTM_ESCO_CBACK) (tBTM_ESCO_EVT event, tBTM_ESCO_EVT_DATA *p_data);
/*****************************************************************************
** SECURITY MANAGEMENT
*****************************************************************************/
/*******************************
** Security Manager Constants
********************************/
/* Security Mode (BTM_SetSecurityMode) */
#define BTM_SEC_MODE_UNDEFINED 0
#define BTM_SEC_MODE_NONE 1
#define BTM_SEC_MODE_SERVICE 2
#define BTM_SEC_MODE_LINK 3
#define BTM_SEC_MODE_SP 4
#define BTM_SEC_MODE_SP_DEBUG 5
#define BTM_SEC_MODE_SC 6
/* Maximum Number of BTM Security Modes */
#define BTM_SEC_MODES_MAX 7
/* Security Service Levels [bit mask] (BTM_SetSecurityLevel)
** Encryption should not be used without authentication
*/
#define BTM_SEC_NONE 0x0000 /* Nothing required */
#define BTM_SEC_IN_AUTHORIZE 0x0001 /* Inbound call requires authorization */
#define BTM_SEC_IN_AUTHENTICATE 0x0002 /* Inbound call requires authentication */
#define BTM_SEC_IN_ENCRYPT 0x0004 /* Inbound call requires encryption */
#define BTM_SEC_OUT_AUTHORIZE 0x0008 /* Outbound call requires authorization */
#define BTM_SEC_OUT_AUTHENTICATE 0x0010 /* Outbound call requires authentication */
#define BTM_SEC_OUT_ENCRYPT 0x0020 /* Outbound call requires encryption */
#define BTM_SEC_MODE4_LEVEL4 0x0040 /* Secure Connections Only Mode */
#define BTM_SEC_FORCE_MASTER 0x0100 /* Need to switch connection to be master */
#define BTM_SEC_ATTEMPT_MASTER 0x0200 /* Try to switch connection to be master */
#define BTM_SEC_FORCE_SLAVE 0x0400 /* Need to switch connection to be master */
#define BTM_SEC_ATTEMPT_SLAVE 0x0800 /* Try to switch connection to be slave */
#define BTM_SEC_IN_MITM 0x1000 /* inbound Do man in the middle protection */
#define BTM_SEC_OUT_MITM 0x2000 /* outbound Do man in the middle protection */
#define BTM_SEC_IN_MIN_16_DIGIT_PIN 0x4000 /* enforce a minimum of 16 digit for sec mode 2 */
/* Security Flags [bit mask] (BTM_GetSecurityFlags)
*/
#define BTM_SEC_FLAG_AUTHORIZED 0x01
#define BTM_SEC_FLAG_AUTHENTICATED 0x02
#define BTM_SEC_FLAG_ENCRYPTED 0x04
#define BTM_SEC_FLAG_LKEY_KNOWN 0x10
#define BTM_SEC_FLAG_LKEY_AUTHED 0x20
/* PIN types */
#define BTM_PIN_TYPE_VARIABLE HCI_PIN_TYPE_VARIABLE
#define BTM_PIN_TYPE_FIXED HCI_PIN_TYPE_FIXED
/* Link Key types used to generate the new link key.
** returned in link key notification callback function
*/
#define BTM_LKEY_TYPE_COMBINATION HCI_LKEY_TYPE_COMBINATION
#define BTM_LKEY_TYPE_LOCAL_UNIT HCI_LKEY_TYPE_LOCAL_UNIT
#define BTM_LKEY_TYPE_REMOTE_UNIT HCI_LKEY_TYPE_REMOTE_UNIT
#define BTM_LKEY_TYPE_DEBUG_COMB HCI_LKEY_TYPE_DEBUG_COMB
#define BTM_LKEY_TYPE_UNAUTH_COMB HCI_LKEY_TYPE_UNAUTH_COMB
#define BTM_LKEY_TYPE_AUTH_COMB HCI_LKEY_TYPE_AUTH_COMB
#define BTM_LKEY_TYPE_CHANGED_COMB HCI_LKEY_TYPE_CHANGED_COMB
#define BTM_LKEY_TYPE_UNAUTH_COMB_P_256 HCI_LKEY_TYPE_UNAUTH_COMB_P_256
#define BTM_LKEY_TYPE_AUTH_COMB_P_256 HCI_LKEY_TYPE_AUTH_COMB_P_256
#define BTM_LTK_DERIVED_LKEY_OFFSET 0x20 /* "easy" requirements for LK derived from LTK */
#define BTM_LKEY_TYPE_IGNORE 0xff /* used when event is response from
hci return link keys request */
typedef UINT8 tBTM_LINK_KEY_TYPE;
/* Protocol level security (BTM_SetSecurityLevel) */
#define BTM_SEC_PROTO_L2CAP 0
#define BTM_SEC_PROTO_SDP 1
#define BTM_SEC_PROTO_TCS 2
#define BTM_SEC_PROTO_RFCOMM 3
#define BTM_SEC_PROTO_OBEX 4
#define BTM_SEC_PROTO_BNEP 5
#define BTM_SEC_PROTO_HID 6 /* HID */
#define BTM_SEC_PROTO_AVDT 7
#define BTM_SEC_PROTO_MCA 8
/* Determine the number of UINT32's necessary for security services */
#define BTM_SEC_ARRAY_BITS 32 /* Number of bits in each array element */
#define BTM_SEC_SERVICE_ARRAY_SIZE (((UINT32)BTM_SEC_MAX_SERVICES / BTM_SEC_ARRAY_BITS) + \
(((UINT32)BTM_SEC_MAX_SERVICES % BTM_SEC_ARRAY_BITS) ? 1 : 0))
/* Security service definitions (BTM_SetSecurityLevel)
** Used for Authorization APIs
*/
#define BTM_SEC_SERVICE_SDP_SERVER 0
#define BTM_SEC_SERVICE_SERIAL_PORT 1
#define BTM_SEC_SERVICE_LAN_ACCESS 2
#define BTM_SEC_SERVICE_DUN 3
#define BTM_SEC_SERVICE_IRMC_SYNC 4
#define BTM_SEC_SERVICE_IRMC_SYNC_CMD 5
#define BTM_SEC_SERVICE_OBEX 6
#define BTM_SEC_SERVICE_OBEX_FTP 7
#define BTM_SEC_SERVICE_HEADSET 8
#define BTM_SEC_SERVICE_CORDLESS 9
#define BTM_SEC_SERVICE_INTERCOM 10
#define BTM_SEC_SERVICE_FAX 11
#define BTM_SEC_SERVICE_HEADSET_AG 12
#define BTM_SEC_SERVICE_PNP_INFO 13
#define BTM_SEC_SERVICE_GEN_NET 14
#define BTM_SEC_SERVICE_GEN_FILE 15
#define BTM_SEC_SERVICE_GEN_AUDIO 16
#define BTM_SEC_SERVICE_GEN_TEL 17
#define BTM_SEC_SERVICE_CTP_DATA 18
#define BTM_SEC_SERVICE_HCRP_CTRL 19
#define BTM_SEC_SERVICE_HCRP_DATA 20
#define BTM_SEC_SERVICE_HCRP_NOTIF 21
#define BTM_SEC_SERVICE_BPP_JOB 22
#define BTM_SEC_SERVICE_BPP_STATUS 23
#define BTM_SEC_SERVICE_BPP_REF 24
#define BTM_SEC_SERVICE_BNEP_PANU 25
#define BTM_SEC_SERVICE_BNEP_GN 26
#define BTM_SEC_SERVICE_BNEP_NAP 27
#define BTM_SEC_SERVICE_HF_HANDSFREE 28
#define BTM_SEC_SERVICE_AG_HANDSFREE 29
#define BTM_SEC_SERVICE_TE_PHONE_ACCESS 30
#define BTM_SEC_SERVICE_ME_PHONE_ACCESS 31
#define BTM_SEC_SERVICE_HIDH_SEC_CTRL 32
#define BTM_SEC_SERVICE_HIDH_NOSEC_CTRL 33
#define BTM_SEC_SERVICE_HIDH_INTR 34
#define BTM_SEC_SERVICE_BIP 35
#define BTM_SEC_SERVICE_BIP_REF 36
#define BTM_SEC_SERVICE_AVDTP 37
#define BTM_SEC_SERVICE_AVDTP_NOSEC 38
#define BTM_SEC_SERVICE_AVCTP 39
#define BTM_SEC_SERVICE_SAP 40
#define BTM_SEC_SERVICE_PBAP 41
#define BTM_SEC_SERVICE_RFC_MUX 42
#define BTM_SEC_SERVICE_AVCTP_BROWSE 43
#define BTM_SEC_SERVICE_MAP 44
#define BTM_SEC_SERVICE_MAP_NOTIF 45
#define BTM_SEC_SERVICE_MCAP_CTRL 46
#define BTM_SEC_SERVICE_MCAP_DATA 47
#define BTM_SEC_SERVICE_HDP_SNK 48
#define BTM_SEC_SERVICE_HDP_SRC 49
#define BTM_SEC_SERVICE_ATT 50
/* Update these as services are added */
#define BTM_SEC_SERVICE_FIRST_EMPTY 51
#ifndef BTM_SEC_MAX_SERVICES
#define BTM_SEC_MAX_SERVICES 65
#endif
/************************************************************************************************
** Security Services MACROS handle array of UINT32 bits for more than 32 trusted services
*************************************************************************************************/
/* MACRO to set the security service bit mask in a bit stream */
#define BTM_SEC_SET_SERVICE(p, service) (((UINT32 *)(p))[(((UINT32)(service)) / BTM_SEC_ARRAY_BITS)] |= \
((UINT32)1 << (((UINT32)(service)) % BTM_SEC_ARRAY_BITS)))
/* MACRO to clear the security service bit mask in a bit stream */
#define BTM_SEC_CLR_SERVICE(p, service) (((UINT32 *)(p))[(((UINT32)(service)) / BTM_SEC_ARRAY_BITS)] &= \
~((UINT32)1 << (((UINT32)(service)) % BTM_SEC_ARRAY_BITS)))
/* MACRO to check the security service bit mask in a bit stream (Returns TRUE or FALSE) */
#define BTM_SEC_IS_SERVICE_TRUSTED(p, service) (((((UINT32 *)(p))[(((UINT32)(service)) / BTM_SEC_ARRAY_BITS)]) & \
(UINT32)(((UINT32)1 << (((UINT32)(service)) % BTM_SEC_ARRAY_BITS)))) ? TRUE : FALSE)
/* MACRO to copy two trusted device bitmask */
#define BTM_SEC_COPY_TRUSTED_DEVICE(p_src, p_dst) {UINT32 trst; for (trst = 0; trst < BTM_SEC_SERVICE_ARRAY_SIZE; trst++) \
((UINT32 *)(p_dst))[trst] = ((UINT32 *)(p_src))[trst];}
/* MACRO to clear two trusted device bitmask */
#define BTM_SEC_CLR_TRUSTED_DEVICE(p_dst) {UINT32 trst; for (trst = 0; trst < BTM_SEC_SERVICE_ARRAY_SIZE; trst++) \
((UINT32 *)(p_dst))[trst] = 0;}
/* Following bits can be provided by host in the trusted_mask array */
/* 0..31 bits of mask[0] (Least Significant Word) */
#define BTM_SEC_TRUST_SDP_SERVER (1 << BTM_SEC_SERVICE_SDP_SERVER)
#define BTM_SEC_TRUST_SERIAL_PORT (1 << BTM_SEC_SERVICE_SERIAL_PORT)
#define BTM_SEC_TRUST_LAN_ACCESS (1 << BTM_SEC_SERVICE_LAN_ACCESS)
#define BTM_SEC_TRUST_DUN (1 << BTM_SEC_SERVICE_DUN)
#define BTM_SEC_TRUST_IRMC_SYNC (1 << BTM_SEC_SERVICE_IRMC_SYNC)
#define BTM_SEC_TRUST_IRMC_SYNC_CMD (1 << BTM_SEC_SERVICE_IRMC_SYNC_CMD)
#define BTM_SEC_TRUST_OBEX (1 << BTM_SEC_SERVICE_OBEX)
#define BTM_SEC_TRUST_OBEX_FTP (1 << BTM_SEC_SERVICE_OBEX_FTP)
#define BTM_SEC_TRUST_HEADSET (1 << BTM_SEC_SERVICE_HEADSET)
#define BTM_SEC_TRUST_CORDLESS (1 << BTM_SEC_SERVICE_CORDLESS)
#define BTM_SEC_TRUST_INTERCOM (1 << BTM_SEC_SERVICE_INTERCOM)
#define BTM_SEC_TRUST_FAX (1 << BTM_SEC_SERVICE_FAX)
#define BTM_SEC_TRUST_HEADSET_AG (1 << BTM_SEC_SERVICE_HEADSET_AG)
#define BTM_SEC_TRUST_PNP_INFO (1 << BTM_SEC_SERVICE_PNP_INFO)
#define BTM_SEC_TRUST_GEN_NET (1 << BTM_SEC_SERVICE_GEN_NET)
#define BTM_SEC_TRUST_GEN_FILE (1 << BTM_SEC_SERVICE_GEN_FILE)
#define BTM_SEC_TRUST_GEN_AUDIO (1 << BTM_SEC_SERVICE_GEN_AUDIO)
#define BTM_SEC_TRUST_GEN_TEL (1 << BTM_SEC_SERVICE_GEN_TEL)
#define BTM_SEC_TRUST_CTP_DATA (1 << BTM_SEC_SERVICE_CTP_DATA)
#define BTM_SEC_TRUST_HCRP_CTRL (1 << BTM_SEC_SERVICE_HCRP_CTRL)
#define BTM_SEC_TRUST_HCRP_DATA (1 << BTM_SEC_SERVICE_HCRP_DATA)
#define BTM_SEC_TRUST_HCRP_NOTIF (1 << BTM_SEC_SERVICE_HCRP_NOTIF)
#define BTM_SEC_TRUST_BPP_JOB (1 << BTM_SEC_SERVICE_JOB)
#define BTM_SEC_TRUST_BPP_STATUS (1 << BTM_SEC_SERVICE_STATUS)
#define BTM_SEC_TRUST_BPP_REF (1 << BTM_SEC_SERVICE_REF)
#define BTM_SEC_TRUST_BNEP_PANU (1 << BTM_SEC_SERVICE_BNEP_PANU)
#define BTM_SEC_TRUST_BNEP_GN (1 << BTM_SEC_SERVICE_BNEP_GN)
#define BTM_SEC_TRUST_BNEP_NAP (1 << BTM_SEC_SERVICE_BNEP_NAP)
#define BTM_SEC_TRUST_HFP_HF (1 << BTM_SEC_SERVICE_HF_HANDSFREE)
#define BTM_SEC_TRUST_HFP_AG (1 << BTM_SEC_SERVICE_AG_HANDSFREE)
#define BTM_SEC_TRUST_TE_PHONE_ACCESS (1 << BTM_SEC_SERVICE_TE_PHONE_ACCESS)
#define BTM_SEC_TRUST_ME_PHONE_ACCESS (1 << BTM_SEC_SERVICE_ME_PHONE_ACCESS)
/* 0..31 bits of mask[1] (Most Significant Word) */
#define BTM_SEC_TRUST_HIDH_CTRL (1 << (BTM_SEC_SERVICE_HIDH_SEC_CTRL - 32))
#define BTM_SEC_TRUST_HIDH_NOSEC_CTRL (1 << (BTM_SEC_SERVICE_HIDH_NOSEC_CTRL - 32))
#define BTM_SEC_TRUST_HIDH_INTR (1 << (BTM_SEC_SERVICE_HIDH_INTR - 32))
#define BTM_SEC_TRUST_BIP (1 << (BTM_SEC_SERVICE_BIP - 32))
#define BTM_SEC_TRUST_BIP_REF (1 << (BTM_SEC_SERVICE_BIP_REF - 32))
#define BTM_SEC_TRUST_AVDTP (1 << (BTM_SEC_SERVICE_AVDTP - 32))
#define BTM_SEC_TRUST_AVDTP_NOSEC (1 << (BTM_SEC_SERVICE_AVDTP_NOSEC - 32))
#define BTM_SEC_TRUST_AVCTP (1 << (BTM_SEC_SERVICE_AVCTP - 32))
#define BTM_SEC_TRUST_SAP (1 << (BTM_SEC_SERVICE_SAP - 32))
#define BTM_SEC_TRUST_PBAP (1 << (BTM_SEC_SERVICE_PBAP - 32))
#define BTM_SEC_TRUST_RFC_MUX (1 << (BTM_SEC_SERVICE_RFC_MUX - 32))
#define BTM_SEC_TRUST_AVCTP_BROWSE (1 << (BTM_SEC_SERVICE_AVCTP_BROWSE - 32))
#define BTM_SEC_TRUST_MAP (1 << (BTM_SEC_SERVICE_MAP - 32))
#define BTM_SEC_TRUST_MAP_NOTIF (1 << (BTM_SEC_SERVICE_MAP_NOTIF - 32))
#define BTM_SEC_TRUST_MCAP_CTRL (1 << (BTM_SEC_SERVICE_MCAP_CTRL - 32))
#define BTM_SEC_TRUST_MCAP_DATA (1 << (BTM_SEC_SERVICE_MCAP_DATA - 32))
#define BTM_SEC_TRUST_HDP_SNK (1 << (BTM_SEC_SERVICE_HDP_SNK - 32))
#define BTM_SEC_TRUST_HDP_SRC (1 << (BTM_SEC_SERVICE_HDP_SRC - 32))
#define BTM_SEC_TRUST_ALL 0xFFFFFFFF /* for each array element */
/****************************************
** Security Manager Callback Functions
*****************************************/
/* Authorize device for service. Parameters are
** BD Address of remote
** Device Class of remote
** BD Name of remote
** Service name
** Service Id (NULL - unknown service or unused
** [BTM_SEC_SERVICE_NAME_LEN set to 0])
** Is originator of the connection
** Result of the operation
*/
typedef UINT8 (tBTM_AUTHORIZE_CALLBACK) (BD_ADDR bd_addr, DEV_CLASS dev_class,
tBTM_BD_NAME bd_name, UINT8 *service_name,
UINT8 service_id, BOOLEAN is_originator);
/* Get PIN for the connection. Parameters are
** BD Address of remote
** Device Class of remote
** BD Name of remote
** Flag indicating the minimum pin code length to be 16 digits
*/
typedef UINT8 (tBTM_PIN_CALLBACK) (BD_ADDR bd_addr, DEV_CLASS dev_class,
tBTM_BD_NAME bd_name, BOOLEAN min_16_digit);
/* New Link Key for the connection. Parameters are
** BD Address of remote
** Link Key
** Key Type: Combination, Local Unit, or Remote Unit
*/
typedef UINT8 (tBTM_LINK_KEY_CALLBACK) (BD_ADDR bd_addr, DEV_CLASS dev_class,
tBTM_BD_NAME bd_name, UINT8 *key,
UINT8 key_type, BOOLEAN sc_support);
/* Remote Name Resolved. Parameters are
** BD Address of remote
** BD Name of remote
*/
typedef void (tBTM_RMT_NAME_CALLBACK) (BD_ADDR bd_addr, DEV_CLASS dc,
tBTM_BD_NAME bd_name);
/* Authentication complete for the connection. Parameters are
** BD Address of remote
** Device Class of remote
** BD Name of remote
**
*/
typedef UINT8 (tBTM_AUTH_COMPLETE_CALLBACK) (BD_ADDR bd_addr, DEV_CLASS dev_class,
tBTM_BD_NAME bd_name, int result);
enum {
BTM_SP_IO_REQ_EVT, /* received IO_CAPABILITY_REQUEST event */
BTM_SP_IO_RSP_EVT, /* received IO_CAPABILITY_RESPONSE event */
BTM_SP_CFM_REQ_EVT, /* received USER_CONFIRMATION_REQUEST event */
BTM_SP_KEY_NOTIF_EVT, /* received USER_PASSKEY_NOTIFY event */
BTM_SP_KEY_REQ_EVT, /* received USER_PASSKEY_REQUEST event */
BTM_SP_KEYPRESS_EVT, /* received KEYPRESS_NOTIFY event */
BTM_SP_LOC_OOB_EVT, /* received result for READ_LOCAL_OOB_DATA command */
BTM_SP_RMT_OOB_EVT, /* received REMOTE_OOB_DATA_REQUEST event */
BTM_SP_COMPLT_EVT, /* received SIMPLE_PAIRING_COMPLETE event */
BTM_SP_UPGRADE_EVT /* check if the application wants to upgrade the link key */
};
typedef UINT8 tBTM_SP_EVT;
/* relate to ESP_IO_CAP_xxx in esp_gap_ble_api.h */
#define BTM_IO_CAP_OUT 0 /* DisplayOnly */
#define BTM_IO_CAP_IO 1 /* DisplayYesNo */
#define BTM_IO_CAP_IN 2 /* KeyboardOnly */
#define BTM_IO_CAP_NONE 3 /* NoInputNoOutput */
// #if BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE
#define BTM_IO_CAP_KBDISP 4 /* Keyboard display */
#define BTM_IO_CAP_MAX 5
// #else
// #define BTM_IO_CAP_MAX 4
// #endif
typedef UINT8 tBTM_IO_CAP;
#define BTM_MAX_PASSKEY_VAL (999999)
#define BTM_MIN_PASSKEY_VAL (0)
#define BTM_AUTH_SP_NO 0 /* MITM Protection Not Required - Single Profile/non-bonding
Numeric comparison with automatic accept allowed */
#define BTM_AUTH_SP_YES 1 /* MITM Protection Required - Single Profile/non-bonding
Use IO Capabilities to determine authentication procedure */
#define BTM_AUTH_AP_NO 2 /* MITM Protection Not Required - All Profiles/dedicated bonding
Numeric comparison with automatic accept allowed */
#define BTM_AUTH_AP_YES 3 /* MITM Protection Required - All Profiles/dedicated bonding
Use IO Capabilities to determine authentication procedure */
#define BTM_AUTH_SPGB_NO 4 /* MITM Protection Not Required - Single Profiles/general bonding
Numeric comparison with automatic accept allowed */
#define BTM_AUTH_SPGB_YES 5 /* MITM Protection Required - Single Profiles/general bonding
Use IO Capabilities to determine authentication procedure */
#define BTM_AUTH_DD_BOND 2 /* this bit is ORed to the BTM_AUTH_SP_* when IO exchange for dedicated bonding */
#define BTM_AUTH_GB_BIT 4 /* the genernal bonding bit */
#define BTM_AUTH_BONDS 6 /* the general/dedicated bonding bits */
#define BTM_AUTH_YN_BIT 1 /* this is the Yes or No bit */
#define BTM_BLE_ENC_KEY_MASK (1 << 0)
#define BTM_BLE_ID_KEY_MASK (1 << 1)
#define BTM_BLE_CSR_KEY_MASK (1 << 2)
#define BTM_BLE_LINK_KEY_MASK (1 << 3)
#define BTM_BLE_INITIATOR_KEY_SIZE 15
#define BTM_BLE_RESPONDER_KEY_SIZE 15
#define BTM_BLE_MAX_KEY_SIZE 16
#define BTM_BLE_MIN_KEY_SIZE 7
#define BTM_BLE_APPL_ENC_KEY_SIZE 7
typedef UINT8 tBTM_AUTH_REQ;
enum {
BTM_OOB_NONE,
BTM_OOB_PRESENT
#if BTM_OOB_INCLUDED == TRUE
, BTM_OOB_UNKNOWN
#endif
};
typedef UINT8 tBTM_OOB_DATA;
/* data type for BTM_SP_IO_REQ_EVT */
typedef struct {
BD_ADDR bd_addr; /* peer address */
tBTM_IO_CAP io_cap; /* local IO capabilities */
tBTM_OOB_DATA oob_data; /* OOB data present (locally) for the peer device */
tBTM_AUTH_REQ auth_req; /* Authentication required (for local device) */
BOOLEAN is_orig; /* TRUE, if local device initiated the SP process */
} tBTM_SP_IO_REQ;
/* data type for BTM_SP_IO_RSP_EVT */
typedef struct {
BD_ADDR bd_addr; /* peer address */
tBTM_IO_CAP io_cap; /* peer IO capabilities */
tBTM_OOB_DATA oob_data; /* OOB data present at peer device for the local device */
tBTM_AUTH_REQ auth_req; /* Authentication required for peer device */
} tBTM_SP_IO_RSP;
/* data type for BTM_SP_CFM_REQ_EVT */
typedef struct {
BD_ADDR bd_addr; /* peer address */
DEV_CLASS dev_class; /* peer CoD */
tBTM_BD_NAME bd_name; /* peer device name */
UINT32 num_val; /* the numeric value for comparison. If just_works, do not show this number to UI */
BOOLEAN just_works; /* TRUE, if "Just Works" association model */
tBTM_AUTH_REQ loc_auth_req; /* Authentication required for local device */
tBTM_AUTH_REQ rmt_auth_req; /* Authentication required for peer device */
tBTM_IO_CAP loc_io_caps; /* IO Capabilities of the local device */
tBTM_IO_CAP rmt_io_caps; /* IO Capabilities of the remot device */
} tBTM_SP_CFM_REQ;
/* data type for BTM_SP_KEY_REQ_EVT */
typedef struct {
BD_ADDR bd_addr; /* peer address */
DEV_CLASS dev_class; /* peer CoD */
tBTM_BD_NAME bd_name; /* peer device name */
} tBTM_SP_KEY_REQ;
/* data type for BTM_SP_KEY_NOTIF_EVT */
typedef struct {
BD_ADDR bd_addr; /* peer address */
DEV_CLASS dev_class; /* peer CoD */
tBTM_BD_NAME bd_name; /* peer device name */
UINT32 passkey; /* passkey */
} tBTM_SP_KEY_NOTIF;
enum {
BTM_SP_KEY_STARTED, /* 0 - passkey entry started */
BTM_SP_KEY_ENTERED, /* 1 - passkey digit entered */
BTM_SP_KEY_ERASED, /* 2 - passkey digit erased */
BTM_SP_KEY_CLEARED, /* 3 - passkey cleared */
BTM_SP_KEY_COMPLT, /* 4 - passkey entry completed */
BTM_SP_KEY_OUT_OF_RANGE /* 5 - out of range */
};
typedef UINT8 tBTM_SP_KEY_TYPE;
/* data type for BTM_SP_KEYPRESS_EVT */
typedef struct {
BD_ADDR bd_addr; /* peer address */
tBTM_SP_KEY_TYPE notif_type;
} tBTM_SP_KEYPRESS;
/* data type for BTM_SP_LOC_OOB_EVT */
typedef struct {
tBTM_STATUS status; /* */
BT_OCTET16 c; /* Simple Pairing Hash C */
BT_OCTET16 r; /* Simple Pairing Randomnizer R */
} tBTM_SP_LOC_OOB;
/* data type for BTM_SP_RMT_OOB_EVT */
typedef struct {
BD_ADDR bd_addr; /* peer address */
DEV_CLASS dev_class; /* peer CoD */
tBTM_BD_NAME bd_name; /* peer device name */
} tBTM_SP_RMT_OOB;
/* data type for BTM_SP_COMPLT_EVT */
typedef struct {
BD_ADDR bd_addr; /* peer address */
DEV_CLASS dev_class; /* peer CoD */
tBTM_BD_NAME bd_name; /* peer device name */
tBTM_STATUS status; /* status of the simple pairing process */
} tBTM_SP_COMPLT;
/* data type for BTM_SP_UPGRADE_EVT */
typedef struct {
BD_ADDR bd_addr; /* peer address */
BOOLEAN upgrade; /* TRUE, to upgrade the link key */
} tBTM_SP_UPGRADE;
typedef union {
tBTM_SP_IO_REQ io_req; /* BTM_SP_IO_REQ_EVT */
tBTM_SP_IO_RSP io_rsp; /* BTM_SP_IO_RSP_EVT */
tBTM_SP_CFM_REQ cfm_req; /* BTM_SP_CFM_REQ_EVT */
tBTM_SP_KEY_NOTIF key_notif; /* BTM_SP_KEY_NOTIF_EVT */
tBTM_SP_KEY_REQ key_req; /* BTM_SP_KEY_REQ_EVT */
tBTM_SP_KEYPRESS key_press; /* BTM_SP_KEYPRESS_EVT */
tBTM_SP_LOC_OOB loc_oob; /* BTM_SP_LOC_OOB_EVT */
tBTM_SP_RMT_OOB rmt_oob; /* BTM_SP_RMT_OOB_EVT */
tBTM_SP_COMPLT complt; /* BTM_SP_COMPLT_EVT */
tBTM_SP_UPGRADE upgrade; /* BTM_SP_UPGRADE_EVT */
} tBTM_SP_EVT_DATA;
/* Simple Pairing Events. Called by the stack when Simple Pairing related
** events occur.
*/
typedef UINT8 (tBTM_SP_CALLBACK) (tBTM_SP_EVT event, tBTM_SP_EVT_DATA *p_data);
typedef void (tBTM_MKEY_CALLBACK) (BD_ADDR bd_addr, UINT8 status, UINT8 key_flag) ;
/* Encryption enabled/disabled complete: Optionally passed with BTM_SetEncryption.
** Parameters are
** BD Address of remote
** optional data passed in by BTM_SetEncryption
** tBTM_STATUS - result of the operation
*/
typedef void (tBTM_SEC_CBACK) (BD_ADDR bd_addr, tBT_TRANSPORT transport,
void *p_ref_data, tBTM_STATUS result);
/* Bond Cancel complete. Parameters are
** Result of the cancel operation
**
*/
typedef void (tBTM_BOND_CANCEL_CMPL_CALLBACK) (tBTM_STATUS result);
/* LE related event and data structure
*/
/* relate to ESP_LE_KEY_xxx in esp_gap_ble_api.h */
#if (SMP_INCLUDED == TRUE)
#define BTM_LE_IO_REQ_EVT SMP_IO_CAP_REQ_EVT /* received IO_CAPABILITY_REQUEST event */
#define BTM_LE_SEC_REQUEST_EVT SMP_SEC_REQUEST_EVT /* security request event */
#define BTM_LE_KEY_NOTIF_EVT SMP_PASSKEY_NOTIF_EVT /* received USER_PASSKEY_NOTIFY event */
#define BTM_LE_KEY_REQ_EVT SMP_PASSKEY_REQ_EVT /* received USER_PASSKEY_REQUEST event */
#define BTM_LE_OOB_REQ_EVT SMP_OOB_REQ_EVT /* OOB data request event */
#define BTM_LE_NC_REQ_EVT SMP_NC_REQ_EVT /* Numeric Comparison request event */
#define BTM_LE_PR_KEYPR_NOT_EVT SMP_PEER_KEYPR_NOT_EVT /* Peer keypress notification recd event */
/* SC OOB request event (both local and peer OOB data) can be expected in response */
#define BTM_LE_SC_OOB_REQ_EVT SMP_SC_OOB_REQ_EVT
/* SC OOB local data set is created (as result of SMP_CrLocScOobData(...)) */
#define BTM_LE_SC_LOC_OOB_EVT SMP_SC_LOC_OOB_DATA_UP_EVT
#define BTM_LE_BR_KEYS_REQ_EVT SMP_BR_KEYS_REQ_EVT /* SMP over BR keys request event */
#define BTM_LE_COMPLT_EVT SMP_COMPLT_EVT /* SMP complete event */
#define BTM_LE_LAST_FROM_SMP BTM_LE_BR_KEYS_REQ_EVT
#define BTM_LE_KEY_EVT BTM_LE_LAST_FROM_SMP + 1 /* KEY update event */
#endif ///SMP_INCLUDED == TRUE
typedef UINT8 tBTM_LE_EVT;
#if (BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE)
#define BTM_LE_KEY_NONE 0
#define BTM_LE_KEY_PENC SMP_SEC_KEY_TYPE_ENC /* encryption information of peer device */
#define BTM_LE_KEY_PID SMP_SEC_KEY_TYPE_ID /* identity key of the peer device */
#define BTM_LE_KEY_PCSRK SMP_SEC_KEY_TYPE_CSRK /* peer SRK */
#define BTM_LE_KEY_PLK SMP_SEC_KEY_TYPE_LK
#define BTM_LE_KEY_LLK (SMP_SEC_KEY_TYPE_LK << 4)
#define BTM_LE_KEY_LENC (SMP_SEC_KEY_TYPE_ENC << 4) /* master role security information:div */
#define BTM_LE_KEY_LID (SMP_SEC_KEY_TYPE_ID << 4) /* master device ID key */
#define BTM_LE_KEY_LCSRK (SMP_SEC_KEY_TYPE_CSRK << 4) /* local CSRK has been deliver to peer */
#endif ///BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE
typedef UINT8 tBTM_LE_KEY_TYPE;
/* relate to ESP_LE_AUTH_xxx in esp_gap_ble_api.h */
#if (SMP_INCLUDED == TRUE)
#define BTM_LE_AUTH_REQ_NO_BOND SMP_AUTH_NO_BOND /* 0 */
#define BTM_LE_AUTH_REQ_BOND SMP_AUTH_GEN_BOND /* 1 << 0 */
#define BTM_LE_AUTH_REQ_MITM SMP_AUTH_YN_BIT /* 1 << 2 */
#endif ///SMP_INCLUDED == TRUE
typedef UINT8 tBTM_LE_AUTH_REQ;
#if (SMP_INCLUDED == TRUE)
#define BTM_LE_SC_SUPPORT_BIT SMP_SC_SUPPORT_BIT /* (1 << 3) */
#define BTM_LE_KP_SUPPORT_BIT SMP_KP_SUPPORT_BIT /* (1 << 4) */
#define BTM_LE_AUTH_REQ_SC_ONLY SMP_AUTH_SC_ENC_ONLY /* 1 << 3 */
#define BTM_LE_AUTH_REQ_SC_BOND SMP_AUTH_SC_GB /* 1001 */
#define BTM_LE_AUTH_REQ_SC_MITM SMP_AUTH_SC_MITM_NB /* 1100 */
#define BTM_LE_AUTH_REQ_SC_MITM_BOND SMP_AUTH_SC_MITM_GB /* 1101 */
#define BTM_LE_AUTH_REQ_MASK SMP_AUTH_MASK /* 0x1D */
/* LE security level */
#define BTM_LE_SEC_NONE SMP_SEC_NONE
#define BTM_LE_SEC_UNAUTHENTICATE SMP_SEC_UNAUTHENTICATE /* 1 */
#define BTM_LE_SEC_AUTHENTICATED SMP_SEC_AUTHENTICATED /* 4 */
#endif ///SMP_INCLUDED == TRUE
typedef UINT8 tBTM_LE_SEC;
typedef struct {
tBTM_IO_CAP io_cap; /* local IO capabilities */
UINT8 oob_data; /* OOB data present (locally) for the peer device */
tBTM_LE_AUTH_REQ auth_req; /* Authentication request (for local device) contain bonding and MITM info */
UINT8 max_key_size; /* max encryption key size */
tBTM_LE_KEY_TYPE init_keys; /* keys to be distributed, bit mask */
tBTM_LE_KEY_TYPE resp_keys; /* keys to be distributed, bit mask */
} tBTM_LE_IO_REQ;
#if BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE
/* data type for tBTM_LE_COMPLT */
typedef struct {
UINT8 reason;
UINT8 sec_level;
BOOLEAN is_pair_cancel;
BOOLEAN smp_over_br;
tSMP_AUTH_REQ auth_mode;
} tBTM_LE_COMPLT;
#endif
/* BLE encryption keys */
typedef struct {
BT_OCTET16 ltk;
BT_OCTET8 rand;
UINT16 ediv;
UINT8 sec_level;
UINT8 key_size;
} tBTM_LE_PENC_KEYS;
/* BLE CSRK keys */
typedef struct {
UINT32 counter;
BT_OCTET16 csrk;
UINT8 sec_level;
} tBTM_LE_PCSRK_KEYS;
/* BLE Encryption reproduction keys */
typedef struct {
BT_OCTET16 ltk;
UINT16 div;
UINT8 key_size;
UINT8 sec_level;
} tBTM_LE_LENC_KEYS;
/* BLE SRK keys */
typedef struct {
UINT32 counter;
UINT16 div;
UINT8 sec_level;
BT_OCTET16 csrk;
} tBTM_LE_LCSRK_KEYS;
typedef struct {
BT_OCTET16 irk;
tBLE_ADDR_TYPE addr_type;
BD_ADDR static_addr;
} tBTM_LE_PID_KEYS;
typedef union {
tBTM_LE_PENC_KEYS penc_key; /* received peer encryption key */
tBTM_LE_PCSRK_KEYS pcsrk_key; /* received peer device SRK */
tBTM_LE_PID_KEYS pid_key; /* peer device ID key */
tBTM_LE_LENC_KEYS lenc_key; /* local encryption reproduction keys LTK = = d1(ER,DIV,0)*/
tBTM_LE_LCSRK_KEYS lcsrk_key; /* local device CSRK = d1(ER,DIV,1)*/
} tBTM_LE_KEY_VALUE;
typedef struct {
tBTM_LE_KEY_TYPE key_type;
tBTM_LE_KEY_VALUE *p_key_value;
} tBTM_LE_KEY;
typedef union {
tBTM_LE_IO_REQ io_req; /* BTM_LE_IO_REQ_EVT */
UINT32 key_notif; /* BTM_LE_KEY_NOTIF_EVT */
/* BTM_LE_NC_REQ_EVT */
/* no callback data for BTM_LE_KEY_REQ_EVT */
/* and BTM_LE_OOB_REQ_EVT */
#if BLE_INCLUDED == TRUE && SMP_INCLUDED == TRUE
tBTM_LE_COMPLT complt; /* BTM_LE_COMPLT_EVT */
tSMP_OOB_DATA_TYPE req_oob_type;
#endif
tBTM_LE_KEY key;
} tBTM_LE_EVT_DATA;
/* Simple Pairing Events. Called by the stack when Simple Pairing related
** events occur.
*/
typedef UINT8 (tBTM_LE_CALLBACK) (tBTM_LE_EVT event, BD_ADDR bda, tBTM_LE_EVT_DATA *p_data);
#define BTM_BLE_KEY_TYPE_ID 1
#define BTM_BLE_KEY_TYPE_ER 2
#define BTM_BLE_KEY_TYPE_COUNTER 3 //tobe obsolete
typedef struct {
BT_OCTET16 ir;
BT_OCTET16 irk;
BT_OCTET16 dhk;
} tBTM_BLE_LOCAL_ID_KEYS;
typedef union {
tBTM_BLE_LOCAL_ID_KEYS id_keys;
BT_OCTET16 er;
} tBTM_BLE_LOCAL_KEYS;
/* New LE identity key for local device.
*/
typedef void (tBTM_LE_KEY_CALLBACK) (UINT8 key_type, tBTM_BLE_LOCAL_KEYS *p_key);
/***************************
** Security Manager Types
****************************/
/* Structure that applications use to register with BTM_SecRegister */
typedef struct {
tBTM_AUTHORIZE_CALLBACK *p_authorize_callback;
tBTM_PIN_CALLBACK *p_pin_callback;
tBTM_LINK_KEY_CALLBACK *p_link_key_callback;
tBTM_AUTH_COMPLETE_CALLBACK *p_auth_complete_callback;
tBTM_BOND_CANCEL_CMPL_CALLBACK *p_bond_cancel_cmpl_callback;
tBTM_SP_CALLBACK *p_sp_callback;
#if BLE_INCLUDED == TRUE
#if SMP_INCLUDED == TRUE
tBTM_LE_CALLBACK *p_le_callback;
#endif
tBTM_LE_KEY_CALLBACK *p_le_key_callback;
#endif
} tBTM_APPL_INFO;
/* Callback function for when a link supervision timeout event occurs.
** This asynchronous event is enabled/disabled by calling BTM_RegForLstoEvt().
*/
typedef void (tBTM_LSTO_CBACK) (BD_ADDR remote_bda, UINT16 timeout);
/*****************************************************************************
** POWER MANAGEMENT
*****************************************************************************/
/****************************
** Power Manager Constants
*****************************/
/* BTM Power manager status codes */
enum {
BTM_PM_STS_ACTIVE = HCI_MODE_ACTIVE,
BTM_PM_STS_HOLD = HCI_MODE_HOLD,
BTM_PM_STS_SNIFF = HCI_MODE_SNIFF,
BTM_PM_STS_PARK = HCI_MODE_PARK,
BTM_PM_STS_SSR, /* report the SSR parameters in HCI_SNIFF_SUB_RATE_EVT */
BTM_PM_STS_PENDING, /* when waiting for status from controller */
BTM_PM_STS_ERROR /* when HCI command status returns error */
};
typedef UINT8 tBTM_PM_STATUS;
/* BTM Power manager modes */
enum {
BTM_PM_MD_ACTIVE = BTM_PM_STS_ACTIVE,
BTM_PM_MD_HOLD = BTM_PM_STS_HOLD,
BTM_PM_MD_SNIFF = BTM_PM_STS_SNIFF,
BTM_PM_MD_PARK = BTM_PM_STS_PARK,
BTM_PM_MD_FORCE = 0x10 /* OR this to force ACL link to a certain mode */
};
typedef UINT8 tBTM_PM_MODE;
#define BTM_PM_SET_ONLY_ID 0x80
/* Operation codes */
#define BTM_PM_REG_SET 1 /* The module wants to set the desired power mode */
#define BTM_PM_REG_NOTIF 2 /* The module wants to receive mode change event */
#define BTM_PM_DEREG 4 /* The module does not want to involve with PM anymore */
/************************
** Power Manager Types
*************************/
typedef struct {
UINT16 max;
UINT16 min;
UINT16 attempt;
UINT16 timeout;
tBTM_PM_MODE mode;
} tBTM_PM_PWR_MD;
/*************************************
** Power Manager Callback Functions
**************************************/
typedef void (tBTM_PM_STATUS_CBACK) (BD_ADDR p_bda, tBTM_PM_STATUS status,
UINT16 value, UINT8 hci_status);
/************************
** Stored Linkkey Types
*************************/
#define BTM_CB_EVT_DELETE_STORED_LINK_KEYS 4
typedef struct {
UINT8 event;
UINT8 status;
UINT16 num_keys;
} tBTM_DELETE_STORED_LINK_KEY_COMPLETE;
/* MIP evnets, callbacks */
enum {
BTM_MIP_MODE_CHG_EVT,
BTM_MIP_DISCONNECT_EVT,
BTM_MIP_PKTS_COMPL_EVT,
BTM_MIP_RXDATA_EVT
};
typedef UINT8 tBTM_MIP_EVT;
typedef struct {
tBTM_MIP_EVT event;
BD_ADDR bd_addr;
UINT16 mip_id;
} tBTM_MIP_MODE_CHANGE;
typedef struct {
tBTM_MIP_EVT event;
UINT16 mip_id;
UINT8 disc_reason;
} tBTM_MIP_CONN_TIMEOUT;
#define BTM_MIP_MAX_RX_LEN 17
typedef struct {
tBTM_MIP_EVT event;
UINT16 mip_id;
UINT8 rx_len;
UINT8 rx_data[BTM_MIP_MAX_RX_LEN];
} tBTM_MIP_RXDATA;
typedef struct {
tBTM_MIP_EVT event;
BD_ADDR bd_addr;
UINT8 data[11]; /* data[0] shows Vender-specific device type */
} tBTM_MIP_EIR_HANDSHAKE;
typedef struct {
tBTM_MIP_EVT event;
UINT16 num_sent; /* Number of packets completed at the controller */
} tBTM_MIP_PKTS_COMPL;
typedef union {
tBTM_MIP_EVT event;
tBTM_MIP_MODE_CHANGE mod_chg;
tBTM_MIP_CONN_TIMEOUT conn_tmo;
tBTM_MIP_EIR_HANDSHAKE eir;
tBTM_MIP_PKTS_COMPL completed;
tBTM_MIP_RXDATA rxdata;
} tBTM_MIP_EVENT_DATA;
/* MIP event callback function */
typedef void (tBTM_MIP_EVENTS_CB) (tBTM_MIP_EVT event, tBTM_MIP_EVENT_DATA data);
/* MIP Device query callback function */
typedef BOOLEAN (tBTM_MIP_QUERY_CB) (BD_ADDR dev_addr, UINT8 *p_mode, LINK_KEY link_key);
#define BTM_CONTRL_ACTIVE 1 /* ACL link on, SCO link ongoing, sniff mode */
#define BTM_CONTRL_SCAN 2 /* Scan state - paging/inquiry/trying to connect*/
#define BTM_CONTRL_IDLE 3 /* Idle state - page scan, LE advt, inquiry scan */
typedef UINT8 tBTM_CONTRL_STATE;
/*****************************************************************************
** EXTERNAL FUNCTION DECLARATIONS
*****************************************************************************/
/*
#ifdef __cplusplus
extern "C" {
#endif
*/
/*****************************************************************************
** DEVICE CONTROL and COMMON FUNCTIONS
*****************************************************************************/
/*******************************************************************************
**
** Function BTM_DeviceReset
**
** Description This function is called to reset the controller.The Callback function
** if provided is called when startup of the device has
** completed.
**
** Returns void
**
*******************************************************************************/
//extern
void BTM_DeviceReset (tBTM_CMPL_CB *p_cb);
/*******************************************************************************
**
** Function BTM_IsDeviceUp
**
** Description This function is called to check if the device is up.
**
** Returns TRUE if device is up, else FALSE
**
*******************************************************************************/
//extern
BOOLEAN BTM_IsDeviceUp (void);
/*******************************************************************************
**
** Function BTM_SetLocalDeviceName
**
** Description This function is called to set the local device name.
**
** Returns BTM_CMD_STARTED if successful, otherwise an error
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_SetLocalDeviceName (char *p_name);
/*******************************************************************************
**
** Function BTM_SetDeviceClass
**
** Description This function is called to set the local device class
**
** Returns BTM_SUCCESS if successful, otherwise an error
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_SetDeviceClass (DEV_CLASS dev_class);
/*******************************************************************************
**
** Function BTM_ReadLocalDeviceName
**
** Description This function is called to read the local device name.
**
** Returns status of the operation
** If success, BTM_SUCCESS is returned and p_name points stored
** local device name
** If BTM doesn't store local device name, BTM_NO_RESOURCES is
** is returned and p_name is set to NULL
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_ReadLocalDeviceName (char **p_name);
/*******************************************************************************
**
** Function BTM_ReadLocalDeviceNameFromController
**
** Description Get local device name from controller. Do not use cached
** name (used to get chip-id prior to btm reset complete).
**
** Returns BTM_CMD_STARTED if successful, otherwise an error
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_ReadLocalDeviceNameFromController (tBTM_CMPL_CB *p_rln_cmpl_cback);
/*******************************************************************************
**
** Function BTM_ReadDeviceClass
**
** Description This function is called to read the local device class
**
** Returns pointer to the device class
**
*******************************************************************************/
//extern
UINT8 *BTM_ReadDeviceClass (void);
/*******************************************************************************
**
** Function BTM_ReadLocalFeatures
**
** Description This function is called to read the local features
**
** Returns pointer to the local features string
**
*******************************************************************************/
//extern
UINT8 *BTM_ReadLocalFeatures (void);
/*******************************************************************************
**
** Function BTM_RegisterForDeviceStatusNotif
**
** Description This function is called to register for device status
** change notifications.
**
** Returns pointer to previous caller's callback function or NULL if first
** registration.
**
*******************************************************************************/
//extern
tBTM_DEV_STATUS_CB *BTM_RegisterForDeviceStatusNotif (tBTM_DEV_STATUS_CB *p_cb);
/*******************************************************************************
**
** Function BTM_RegisterForVSEvents
**
** Description This function is called to register/deregister for vendor
** specific HCI events.
**
** If is_register=TRUE, then the function will be registered;
** if is_register=FALSE, then the function will be deregistered.
**
** Returns BTM_SUCCESS if successful,
** BTM_BUSY if maximum number of callbacks have already been
** registered.
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_RegisterForVSEvents (tBTM_VS_EVT_CB *p_cb, BOOLEAN is_register);
/*******************************************************************************
**
** Function BTM_VendorSpecificCommand
**
** Description Send a vendor specific HCI command to the controller.
**
** Returns
** BTM_SUCCESS Command sent. Does not expect command complete
** event. (command cmpl callback param is NULL)
** BTM_CMD_STARTED Command sent. Waiting for command cmpl event.
** BTM_BUSY Command not sent. Waiting for cmd cmpl event for
** prior command.
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_VendorSpecificCommand(UINT16 opcode,
UINT8 param_len,
UINT8 *p_param_buf,
tBTM_VSC_CMPL_CB *p_cb);
/*******************************************************************************
**
** Function BTM_AllocateSCN
**
** Description Look through the Server Channel Numbers for a free one to be
** used with an RFCOMM connection.
**
** Returns Allocated SCN number or 0 if none.
**
*******************************************************************************/
//extern
#if (CLASSIC_BT_INCLUDED == TRUE)
UINT8 BTM_AllocateSCN(void);
// btla-specific ++
/*******************************************************************************
**
** Function BTM_TryAllocateSCN
**
** Description Try to allocate a fixed server channel
**
** Returns Returns TRUE if server channel was available
**
*******************************************************************************/
//extern
BOOLEAN BTM_TryAllocateSCN(UINT8 scn);
// btla-specific --
/*******************************************************************************
**
** Function BTM_FreeSCN
**
** Description Free the specified SCN.
**
** Returns TRUE if successful, FALSE if SCN is not in use or invalid
**
*******************************************************************************/
//extern
BOOLEAN BTM_FreeSCN(UINT8 scn);
#endif ///CLASSIC_BT_INCLUDED == TRUE
/*******************************************************************************
**
** Function BTM_SetTraceLevel
**
** Description This function sets the trace level for BTM. If called with
** a value of 0xFF, it simply returns the current trace level.
**
** Returns The new or current trace level
**
*******************************************************************************/
//extern
UINT8 BTM_SetTraceLevel (UINT8 new_level);
/*******************************************************************************
**
** Function BTM_WritePageTimeout
**
** Description Send HCI Wite Page Timeout.
**
** Returns
** BTM_SUCCESS Command sent.
** BTM_NO_RESOURCES If out of resources to send the command.
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_WritePageTimeout(UINT16 timeout);
/*******************************************************************************
**
** Function BTM_WriteVoiceSettings
**
** Description Send HCI Write Voice Settings command.
** See stack/hcidefs.h for settings bitmask values.
**
** Returns
** BTM_SUCCESS Command sent.
** BTM_NO_RESOURCES If out of resources to send the command.
**
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_WriteVoiceSettings(UINT16 settings);
/*******************************************************************************
**
** Function BTM_EnableTestMode
**
** Description Send HCI the enable device under test command.
**
** Note: Controller can only be taken out of this mode by
** resetting the controller.
**
** Returns
** BTM_SUCCESS Command sent.
** BTM_NO_RESOURCES If out of resources to send the command.
**
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_EnableTestMode(void);
/*****************************************************************************
** DEVICE DISCOVERY FUNCTIONS - Inquiry, Remote Name, Discovery, Class of Device
*****************************************************************************/
/*******************************************************************************
**
** Function BTM_SetDiscoverability
**
** Description This function is called to set the device into or out of
** discoverable mode. Discoverable mode means inquiry
** scans are enabled. If a value of '0' is entered for window or
** interval, the default values are used.
**
** Returns BTM_SUCCESS if successful
** BTM_BUSY if a setting of the filter is already in progress
** BTM_NO_RESOURCES if couldn't get a memory pool buffer
** BTM_ILLEGAL_VALUE if a bad parameter was detected
** BTM_WRONG_MODE if the device is not up.
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_SetDiscoverability (UINT16 inq_mode, UINT16 window,
UINT16 interval);
/*******************************************************************************
**
** Function BTM_ReadDiscoverability
**
** Description This function is called to read the current discoverability
** mode of the device.
**
** Output Params: p_window - current inquiry scan duration
** p_interval - current inquiry scan interval
**
** Returns BTM_NON_DISCOVERABLE, BTM_LIMITED_DISCOVERABLE, or
** BTM_GENERAL_DISCOVERABLE
**
*******************************************************************************/
//extern
UINT16 BTM_ReadDiscoverability (UINT16 *p_window,
UINT16 *p_interval);
/*******************************************************************************
**
** Function BTM_SetPeriodicInquiryMode
**
** Description This function is called to set the device periodic inquiry mode.
** If the duration is zero, the periodic inquiry mode is cancelled.
**
** Parameters: p_inqparms - pointer to the inquiry information
** mode - GENERAL or LIMITED inquiry
** duration - length in 1.28 sec intervals (If '0', the inquiry is CANCELLED)
** max_resps - maximum amount of devices to search for before ending the inquiry
** filter_cond_type - BTM_CLR_INQUIRY_FILTER, BTM_FILTER_COND_DEVICE_CLASS, or
** BTM_FILTER_COND_BD_ADDR
** filter_cond - value for the filter (based on filter_cond_type)
**
** max_delay - maximum amount of time between successive inquiries
** min_delay - minimum amount of time between successive inquiries
** p_results_cb - callback returning pointer to results (tBTM_INQ_RESULTS)
**
** Returns BTM_CMD_STARTED if successfully started
** BTM_ILLEGAL_VALUE if a bad parameter is detected
** BTM_NO_RESOURCES if could not allocate a message buffer
** BTM_SUCCESS - if cancelling the periodic inquiry
** BTM_BUSY - if an inquiry is already active
** BTM_WRONG_MODE if the device is not up.
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_SetPeriodicInquiryMode (tBTM_INQ_PARMS *p_inqparms,
UINT16 max_delay, UINT16 min_delay,
tBTM_INQ_RESULTS_CB *p_results_cb);
/*******************************************************************************
**
** Function BTM_StartInquiry
**
** Description This function is called to start an inquiry.
**
** Parameters: p_inqparms - pointer to the inquiry information
** mode - GENERAL or LIMITED inquiry
** duration - length in 1.28 sec intervals (If '0', the inquiry is CANCELLED)
** max_resps - maximum amount of devices to search for before ending the inquiry
** filter_cond_type - BTM_CLR_INQUIRY_FILTER, BTM_FILTER_COND_DEVICE_CLASS, or
** BTM_FILTER_COND_BD_ADDR
** filter_cond - value for the filter (based on filter_cond_type)
**
** p_results_cb - Pointer to the callback routine which gets called
** upon receipt of an inquiry result. If this field is
** NULL, the application is not notified.
**
** p_cmpl_cb - Pointer to the callback routine which gets called
** upon completion. If this field is NULL, the
** application is not notified when completed.
** Returns tBTM_STATUS
** BTM_CMD_STARTED if successfully initiated
** BTM_BUSY if already in progress
** BTM_ILLEGAL_VALUE if parameter(s) are out of range
** BTM_NO_RESOURCES if could not allocate resources to start the command
** BTM_WRONG_MODE if the device is not up.
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_StartInquiry (tBTM_INQ_PARMS *p_inqparms,
tBTM_INQ_RESULTS_CB *p_results_cb,
tBTM_CMPL_CB *p_cmpl_cb);
/*******************************************************************************
**
** Function BTM_IsInquiryActive
**
** Description This function returns a bit mask of the current inquiry state
**
** Returns BTM_INQUIRY_INACTIVE if inactive (0)
** BTM_LIMITED_INQUIRY_ACTIVE if a limted inquiry is active
** BTM_GENERAL_INQUIRY_ACTIVE if a general inquiry is active
** BTM_PERIODIC_INQUIRY_ACTIVE if a periodic inquiry is active
**
*******************************************************************************/
//extern
UINT16 BTM_IsInquiryActive (void);
/*******************************************************************************
**
** Function BTM_CancelInquiry
**
** Description This function cancels an inquiry if active
**
** Returns BTM_SUCCESS if successful
** BTM_NO_RESOURCES if could not allocate a message buffer
** BTM_WRONG_MODE if the device is not up.
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_CancelInquiry(void);
/*******************************************************************************
**
** Function BTM_CancelPeriodicInquiry
**
** Description This function cancels a periodic inquiry
**
** Returns
** BTM_NO_RESOURCES if could not allocate a message buffer
** BTM_SUCCESS - if cancelling the periodic inquiry
** BTM_WRONG_MODE if the device is not up.
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_CancelPeriodicInquiry(void);
/*******************************************************************************
**
** Function BTM_SetConnectability
**
** Description This function is called to set the device into or out of
** connectable mode. Discoverable mode means page scans enabled.
**
** Returns BTM_SUCCESS if successful
** BTM_ILLEGAL_VALUE if a bad parameter is detected
** BTM_NO_RESOURCES if could not allocate a message buffer
** BTM_WRONG_MODE if the device is not up.
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_SetConnectability (UINT16 page_mode, UINT16 window,
UINT16 interval);
/*******************************************************************************
**
** Function BTM_ReadConnectability
**
** Description This function is called to read the current discoverability
** mode of the device.
** Output Params p_window - current page scan duration
** p_interval - current time between page scans
**
** Returns BTM_NON_CONNECTABLE or BTM_CONNECTABLE
**
*******************************************************************************/
//extern
UINT16 BTM_ReadConnectability (UINT16 *p_window, UINT16 *p_interval);
/*******************************************************************************
**
** Function BTM_SetInquiryMode
**
** Description This function is called to set standard, with RSSI
** mode or extended of the inquiry for local device.
**
** Input Params: BTM_INQ_RESULT_STANDARD, BTM_INQ_RESULT_WITH_RSSI or
** BTM_INQ_RESULT_EXTENDED
**
** Returns BTM_SUCCESS if successful
** BTM_NO_RESOURCES if couldn't get a memory pool buffer
** BTM_ILLEGAL_VALUE if a bad parameter was detected
** BTM_WRONG_MODE if the device is not up.
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_SetInquiryMode (UINT8 mode);
/*******************************************************************************
**
** Function BTM_SetInquiryScanType
**
** Description This function is called to set the iquiry scan-type to
** standard or interlaced.
**
** Input Params: BTM_SCAN_TYPE_STANDARD or BTM_SCAN_TYPE_INTERLACED
**
** Returns BTM_SUCCESS if successful
** BTM_MODE_UNSUPPORTED if not a 1.2 device
** BTM_WRONG_MODE if the device is not up.
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_SetInquiryScanType (UINT16 scan_type);
/*******************************************************************************
**
** Function BTM_SetPageScanType
**
** Description This function is called to set the page scan-type to
** standard or interlaced.
**
** Input Params: BTM_SCAN_TYPE_STANDARD or BTM_SCAN_TYPE_INTERLACED
**
** Returns BTM_SUCCESS if successful
** BTM_MODE_UNSUPPORTED if not a 1.2 device
** BTM_WRONG_MODE if the device is not up.
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_SetPageScanType (UINT16 scan_type);
/*******************************************************************************
**
** Function BTM_ReadRemoteDeviceName
**
** Description This function initiates a remote device HCI command to the
** controller and calls the callback when the process has completed.
**
** Input Params: remote_bda - device address of name to retrieve
** p_cb - callback function called when BTM_CMD_STARTED
** is returned.
** A pointer to tBTM_REMOTE_DEV_NAME is passed to the
** callback.
**
** Returns
** BTM_CMD_STARTED is returned if the request was successfully sent
** to HCI.
** BTM_BUSY if already in progress
** BTM_UNKNOWN_ADDR if device address is bad
** BTM_NO_RESOURCES if could not allocate resources to start the command
** BTM_WRONG_MODE if the device is not up.
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_ReadRemoteDeviceName (BD_ADDR remote_bda,
tBTM_CMPL_CB *p_cb,
tBT_TRANSPORT transport);
/*******************************************************************************
**
** Function BTM_CancelRemoteDeviceName
**
** Description This function initiates the cancel request for the specified
** remote device.
**
** Input Params: None
**
** Returns
** BTM_CMD_STARTED is returned if the request was successfully sent
** to HCI.
** BTM_NO_RESOURCES if could not allocate resources to start the command
** BTM_WRONG_MODE if there is not an active remote name request.
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_CancelRemoteDeviceName (void);
/*******************************************************************************
**
** Function BTM_ReadRemoteVersion
**
** Description This function is called to read a remote device's version
**
** Returns BTM_SUCCESS if successful, otherwise an error
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_ReadRemoteVersion (BD_ADDR addr,
UINT8 *lmp_version,
UINT16 *manufacturer,
UINT16 *lmp_sub_version);
/*******************************************************************************
**
** Function BTM_ReadRemoteFeatures
**
** Description This function is called to read a remote device's
** supported features mask (features mask located at page 0)
**
** Note: The size of device features mask page is
** BTM_FEATURE_BYTES_PER_PAGE bytes.
**
** Returns pointer to the remote supported features mask
**
*******************************************************************************/
//extern
UINT8 *BTM_ReadRemoteFeatures (BD_ADDR addr);
/*******************************************************************************
**
** Function BTM_ReadRemoteExtendedFeatures
**
** Description This function is called to read a specific extended features
** page of the remote device
**
** Note1: The size of device features mask page is
** BTM_FEATURE_BYTES_PER_PAGE bytes.
** Note2: The valid device features mask page number depends on
** the remote device capabilities. It is expected to be in the
** range [0 - BTM_EXT_FEATURES_PAGE_MAX].
** Returns pointer to the remote extended features mask
** or NULL if page_number is not valid
**
*******************************************************************************/
//extern
UINT8 *BTM_ReadRemoteExtendedFeatures (BD_ADDR addr, UINT8 page_number);
/*******************************************************************************
**
** Function BTM_ReadNumberRemoteFeaturesPages
**
** Description This function is called to retrieve the number of feature pages
** read from the remote device
**
** Returns number of features pages read from the remote device
**
*******************************************************************************/
//extern
UINT8 BTM_ReadNumberRemoteFeaturesPages (BD_ADDR addr);
/*******************************************************************************
**
** Function BTM_ReadAllRemoteFeatures
**
** Description This function is called to read all features of the remote device
**
** Returns pointer to the byte[0] of the page[0] of the remote device
** feature mask.
**
** Note: the function returns the pointer to the array of the size
** BTM_FEATURE_BYTES_PER_PAGE * (BTM_EXT_FEATURES_PAGE_MAX + 1).
**
*******************************************************************************/
//extern
UINT8 *BTM_ReadAllRemoteFeatures (BD_ADDR addr);
/*******************************************************************************
**
** Function BTM_InqDbRead
**
** Description This function looks through the inquiry database for a match
** based on Bluetooth Device Address. This is the application's
** interface to get the inquiry details of a specific BD address.
**
** Returns pointer to entry, or NULL if not found
**
*******************************************************************************/
//extern
tBTM_INQ_INFO *BTM_InqDbRead (BD_ADDR p_bda);
/*******************************************************************************
**
** Function BTM_InqDbFirst
**
** Description This function looks through the inquiry database for the first
** used entry, and returns that. This is used in conjunction with
** BTM_InqDbNext by applications as a way to walk through the
** inquiry database.
**
** Returns pointer to first in-use entry, or NULL if DB is empty
**
*******************************************************************************/
//extern
tBTM_INQ_INFO *BTM_InqDbFirst (void);
/*******************************************************************************
**
** Function BTM_InqDbNext
**
** Description This function looks through the inquiry database for the next
** used entry, and returns that. If the input parameter is NULL,
** the first entry is returned.
**
** Returns pointer to next in-use entry, or NULL if no more found.
**
*******************************************************************************/
//extern
tBTM_INQ_INFO *BTM_InqDbNext (tBTM_INQ_INFO *p_cur);
/*******************************************************************************
**
** Function BTM_ClearInqDb
**
** Description This function is called to clear out a device or all devices
** from the inquiry database.
**
** Parameter p_bda - (input) BD_ADDR -> Address of device to clear
** (NULL clears all entries)
**
** Returns BTM_BUSY if an inquiry, get remote name, or event filter
** is active, otherwise BTM_SUCCESS
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_ClearInqDb (BD_ADDR p_bda);
/*******************************************************************************
**
** Function BTM_ReadInquiryRspTxPower
**
** Description This command will read the inquiry Transmit Power level used
** to transmit the FHS and EIR data packets.
** This can be used directly in the Tx Power Level EIR data type.
**
** Returns BTM_SUCCESS if successful
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_ReadInquiryRspTxPower (tBTM_CMPL_CB *p_cb);
#if SDP_INCLUDED == TRUE
/*******************************************************************************
**
** Function BTM_StartDiscovery
**
** Description This function is called by an application (or profile)
** when it wants to trigger an service discovery using the
** BTM's discovery database.
**
** Returns tBTM_STATUS
** BTM_CMD_STARTED if the discovery was initiated
** BTM_BUSY if one is already in progress
** BTM_UNKNOWN_ADDR if no addresses are in the INQ DB
** BTM_ERR_PROCESSING if err initiating the command
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_StartDiscovery (tBTM_CMPL_CB *p_cmpl_cb,
BD_ADDR_PTR p_rem_addr);
/*******************************************************************************
**
** Function BTM_FindAttribute
**
** Description This function is called by an application (or profile)
** when it wants to see if an attribute exists in the BTM
** discovery database.
**
** Returns Pointer to matching record, or NULL
**
*******************************************************************************/
//extern
tSDP_DISC_REC *BTM_FindAttribute (UINT16 attr_id,
tSDP_DISC_REC *p_start_rec);
/*******************************************************************************
**
** Function BTM_FindService
**
** Description This function is called by an application (or profile)
** when it wants to see if a service exists in the BTM
** discovery database.
**
** Returns Pointer to matching record, or NULL
**
*******************************************************************************/
//extern
tSDP_DISC_REC *BTM_FindService (UINT16 service_uuid,
tSDP_DISC_REC *p_start_rec);
/*******************************************************************************
**
** Function BTM_SetDiscoveryParams
**
** Description This function is called to set the BTM default discovery parameters.
** These UUID and attribute filters are used during the call to
** BTM_StartDiscovery.
**
** Returns void
**
*******************************************************************************/
//extern
void BTM_SetDiscoveryParams (UINT16 num_uuid, tSDP_UUID *p_uuid_list,
UINT16 num_attr, UINT16 *p_attr_list);
#endif /*SDP_INCLUDED*/
/*****************************************************************************
** ACL CHANNEL MANAGEMENT FUNCTIONS
*****************************************************************************/
/*******************************************************************************
**
** Function BTM_SetLinkPolicy
**
** Description Create and send HCI "Write Policy Set" command
**
** Returns BTM_CMD_STARTED if successfully initiated, otherwise error
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_SetLinkPolicy (BD_ADDR remote_bda,
UINT16 *settings);
/*******************************************************************************
**
** Function BTM_SetDefaultLinkPolicy
**
** Description Set the default value for HCI "Write Policy Set" command
** to use when an ACL link is created.
**
** Returns void
**
*******************************************************************************/
//extern
void BTM_SetDefaultLinkPolicy (UINT16 settings);
/*******************************************************************************
**
** Function BTM_SetDefaultLinkSuperTout
**
** Description Set the default value for HCI "Write Link Supervision Timeout"
** command to use when an ACL link is created.
**
** Returns void
**
*******************************************************************************/
//extern
void BTM_SetDefaultLinkSuperTout (UINT16 timeout);
/*******************************************************************************
**
** Function BTM_SetLinkSuperTout
**
** Description Create and send HCI "Write Link Supervision Timeout" command
**
** Returns BTM_CMD_STARTED if successfully initiated, otherwise error
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_SetLinkSuperTout (BD_ADDR remote_bda,
UINT16 timeout);
/*******************************************************************************
**
** Function BTM_GetLinkSuperTout
**
** Description Read the link supervision timeout value of the connection
**
** Returns status of the operation
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_GetLinkSuperTout (BD_ADDR remote_bda,
UINT16 *p_timeout);
/*******************************************************************************
**
** Function BTM_IsAclConnectionUp
**
** Description This function is called to check if an ACL connection exists
** to a specific remote BD Address.
**
** Returns TRUE if connection is up, else FALSE.
**
*******************************************************************************/
//extern
BOOLEAN BTM_IsAclConnectionUp (BD_ADDR remote_bda, tBT_TRANSPORT transport);
/*******************************************************************************
**
** Function BTM_GetRole
**
** Description This function is called to get the role of the local device
** for the ACL connection with the specified remote device
**
** Returns BTM_SUCCESS if connection exists.
** BTM_UNKNOWN_ADDR if no active link with bd addr specified
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_GetRole (BD_ADDR remote_bd_addr, UINT8 *p_role);
/*******************************************************************************
**
** Function BTM_SwitchRole
**
** Description This function is called to switch role between master and
** slave. If role is already set it will do nothing. If the
** command was initiated, the callback function is called upon
** completion.
**
** Returns BTM_SUCCESS if already in specified role.
** BTM_CMD_STARTED if command issued to controller.
** BTM_NO_RESOURCES if couldn't allocate memory to issue command
** BTM_UNKNOWN_ADDR if no active link with bd addr specified
** BTM_MODE_UNSUPPORTED if local device does not support role switching
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_SwitchRole (BD_ADDR remote_bd_addr,
UINT8 new_role,
tBTM_CMPL_CB *p_cb);
/*******************************************************************************
**
** Function BTM_ReadRSSI
**
** Description This function is called to read the RSSI for a particular transport.
** The RSSI of results are returned in the callback.
** (tBTM_RSSI_RESULTS)
**
** Returns BTM_CMD_STARTED if command issued to controller.
** BTM_NO_RESOURCES if couldn't allocate memory to issue command
** BTM_UNKNOWN_ADDR if no active link with bd addr specified
** BTM_BUSY if command is already in progress
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_ReadRSSI (BD_ADDR remote_bda, tBT_TRANSPORT transport, tBTM_CMPL_CB *p_cb);
/*******************************************************************************
**
** Function BTM_ReadTxPower
**
** Description This function is called to read the current connection
** TX power of the connection. The TX power level results
** are returned in the callback.
** (tBTM_RSSI_RESULTS)
**
** Returns BTM_CMD_STARTED if command issued to controller.
** BTM_NO_RESOURCES if couldn't allocate memory to issue command
** BTM_UNKNOWN_ADDR if no active link with bd addr specified
** BTM_BUSY if command is already in progress
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_ReadTxPower (BD_ADDR remote_bda,
tBT_TRANSPORT transport, tBTM_CMPL_CB *p_cb);
tBTM_STATUS BTM_BleReadAdvTxPower(tBTM_CMPL_CB *p_cb);
void BTM_BleGetWhiteListSize(uint16_t *length);
/*******************************************************************************
**
** Function BTM_ReadLinkQuality
**
** Description This function is called to read the link quality.
** The value of the link quality is returned in the callback.
** (tBTM_LINK_QUALITY_RESULTS)
**
** Returns BTM_CMD_STARTED if command issued to controller.
** BTM_NO_RESOURCES if couldn't allocate memory to issue command
** BTM_UNKNOWN_ADDR if no active link with bd addr specified
** BTM_BUSY if command is already in progress
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_ReadLinkQuality (BD_ADDR remote_bda, tBTM_CMPL_CB *p_cb);
/*******************************************************************************
**
** Function BTM_RegBusyLevelNotif
**
** Description This function is called to register a callback to receive
** busy level change events.
**
** Returns BTM_SUCCESS if successfully registered, otherwise error
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_RegBusyLevelNotif (tBTM_BL_CHANGE_CB *p_cb, UINT8 *p_level,
tBTM_BL_EVENT_MASK evt_mask);
/*******************************************************************************
**
** Function BTM_AclRegisterForChanges
**
** Description This function is called to register a callback to receive
** ACL database change events, i.e. new connection or removed.
**
** Returns BTM_SUCCESS if successfully initiated, otherwise error
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_AclRegisterForChanges (tBTM_ACL_DB_CHANGE_CB *p_cb);
/*******************************************************************************
**
** Function BTM_GetNumAclLinks
**
** Description This function is called to count the number of
** ACL links that are active.
**
** Returns UINT16 Number of active ACL links
**
*******************************************************************************/
//extern
UINT16 BTM_GetNumAclLinks (void);
/*******************************************************************************
**
** Function BTM_SetQoS
**
** Description This function is called to setup QoS
**
** Returns BTM_CMD_STARTED if successfully initiated, otherwise error
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_SetQoS(BD_ADDR bd, FLOW_SPEC *p_flow,
tBTM_CMPL_CB *p_cb);
/*****************************************************************************
** (e)SCO CHANNEL MANAGEMENT FUNCTIONS
*****************************************************************************/
/*******************************************************************************
**
** Function BTM_CreateSco
**
** Description This function is called to create an SCO connection. If the
** "is_orig" flag is TRUE, the connection will be originated,
** otherwise BTM will wait for the other side to connect.
**
** Returns BTM_UNKNOWN_ADDR if the ACL connection is not up
** BTM_BUSY if another SCO being set up to
** the same BD address
** BTM_NO_RESOURCES if the max SCO limit has been reached
** BTM_CMD_STARTED if the connection establishment is started.
** In this case, "*p_sco_inx" is filled in
** with the sco index used for the connection.
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_CreateSco (BD_ADDR remote_bda, BOOLEAN is_orig,
UINT16 pkt_types, UINT16 *p_sco_inx,
tBTM_SCO_CB *p_conn_cb,
tBTM_SCO_CB *p_disc_cb);
/*******************************************************************************
**
** Function BTM_RemoveSco
**
** Description This function is called to remove a specific SCO connection.
**
** Returns BTM_CMD_STARTED if successfully initiated, otherwise error
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_RemoveSco (UINT16 sco_inx);
/*******************************************************************************
**
** Function BTM_SetScoPacketTypes
**
** Description This function is called to set the packet types used for
** a specific SCO connection,
**
** Parameters pkt_types - One or more of the following
** BTM_SCO_PKT_TYPES_MASK_HV1
** BTM_SCO_PKT_TYPES_MASK_HV2
** BTM_SCO_PKT_TYPES_MASK_HV3
** BTM_SCO_PKT_TYPES_MASK_EV3
** BTM_SCO_PKT_TYPES_MASK_EV4
** BTM_SCO_PKT_TYPES_MASK_EV5
**
** BTM_SCO_LINK_ALL_MASK - enables all supported types
**
** Returns BTM_CMD_STARTED if successfully initiated, otherwise error
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_SetScoPacketTypes (UINT16 sco_inx, UINT16 pkt_types);
/*******************************************************************************
**
** Function BTM_ReadScoPacketTypes
**
** Description This function is read the packet types used for a specific
** SCO connection.
**
** Returns One or more of the following (bitmask)
** BTM_SCO_PKT_TYPES_MASK_HV1
** BTM_SCO_PKT_TYPES_MASK_HV2
** BTM_SCO_PKT_TYPES_MASK_HV3
** BTM_SCO_PKT_TYPES_MASK_EV3
** BTM_SCO_PKT_TYPES_MASK_EV4
** BTM_SCO_PKT_TYPES_MASK_EV5
**
** Returns packet types supported for the connection
**
*******************************************************************************/
//extern
UINT16 BTM_ReadScoPacketTypes (UINT16 sco_inx);
/*******************************************************************************
**
** Function BTM_ReadDeviceScoPacketTypes
**
** Description This function is read the SCO packet types that
** the device supports.
**
** Returns packet types supported by the device.
**
*******************************************************************************/
//extern
UINT16 BTM_ReadDeviceScoPacketTypes (void);
/*******************************************************************************
**
** Function BTM_ReadScoHandle
**
** Description This function is used to read the HCI handle used for a specific
** SCO connection,
**
** Returns handle for the connection, or 0xFFFF if invalid SCO index.
**
*******************************************************************************/
//extern
UINT16 BTM_ReadScoHandle (UINT16 sco_inx);
/*******************************************************************************
**
** Function BTM_ReadScoBdAddr
**
** Description This function is read the remote BD Address for a specific
** SCO connection,
**
** Returns pointer to BD address or NULL if not known
**
*******************************************************************************/
//extern
UINT8 *BTM_ReadScoBdAddr (UINT16 sco_inx);
/*******************************************************************************
**
** Function BTM_ReadScoDiscReason
**
** Description This function is returns the reason why an (e)SCO connection
** has been removed. It contains the value until read, or until
** another (e)SCO connection has disconnected.
**
** Returns HCI reason or BTM_INVALID_SCO_DISC_REASON if not set.
**
*******************************************************************************/
//extern
UINT16 BTM_ReadScoDiscReason (void);
/*******************************************************************************
**
** Function BTM_SetEScoMode
**
** Description This function sets up the negotiated parameters for SCO or
** eSCO, and sets as the default mode used for calls to
** BTM_CreateSco. It can be called only when there are no
** active (e)SCO links.
**
** Returns BTM_SUCCESS if the successful.
** BTM_BUSY if there are one or more active (e)SCO links.
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_SetEScoMode (tBTM_SCO_TYPE sco_mode,
tBTM_ESCO_PARAMS *p_parms);
/*******************************************************************************
**
** Function BTM_SetWBSCodec
**
** Description This function sends command to the controller to setup
** WBS codec for the upcoming eSCO connection.
**
** Returns BTM_SUCCESS.
**
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_SetWBSCodec (tBTM_SCO_CODEC_TYPE codec_type);
/*******************************************************************************
**
** Function BTM_RegForEScoEvts
**
** Description This function registers a SCO event callback with the
** specified instance. It should be used to received
** connection indication events and change of link parameter
** events.
**
** Returns BTM_SUCCESS if the successful.
** BTM_ILLEGAL_VALUE if there is an illegal sco_inx
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_RegForEScoEvts (UINT16 sco_inx,
tBTM_ESCO_CBACK *p_esco_cback);
/*******************************************************************************
**
** Function BTM_ReadEScoLinkParms
**
** Description This function returns the current eSCO link parameters for
** the specified handle. This can be called anytime a connection
** is active, but is typically called after receiving the SCO
** opened callback.
**
** Note: If called over a 1.1 controller, only the packet types
** field has meaning.
** Note: If the upper layer doesn't know the current sco index,
** BTM_FIRST_ACTIVE_SCO_INDEX can be used as the first parameter to
** find the first active SCO index
**
** Returns BTM_SUCCESS if returned data is valid connection.
** BTM_ILLEGAL_VALUE if no connection for specified sco_inx.
** BTM_MODE_UNSUPPORTED if local controller does not support
** 1.2 specification.
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_ReadEScoLinkParms (UINT16 sco_inx,
tBTM_ESCO_DATA *p_parms);
/*******************************************************************************
**
** Function BTM_ChangeEScoLinkParms
**
** Description This function requests renegotiation of the parameters on
** the current eSCO Link. If any of the changes are accepted
** by the controllers, the BTM_ESCO_CHG_EVT event is sent in
** the tBTM_ESCO_CBACK function with the current settings of
** the link. The callback is registered through the call to
** BTM_SetEScoMode.
**
**
** Returns BTM_CMD_STARTED if command is successfully initiated.
** BTM_ILLEGAL_VALUE if no connection for specified sco_inx.
** BTM_NO_RESOURCES - not enough resources to initiate command.
** BTM_MODE_UNSUPPORTED if local controller does not support
** 1.2 specification.
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_ChangeEScoLinkParms (UINT16 sco_inx,
tBTM_CHG_ESCO_PARAMS *p_parms);
/*******************************************************************************
**
** Function BTM_EScoConnRsp
**
** Description This function is called upon receipt of an (e)SCO connection
** request event (BTM_ESCO_CONN_REQ_EVT) to accept or reject
** the request. Parameters used to negotiate eSCO links.
** If p_parms is NULL, then values set through BTM_SetEScoMode
** are used.
** If the link type of the incoming request is SCO, then only
** the tx_bw, max_latency, content format, and packet_types are
** valid. The hci_status parameter should be
** ([0x0] to accept, [0x0d..0x0f] to reject)
**
**
** Returns void
**
*******************************************************************************/
//extern
void BTM_EScoConnRsp (UINT16 sco_inx, UINT8 hci_status,
tBTM_ESCO_PARAMS *p_parms);
/*******************************************************************************
**
** Function BTM_GetNumScoLinks
**
** Description This function returns the number of active SCO links.
**
** Returns UINT8
**
*******************************************************************************/
//extern
UINT8 BTM_GetNumScoLinks (void);
/*****************************************************************************
** SECURITY MANAGEMENT FUNCTIONS
*****************************************************************************/
/*******************************************************************************
**
** Function BTM_SecRegister
**
** Description Application manager calls this function to register for
** security services. There can be one and only one application
** saving link keys. BTM allows only first registration.
**
** Returns TRUE if registered OK, else FALSE
**
*******************************************************************************/
//extern
BOOLEAN BTM_SecRegister (tBTM_APPL_INFO *p_cb_info);
/*******************************************************************************
**
** Function BTM_SecRegisterLinkKeyNotificationCallback
**
** Description Profiles can register to be notified when a new Link Key
** is generated per connection.
**
** Returns TRUE if registered OK, else FALSE
**
*******************************************************************************/
//extern
BOOLEAN BTM_SecRegisterLinkKeyNotificationCallback(
tBTM_LINK_KEY_CALLBACK *p_callback);
/*******************************************************************************
**
** Function BTM_SecAddRmtNameNotifyCallback
**
** Description Profiles can register to be notified when name of the
** remote device is resolved (up to BTM_SEC_MAX_RMT_NAME_CALLBACKS).
**
** Returns TRUE if registered OK, else FALSE
**
*******************************************************************************/
//extern
BOOLEAN BTM_SecAddRmtNameNotifyCallback (tBTM_RMT_NAME_CALLBACK *p_callback);
/*******************************************************************************
**
** Function BTM_SecDeleteRmtNameNotifyCallback
**
** Description A profile can deregister notification when a new Link Key
** is generated per connection.
**
** Returns TRUE if OK, else FALSE
**
*******************************************************************************/
//extern
BOOLEAN BTM_SecDeleteRmtNameNotifyCallback (tBTM_RMT_NAME_CALLBACK *p_callback);
/*******************************************************************************
**
** Function BTM_GetSecurityFlags
**
** Description Get security flags for the device
**
** Returns BOOLEAN TRUE or FALSE is device found
**
*******************************************************************************/
//extern
BOOLEAN BTM_GetSecurityFlags (BD_ADDR bd_addr, UINT8 *p_sec_flags);
/*******************************************************************************
**
** Function BTM_GetSecurityFlagsByTransport
**
** Description Get security flags for the device on a particular transport
**
** Parameters bd_addr: BD address of remote device
** p_sec_flags : Out parameter to be filled with security flags for the connection
** transport : Physical transport of the connection (BR/EDR or LE)
**
** Returns BOOLEAN TRUE or FALSE is device found
**
*******************************************************************************/
//extern
BOOLEAN BTM_GetSecurityFlagsByTransport (BD_ADDR bd_addr,
UINT8 *p_sec_flags, tBT_TRANSPORT transport);
/*******************************************************************************
**
** Function BTM_ReadTrustedMask
**
** Description Get trusted mask for the device
**
** Returns NULL, if the device record is not found.
** otherwise, the trusted mask
**
*******************************************************************************/
//extern
UINT32 *BTM_ReadTrustedMask (BD_ADDR bd_addr);
/*******************************************************************************
**
** Function BTM_SetPinType
**
** Description Set PIN type for the device.
**
** Returns void
**
*******************************************************************************/
//extern
void BTM_SetPinType (UINT8 pin_type, PIN_CODE pin_code, UINT8 pin_code_len);
/*******************************************************************************
**
** Function BTM_SetPairableMode
**
** Description Enable or disable pairing
**
** Parameters allow_pairing - (TRUE or FALSE) whether or not the device
** allows pairing.
** connect_only_paired - (TRUE or FALSE) whether or not to
** only allow paired devices to connect.
**
** Returns void
**
*******************************************************************************/
//extern
void BTM_SetPairableMode (BOOLEAN allow_pairing, BOOLEAN connect_only_paired);
/*******************************************************************************
**
** Function BTM_SetSecureConnectionsOnly
**
** Description Enable or disable default treatment for Mode 4 Level 0 services
**
** Parameter secure_connections_only_mode - (TRUE or FALSE)
** TRUE means that the device should treat Mode 4 Level 0 services as
** services of other levels.
** FALSE means that the device should provide default treatment for
** Mode 4 Level 0 services.
**
** Returns void
**
*******************************************************************************/
//extern
void BTM_SetSecureConnectionsOnly (BOOLEAN secure_connections_only_mode);
/*******************************************************************************
**
** Function BTM_SetSecurityLevel
**
** Description Register service security level with Security Manager. Each
** service must register its requirements regardless of the
** security level that is used. This API is called once for originators
** nad again for acceptors of connections.
**
** Returns TRUE if registered OK, else FALSE
**
*******************************************************************************/
//extern
BOOLEAN BTM_SetSecurityLevel (BOOLEAN is_originator, const char *p_name,
UINT8 service_id, UINT16 sec_level,
UINT16 psm, UINT32 mx_proto_id,
UINT32 mx_chan_id);
/*******************************************************************************
**
** Function BTM_SetOutService
**
** Description This function is called to set the service for
** outgoing connection.
**
** Returns void
**
*******************************************************************************/
//extern
void BTM_SetOutService(BD_ADDR bd_addr, UINT8 service_id, UINT32 mx_chan_id);
/*******************************************************************************
**
** Function BTM_SecClrService
**
** Description Removes specified service record(s) from the security database.
** All service records with the specified name are removed.
** Typically used only by devices with limited RAM so that it can
** reuse an old security service record.
** records (except SDP).
**
** Returns Number of records that were freed.
**
*******************************************************************************/
//extern
UINT8 BTM_SecClrService (UINT8 service_id);
/*******************************************************************************
**
** Function BTM_SecAddDevice
**
** Description Add/modify device. This function will be normally called
** during host startup to restore all required information
** stored in the NVRAM.
** dev_class, bd_name, link_key, and features are NULL if unknown
**
** Returns TRUE if added OK, else FALSE
**
*******************************************************************************/
//extern
BOOLEAN BTM_SecAddDevice (BD_ADDR bd_addr, DEV_CLASS dev_class,
BD_NAME bd_name, UINT8 *features,
UINT32 trusted_mask[], LINK_KEY link_key,
UINT8 key_type, tBTM_IO_CAP io_cap, UINT8 pin_length,
UINT8 sc_support);
/*******************************************************************************
**
** Function BTM_SecDeleteDevice
**
** Description Free resources associated with the device.
**
** Returns TRUE if rmoved OK, FALSE if not found
**
*******************************************************************************/
//extern
BOOLEAN BTM_SecDeleteDevice (BD_ADDR bd_addr, tBT_TRANSPORT transport);
/*******************************************************************************
**
** Function BTM_SecGetDeviceLinkKey
**
** Description This function is called to obtain link key for the device
** it returns BTM_SUCCESS if link key is available, or
** BTM_UNKNOWN_ADDR if Security Manager does not know about
** the device or device record does not contain link key info
**
** Returns BTM_SUCCESS if successful, otherwise error code
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_SecGetDeviceLinkKey (BD_ADDR bd_addr,
LINK_KEY link_key);
/*******************************************************************************
**
** Function BTM_SecGetDeviceLinkKeyType
**
** Description This function is called to obtain link key type for the
** device.
** it returns BTM_SUCCESS if link key is available, or
** BTM_UNKNOWN_ADDR if Security Manager does not know about
** the device or device record does not contain link key info
**
** Returns BTM_LKEY_TYPE_IGNORE if link key is unknown, link type
** otherwise.
**
*******************************************************************************/
//extern
tBTM_LINK_KEY_TYPE BTM_SecGetDeviceLinkKeyType (BD_ADDR bd_addr);
/*******************************************************************************
**
** Function BTM_PINCodeReply
**
** Description This function is called after Security Manager submitted
** PIN code request to the UI.
**
** Parameters: bd_addr - Address of the device for which PIN was requested
** res - result of the operation BTM_SUCCESS if success
** pin_len - length in bytes of the PIN Code
** p_pin - pointer to array with the PIN Code
** trusted_mask - bitwise OR of trusted services (array of UINT32)
**
** Returns void
**
*******************************************************************************/
//extern
void BTM_PINCodeReply (BD_ADDR bd_addr, UINT8 res, UINT8 pin_len,
UINT8 *p_pin, UINT32 trusted_mask[]);
/*******************************************************************************
**
** Function BTM_SecBond
**
** Description This function is called to perform bonding with peer device.
**
** Parameters: bd_addr - Address of the device to bond
** pin_len - length in bytes of the PIN Code
** p_pin - pointer to array with the PIN Code
** trusted_mask - bitwise OR of trusted services (array of UINT32)
** Returns BTM_CMD_STARTED if successfully initiated, otherwise error
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_SecBond (BD_ADDR bd_addr,
UINT8 pin_len, UINT8 *p_pin,
UINT32 trusted_mask[]);
/*******************************************************************************
**
** Function BTM_SecBondByTransport
**
** Description This function is called to perform bonding by designated transport
**
** Parameters: bd_addr - Address of the device to bond
** pin_len - length in bytes of the PIN Code
** p_pin - pointer to array with the PIN Code
** trusted_mask - bitwise OR of trusted services (array of UINT32)
** transport : Physical transport to use for bonding (BR/EDR or LE)
**
** Returns BTM_CMD_STARTED if successfully initiated, otherwise error
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_SecBondByTransport (BD_ADDR bd_addr,
tBT_TRANSPORT transport,
UINT8 pin_len, UINT8 *p_pin,
UINT32 trusted_mask[]);
/*******************************************************************************
**
** Function BTM_SecBondCancel
**
** Description This function is called to cancel ongoing bonding process
** with peer device.
**
** Returns BTM_CMD_STARTED if successfully initiated, otherwise error
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_SecBondCancel (BD_ADDR bd_addr);
/*******************************************************************************
**
** Function BTM_SetEncryption
**
** Description This function is called to ensure that connection is
** encrypted. Should be called only on an open connection.
** Typically only needed for connections that first want to
** bring up unencrypted links, then later encrypt them.
**
** Parameters: bd_addr - Address of the peer device
** p_callback - Pointer to callback function called if
** this function returns PENDING after required
** procedures are completed. Can be set to NULL
** if status is not desired.
** p_ref_data - pointer to any data the caller wishes to receive
** in the callback function upon completion.
* can be set to NULL if not used.
**
** Returns BTM_SUCCESS - already encrypted
** BTM_PENDING - command will be returned in the callback
** BTM_WRONG_MODE- connection not up.
** BTM_BUSY - security procedures are currently active
** BTM_MODE_UNSUPPORTED - if security manager not linked in.
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_SetEncryption (BD_ADDR bd_addr, tBT_TRANSPORT transport,
tBTM_SEC_CBACK *p_callback, void *p_ref_data);
/*******************************************************************************
**
** Function BTM_ConfirmReqReply
**
** Description This function is called to confirm the numeric value for
** Simple Pairing in response to BTM_SP_CFM_REQ_EVT
**
** Parameters: res - result of the operation BTM_SUCCESS if success
** bd_addr - Address of the peer device
**
*******************************************************************************/
//extern
void BTM_ConfirmReqReply(tBTM_STATUS res, BD_ADDR bd_addr);
/*******************************************************************************
**
** Function BTM_PasskeyReqReply
**
** Description This function is called to provide the passkey for
** Simple Pairing in response to BTM_SP_KEY_REQ_EVT
**
** Parameters: res - result of the operation BTM_SUCCESS if success
** bd_addr - Address of the peer device
** passkey - numeric value in the range of 0 - 999999(0xF423F).
**
*******************************************************************************/
//extern
void BTM_PasskeyReqReply(tBTM_STATUS res, BD_ADDR bd_addr, UINT32 passkey);
/*******************************************************************************
**
** Function BTM_SendKeypressNotif
**
** Description This function is used during the passkey entry model
** by a device with KeyboardOnly IO capabilities
** (very likely to be a HID Device).
** It is called by a HID Device to inform the remote device when
** a key has been entered or erased.
**
** Parameters: bd_addr - Address of the peer device
** type - notification type
**
*******************************************************************************/
//extern
void BTM_SendKeypressNotif(BD_ADDR bd_addr, tBTM_SP_KEY_TYPE type);
/*******************************************************************************
**
** Function BTM_IoCapRsp
**
** Description This function is called in response to BTM_SP_IO_REQ_EVT
** When the event data io_req.oob_data is set to BTM_OOB_UNKNOWN
** by the tBTM_SP_CALLBACK implementation, this function is
** called to provide the actual response
**
** Parameters: bd_addr - Address of the peer device
** io_cap - The IO capability of local device.
** oob - BTM_OOB_NONE or BTM_OOB_PRESENT.
** auth_req- MITM protection required or not.
**
*******************************************************************************/
//extern
void BTM_IoCapRsp(BD_ADDR bd_addr, tBTM_IO_CAP io_cap,
tBTM_OOB_DATA oob, tBTM_AUTH_REQ auth_req);
/*******************************************************************************
**
** Function BTM_ReadLocalOobData
**
** Description This function is called to read the local OOB data from
** LM
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_ReadLocalOobData(void);
/*******************************************************************************
**
** Function BTM_RemoteOobDataReply
**
** Description This function is called to provide the remote OOB data for
** Simple Pairing in response to BTM_SP_RMT_OOB_EVT
**
** Parameters: bd_addr - Address of the peer device
** c - simple pairing Hash C.
** r - simple pairing Randomizer C.
**
*******************************************************************************/
//extern
void BTM_RemoteOobDataReply(tBTM_STATUS res, BD_ADDR bd_addr,
BT_OCTET16 c, BT_OCTET16 r);
/*******************************************************************************
**
** Function BTM_BuildOobData
**
** Description This function is called to build the OOB data payload to
** be sent over OOB (non-Bluetooth) link
**
** Parameters: p_data - the location for OOB data
** max_len - p_data size.
** c - simple pairing Hash C.
** r - simple pairing Randomizer C.
** name_len- 0, local device name would not be included.
** otherwise, the local device name is included for
** up to this specified length
**
** Returns Number of bytes in p_data.
**
*******************************************************************************/
//extern
UINT16 BTM_BuildOobData(UINT8 *p_data, UINT16 max_len, BT_OCTET16 c,
BT_OCTET16 r, UINT8 name_len);
/*******************************************************************************
**
** Function BTM_BothEndsSupportSecureConnections
**
** Description This function is called to check if both the local device and the peer device
** specified by bd_addr support BR/EDR Secure Connections.
**
** Parameters: bd_addr - address of the peer
**
** Returns TRUE if BR/EDR Secure Connections are supported by both local
** and the remote device.
** else FALSE.
**
*******************************************************************************/
//extern
BOOLEAN BTM_BothEndsSupportSecureConnections(BD_ADDR bd_addr);
/*******************************************************************************
**
** Function BTM_PeerSupportsSecureConnections
**
** Description This function is called to check if the peer supports
** BR/EDR Secure Connections.
**
** Parameters: bd_addr - address of the peer
**
** Returns TRUE if BR/EDR Secure Connections are supported by the peer,
** else FALSE.
**
*******************************************************************************/
//extern
BOOLEAN BTM_PeerSupportsSecureConnections(BD_ADDR bd_addr);
/*******************************************************************************
**
** Function BTM_ReadOobData
**
** Description This function is called to parse the OOB data payload
** received over OOB (non-Bluetooth) link
**
** Parameters: p_data - the location for OOB data
** eir_tag - The associated EIR tag to read the data.
** *p_len(output) - the length of the data with the given tag.
**
** Returns the beginning of the data with the given tag.
** NULL, if the tag is not found.
**
*******************************************************************************/
//extern
UINT8 *BTM_ReadOobData(UINT8 *p_data, UINT8 eir_tag, UINT8 *p_len);
/*******************************************************************************
**
** Function BTM_SecReadDevName
**
** Description Looks for the device name in the security database for the
** specified BD address.
**
** Returns Pointer to the name or NULL
**
*******************************************************************************/
//extern
char *BTM_SecReadDevName (BD_ADDR bd_addr);
/*******************************************************************************
**
** Function BTM_SecClearSecurityFlags
**
** Description Reset the security flags (mark as not-paired) for a given
** remove device.
**
*******************************************************************************/
extern void BTM_SecClearSecurityFlags (BD_ADDR bd_addr);
/*****************************************************************************
** POWER MANAGEMENT FUNCTIONS
*****************************************************************************/
/*******************************************************************************
**
** Function BTM_PmRegister
**
** Description register or deregister with power manager
**
** Returns BTM_SUCCESS if successful,
** BTM_NO_RESOURCES if no room to hold registration
** BTM_ILLEGAL_VALUE
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_PmRegister (UINT8 mask, UINT8 *p_pm_id,
tBTM_PM_STATUS_CBACK *p_cb);
/*******************************************************************************
**
** Function BTM_SetPowerMode
**
** Description store the mode in control block or
** alter ACL connection behavior.
**
** Returns BTM_SUCCESS if successful,
** BTM_UNKNOWN_ADDR if bd addr is not active or bad
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_SetPowerMode (UINT8 pm_id, BD_ADDR remote_bda,
tBTM_PM_PWR_MD *p_mode);
/*******************************************************************************
**
** Function BTM_ReadPowerMode
**
** Description This returns the current mode for a specific
** ACL connection.
**
** Input Param remote_bda - device address of desired ACL connection
**
** Output Param p_mode - address where the current mode is copied into.
** BTM_ACL_MODE_NORMAL
** BTM_ACL_MODE_HOLD
** BTM_ACL_MODE_SNIFF
** BTM_ACL_MODE_PARK
** (valid only if return code is BTM_SUCCESS)
**
** Returns BTM_SUCCESS if successful,
** BTM_UNKNOWN_ADDR if bd addr is not active or bad
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_ReadPowerMode (BD_ADDR remote_bda,
tBTM_PM_MODE *p_mode);
/*******************************************************************************
**
** Function BTM_SetSsrParams
**
** Description This sends the given SSR parameters for the given ACL
** connection if it is in ACTIVE mode.
**
** Input Param remote_bda - device address of desired ACL connection
** max_lat - maximum latency (in 0.625ms)(0-0xFFFE)
** min_rmt_to - minimum remote timeout
** min_loc_to - minimum local timeout
**
**
** Returns BTM_SUCCESS if the HCI command is issued successful,
** BTM_UNKNOWN_ADDR if bd addr is not active or bad
** BTM_CMD_STORED if the command is stored
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_SetSsrParams (BD_ADDR remote_bda, UINT16 max_lat,
UINT16 min_rmt_to, UINT16 min_loc_to);
/*******************************************************************************
**
** Function BTM_GetHCIConnHandle
**
** Description This function is called to get the handle for an ACL connection
** to a specific remote BD Address.
**
** Returns the handle of the connection, or 0xFFFF if none.
**
*******************************************************************************/
//extern
UINT16 BTM_GetHCIConnHandle (BD_ADDR remote_bda, tBT_TRANSPORT transport);
/*******************************************************************************
**
** Function BTM_DeleteStoredLinkKey
**
** Description This function is called to delete link key for the specified
** device addresses from the NVRAM storage attached to the Bluetooth
** controller.
**
** Parameters: bd_addr - Addresses of the devices
** p_cb - Call back function to be called to return
** the results
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_DeleteStoredLinkKey(BD_ADDR bd_addr, tBTM_CMPL_CB *p_cb);
/*******************************************************************************
**
** Function BTM_WriteEIR
**
** Description This function is called to write EIR data to controller.
**
** Parameters p_buff - allocated HCI command buffer including extended
** inquriry response
** fec_required - FEC is required or not
**
** Returns BTM_SUCCESS - if successful
** BTM_MODE_UNSUPPORTED - if local device cannot support it
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_WriteEIR( BT_HDR *p_buff, BOOLEAN fec_required);
/*******************************************************************************
**
** Function BTM_CheckEirData
**
** Description This function is called to get EIR data from significant part.
**
** Parameters p_eir - pointer of EIR significant part
** type - finding EIR data type
** p_length - return the length of EIR data
**
** Returns pointer of EIR data
**
*******************************************************************************/
//extern
UINT8 *BTM_CheckEirData( UINT8 *p_eir, UINT8 type, UINT8 *p_length );
/*******************************************************************************
**
** Function BTM_HasEirService
**
** Description This function is called to know if UUID in bit map of UUID.
**
** Parameters p_eir_uuid - bit map of UUID list
** uuid16 - UUID 16-bit
**
** Returns TRUE - if found
** FALSE - if not found
**
*******************************************************************************/
//extern
BOOLEAN BTM_HasEirService( UINT32 *p_eir_uuid, UINT16 uuid16 );
/*******************************************************************************
**
** Function BTM_HasInquiryEirService
**
** Description This function is called to know if UUID in bit map of UUID list.
**
** Parameters p_results - inquiry results
** uuid16 - UUID 16-bit
**
** Returns BTM_EIR_FOUND - if found
** BTM_EIR_NOT_FOUND - if not found and it is complete list
** BTM_EIR_UNKNOWN - if not found and it is not complete list
**
*******************************************************************************/
//extern
tBTM_EIR_SEARCH_RESULT BTM_HasInquiryEirService( tBTM_INQ_RESULTS *p_results,
UINT16 uuid16 );
/*******************************************************************************
**
** Function BTM_AddEirService
**
** Description This function is called to add a service in bit map of UUID list.
**
** Parameters p_eir_uuid - bit mask of UUID list for EIR
** uuid16 - UUID 16-bit
**
** Returns None
**
*******************************************************************************/
//extern
void BTM_AddEirService( UINT32 *p_eir_uuid, UINT16 uuid16 );
/*******************************************************************************
**
** Function BTM_RemoveEirService
**
** Description This function is called to remove a service in bit map of UUID list.
**
** Parameters p_eir_uuid - bit mask of UUID list for EIR
** uuid16 - UUID 16-bit
**
** Returns None
**
*******************************************************************************/
//extern
void BTM_RemoveEirService( UINT32 *p_eir_uuid, UINT16 uuid16 );
/*******************************************************************************
**
** Function BTM_GetEirSupportedServices
**
** Description This function is called to get UUID list from bit map of UUID list.
**
** Parameters p_eir_uuid - bit mask of UUID list for EIR
** p - reference of current pointer of EIR
** max_num_uuid16 - max number of UUID can be written in EIR
** num_uuid16 - number of UUID have been written in EIR
**
** Returns BTM_EIR_MORE_16BITS_UUID_TYPE, if it has more than max
** BTM_EIR_COMPLETE_16BITS_UUID_TYPE, otherwise
**
*******************************************************************************/
//extern
UINT8 BTM_GetEirSupportedServices( UINT32 *p_eir_uuid, UINT8 **p,
UINT8 max_num_uuid16, UINT8 *p_num_uuid16);
/*******************************************************************************
**
** Function BTM_GetEirUuidList
**
** Description This function parses EIR and returns UUID list.
**
** Parameters p_eir - EIR
** uuid_size - LEN_UUID_16, LEN_UUID_32, LEN_UUID_128
** p_num_uuid - return number of UUID in found list
** p_uuid_list - return UUID 16-bit list
** max_num_uuid - maximum number of UUID to be returned
**
** Returns 0 - if not found
** BTM_EIR_COMPLETE_16BITS_UUID_TYPE
** BTM_EIR_MORE_16BITS_UUID_TYPE
** BTM_EIR_COMPLETE_32BITS_UUID_TYPE
** BTM_EIR_MORE_32BITS_UUID_TYPE
** BTM_EIR_COMPLETE_128BITS_UUID_TYPE
** BTM_EIR_MORE_128BITS_UUID_TYPE
**
*******************************************************************************/
//extern
UINT8 BTM_GetEirUuidList( UINT8 *p_eir, UINT8 uuid_size, UINT8 *p_num_uuid,
UINT8 *p_uuid_list, UINT8 max_num_uuid);
/*****************************************************************************
** SCO OVER HCI
*****************************************************************************/
/*******************************************************************************
**
** Function BTM_ConfigScoPath
**
** Description This function enable/disable SCO over HCI and registers SCO
** data callback if SCO over HCI is enabled.
**
** Parameter path: SCO or HCI
** p_sco_data_cb: callback function or SCO data if path is set
** to transport.
** p_pcm_param: pointer to the PCM interface parameter. If a NULL
** pointer is used, PCM parameter maintained in
** the control block will be used; otherwise update
** control block value.
** err_data_rpt: Lisbon feature to enable the erronous data report
** or not.
**
** Returns BTM_SUCCESS if the successful.
** BTM_NO_RESOURCES: no rsource to start the command.
** BTM_ILLEGAL_VALUE: invalid callback function pointer.
** BTM_CMD_STARTED :Command sent. Waiting for command cmpl event.
**
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_ConfigScoPath (tBTM_SCO_ROUTE_TYPE path,
tBTM_SCO_DATA_CB *p_sco_data_cb,
tBTM_SCO_PCM_PARAM *p_pcm_param,
BOOLEAN err_data_rpt);
/*******************************************************************************
**
** Function BTM_WriteScoData
**
** Description This function write SCO data to a specified instance. The data
** to be written p_buf needs to carry an offset of
** HCI_SCO_PREAMBLE_SIZE bytes, and the data length can not
** exceed BTM_SCO_DATA_SIZE_MAX bytes, whose default value is set
** to 60 and is configurable. Data longer than the maximum bytes
** will be truncated.
**
** Returns BTM_SUCCESS: data write is successful
** BTM_ILLEGAL_VALUE: SCO data contains illegal offset value.
** BTM_SCO_BAD_LENGTH: SCO data length exceeds the max SCO packet
** size.
** BTM_NO_RESOURCES: no resources.
** BTM_UNKNOWN_ADDR: unknown SCO connection handle, or SCO is not
** routed via HCI.
**
**
*******************************************************************************/
//extern
tBTM_STATUS BTM_WriteScoData (UINT16 sco_inx, BT_HDR *p_buf);
/*******************************************************************************
**
** Function BTM_SetARCMode
**
** Description Send Audio Routing Control command.
**
** Returns void
**
*******************************************************************************/
//extern
void BTM_SetARCMode (UINT8 iface, UINT8 arc_mode, tBTM_VSC_CMPL_CB *p_arc_cb);
/*******************************************************************************
**
** Function BTM_PCM2Setup_Write
**
** Description Send PCM2_Setup write command.
**
** Returns void
**
*******************************************************************************/
//extern
void BTM_PCM2Setup_Write (BOOLEAN clk_master, tBTM_VSC_CMPL_CB *p_arc_cb);
/*******************************************************************************
**
** Function BTM_PM_ReadControllerState
**
** Description This function is called to obtain the controller state
**
** Returns Controller state (BTM_CONTRL_ACTIVE, BTM_CONTRL_SCAN, and BTM_CONTRL_IDLE)
**
*******************************************************************************/
//extern
tBTM_CONTRL_STATE BTM_PM_ReadControllerState(void);
/*******************************************************************************
**
** Function BTM_SetAfhChannels
**
** Description This function is called to set AFH channels
**
** Returns status of the operation
**
*******************************************************************************/
tBTM_STATUS BTM_SetAfhChannels (AFH_CHANNELS channels, tBTM_CMPL_CB *p_afh_channels_cmpl_cback);
/*******************************************************************************
**
** Function BTM_BleSetChannels
**
** Description This function is called to set BLE channels
**
** Returns status of the operation
**
*******************************************************************************/
tBTM_STATUS BTM_BleSetChannels (BLE_CHANNELS channels, tBTM_CMPL_CB *p_ble_channels_cmpl_cback);
/*
#ifdef __cplusplus
}
#endif
*/
#endif /* BTM_API_H */
| 40.88343 | 156 | 0.559005 | [
"model"
] |
82947936af1ded601a1013214f16d12149a31100 | 2,275 | h | C | chrome/browser/ui/views/tabs/tab_strip_layout.h | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | chrome/browser/ui/views/tabs/tab_strip_layout.h | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | chrome/browser/ui/views/tabs/tab_strip_layout.h | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_VIEWS_TABS_TAB_STRIP_LAYOUT_H_
#define CHROME_BROWSER_UI_VIEWS_TABS_TAB_STRIP_LAYOUT_H_
#include <vector>
#include "ui/gfx/geometry/size.h"
namespace gfx {
class Rect;
}
struct TabSizeInfo {
// The width of pinned tabs.
int pinned_tab_width;
// The min width of active/inactive tabs.
int min_active_width;
int min_inactive_width;
// The max size of tabs. Active and inactive tabs have the same max width.
gfx::Size max_size;
// The overlap between adjacent tabs. When positioning tabs the x-coordinate
// of a tab is calculated as the x-coordinate of the previous tab plus the
// previous tab's width minus the |tab_overlap|, e.g.
// next_tab_x = previous_tab.max_x() - tab_overlap.
int tab_overlap;
// Additional offset between the last pinned tab and the first normal tab.
int pinned_to_normal_offset;
};
// Calculates the bounds of the pinned tabs. This assumes |tabs_bounds| is the
// same size as |num_tabs|. Returns the x-coordinate to use for the first
// non-pinned tab, if any.
int CalculateBoundsForPinnedTabs(const TabSizeInfo& tab_size_info,
int num_pinned_tabs,
int num_tabs,
int start_x,
std::vector<gfx::Rect>* tabs_bounds);
// Calculates and returns the bounds of the tabs. |width| is the available
// width to use for tab layout. This never sizes the tabs smaller then the
// minimum widths in TabSizeInfo, and as a result the calculated bounds may go
// beyond |width|.
std::vector<gfx::Rect> CalculateBounds(const TabSizeInfo& tab_size_info,
int num_pinned_tabs,
int num_tabs,
int active_index,
int start_x,
int width,
int* active_width,
int* inactive_width);
#endif // CHROME_BROWSER_UI_VIEWS_TABS_TAB_STRIP_LAYOUT_H_
| 37.916667 | 78 | 0.631648 | [
"geometry",
"vector"
] |
82955543eda4a043c54b73a69f2d2243abc74fe4 | 2,012 | h | C | pixie/PixieObject/PixieObjectAnimator.h | martonantoni/pixie | ab750d25d12f8420e68e1cb393a75b1f0a0c1056 | [
"MIT"
] | null | null | null | pixie/PixieObject/PixieObjectAnimator.h | martonantoni/pixie | ab750d25d12f8420e68e1cb393a75b1f0a0c1056 | [
"MIT"
] | null | null | null | pixie/PixieObject/PixieObjectAnimator.h | martonantoni/pixie | ab750d25d12f8420e68e1cb393a75b1f0a0c1056 | [
"MIT"
] | null | null | null | #pragma once
class cPixieObject;
enum class ePixieObjectAnimationDoneReason
{
StillRunning, NormalDone, AutoDone
};
class cPixieObjectAnimator: public cIntrusiveRefCount
{
public:
enum // flags
{
DoneWhenAffectedPropertySet = 0x01,
DoneWhenSamePropertyAnimatorAdded = 0x02,
KeepsObjectAlive = 0x08,
};
typedef ePixieObjectAnimationDoneReason eAnimationDoneReason;
private:
std::function<void()> mDoneFunction;
unsigned int mStartTime=gFrameTime;
protected:
const unsigned int mFlags;
unsigned int mAffectedProperties;
unsigned int GetStartTime() const { return mStartTime; }
public:
cPixieObjectAnimator(unsigned int Flags, unsigned int AffectedProperties);
cPixieObjectAnimator(const cPixieObjectAnimator &)=delete;
virtual ~cPixieObjectAnimator();
void SetStartTime(unsigned int StartTime) { mStartTime=StartTime; }
unsigned int GetFlags() const { return mFlags; }
unsigned int GetAffectedProperties() const { return mAffectedProperties; }
virtual void Activated(cPixieObject &Object)=0;
enum eAnimateResult { AnimationDone, AnimationActive };
virtual eAnimateResult Animate(cPixieObject &Object)=0;
void SetDoneFunction(const std::function<void()> &DoneFunction);
};
class cEmptyAnimator: public cPixieObjectAnimator
{
public:
cEmptyAnimator(): cPixieObjectAnimator(0u, 0u) {}
cEmptyAnimator(const std::function<void()> &DoneFunction): cEmptyAnimator()
{
SetDoneFunction(DoneFunction);
}
virtual eAnimateResult Animate(cPixieObject &Object) override { return cPixieObjectAnimator::AnimationDone; }
virtual void Activated(cPixieObject &Object) override {}
};
class cPixieObjectAnimatorManager: public tSingleton<cPixieObjectAnimatorManager>
{
tRegisteredObjects<cPixieObject *> mAnimatedObjects;
cRegisteredID mLogicID;
void OnLogic();
public:
cPixieObjectAnimatorManager();
~cPixieObjectAnimatorManager();
cRegisteredID RegisterAnimatedObject(cPixieObject *Object);
};
extern cPixieObjectAnimatorManager *thePixieObjectAnimatorManager; | 31.4375 | 110 | 0.798211 | [
"object"
] |
8295c907b782a559b48e0bcb5a6a321a7a3c47e6 | 3,025 | h | C | cudaPlugin/Source/cudaPlugin/Public/VideoAcquisition.h | leggedrobotics/cuda_ue4_linux | 5f33d935e5240b150de5d3c95bf42e2f80d435ae | [
"MIT"
] | 6 | 2021-01-23T08:58:09.000Z | 2022-02-08T12:38:42.000Z | cudaPlugin/Source/cudaPlugin/Public/VideoAcquisition.h | leggedrobotics/cuda_ue4_linux | 5f33d935e5240b150de5d3c95bf42e2f80d435ae | [
"MIT"
] | 1 | 2021-12-20T02:40:13.000Z | 2021-12-20T02:40:13.000Z | cudaPlugin/Source/cudaPlugin/Public/VideoAcquisition.h | leggedrobotics/cuda_ue4_linux | 5f33d935e5240b150de5d3c95bf42e2f80d435ae | [
"MIT"
] | 2 | 2021-02-06T17:27:57.000Z | 2021-04-28T18:15:53.000Z | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Components/ActorComponent.h"
#include "GameFramework/Actor.h"
#include "Engine/TextureRenderTarget2D.h"
#include "cuda.h"
// includes, cuda
#include <cuda_runtime.h>
#include "npp.h"
#include <memory.h>
#include <string>
#include <iostream>
#include <thread>
#include <vector>
#include <fstream> // std::ifstream, std::ofstream
#include "DynamicRHI.h"
#include "RenderResource.h"
#include "RHICommandList.h"
#include "Materials/MaterialInstanceDynamic.h"
//#include "VulkanLinuxPlatform.h"
//#include "VulkanPlatformDefines.h"
/*
#include "VulkanState.h"
#include "VulkanUtil.h"
#include "VulkanResources.h"
*/
#include "VulkanRHIPrivate.h"
#include "VulkanPendingState.h"
#include "VulkanContext.h"
#include "EngineGlobals.h"
#include "VulkanLLM.h"
#include "VulkanResources.h"
#include "VulkanCommon.h"
#include "VulkanConfiguration.h"
#include "VulkanDynamicRHI.h"
#include "VulkanGlobals.h"
#include "VulkanMemory.h"
#include "VulkanRHIBridge.h"
#include "VulkanShaderResources.h"
#include "VulkanUtil.h"
#include "BoundShaderStateCache.h"
#include "VulkanShaderResources.h"
#include "VulkanState.h"
#include "Misc/ScopeRWLock.h"
#include "VideoAcquisition.generated.h"
#define HandleResult(res,place) if (res!=XI_OK) {printf("Error after %s (%d)\n",place,res);}
UCLASS(ClassGroup = (Custom), meta = (BlueprintSpawnableComponent))
class CUDAPLUGIN_API AVideoAcquisition : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this component's properties
AVideoAcquisition();
~AVideoAcquisition();
//The texture where the Video is rendered to
UPROPERTY(EditAnywhere)
UTextureRenderTarget2D* RenderTarget;
//Video configuration
UPROPERTY(EditAnywhere)
int VideoWidth = 2064;
UPROPERTY(EditAnywhere)
int VideoHeight = 1544;
UPROPERTY(EditAnywhere)
int FPS = 50;
UPROPERTY(EditAnywhere)
float GainR = 0.7;
UPROPERTY(EditAnywhere)
float GainG = 0.6;
UPROPERTY(EditAnywhere)
float GainB = 1.8;
void Acquire();
virtual void Tick(float DeltaTime) override;
bool stopped;
void InitCamera();
void threadLoop();
void stop() { stopped = true; }
void start() { stopped = false; }
void UpdateTextureFromGPU();
int applyWhiteBalance(Npp8u* img_d, int img_pitch, int width, int height, float _gain_r, float _gain_g, float _gain_b);
protected:
// Called when the game starts
virtual void BeginPlay() override;
virtual void EndPlay(const EEndPlayReason::Type) override;
private:
CUcontext cuContext = NULL;
cudaGraphicsResource* CudaResource;
cudaGraphicsResource* Resources[1];
int DISPLAY_WIDTH;
int DISPLAY_HEIGHT;
bool GameEnded = false;
uint8_t *dpFrameBayer[240];
int nPitchBayer;
uint8_t *dpFrame;
int nPitch = 0;
uint8_t *destPtr;
uint32 anydummy;
std::thread *cameraThread = nullptr;
uint8_t vkDeviceUUID[VK_UUID_SIZE];
};
| 21.607143 | 122 | 0.736529 | [
"vector"
] |
8299ef4b4e0ea2314c6a7e392955579f3ddc40b2 | 1,000 | h | C | EventFilter/SiStripRawToDigi/test/plugins/SiStripFEDRawDataAnalyzer.h | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | EventFilter/SiStripRawToDigi/test/plugins/SiStripFEDRawDataAnalyzer.h | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | EventFilter/SiStripRawToDigi/test/plugins/SiStripFEDRawDataAnalyzer.h | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #ifndef EventFilter_SiStripRawToDigi_SiStripFEDRawDataAnalyzer_H
#define EventFilter_SiStripRawToDigi_SiStripFEDRawDataAnalyzer_H
#include "FWCore/Framework/interface/EDAnalyzer.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include <utility>
#include <vector>
/**
@class SiStripFEDRawDataAnalyzer
@brief Analyzes contents of FEDRawData collection
*/
class SiStripFEDRawDataAnalyzer : public edm::EDAnalyzer {
public:
typedef std::pair<uint16_t, uint16_t> Fed;
typedef std::vector<Fed> Feds;
typedef std::vector<uint16_t> Channels;
typedef std::map<uint16_t, Channels> ChannelsMap;
SiStripFEDRawDataAnalyzer(const edm::ParameterSet&);
~SiStripFEDRawDataAnalyzer();
void beginJob();
void analyze(const edm::Event&, const edm::EventSetup&);
void endJob();
private:
edm::InputTag label_;
};
#endif // EventFilter_SiStripRawToDigi_SiStripFEDRawDataAnalyzer_H
| 28.571429 | 67 | 0.794 | [
"vector"
] |
82a6645e46d003ecb85cb7662a47da397b379cf1 | 8,368 | h | C | Project/Temp/StagingArea/Data/il2cppOutput/UnityEngine_UI_UnityEngine_UI_LayoutRebuilder2155218138MethodDeclarations.h | Yuunagi-Yu/NumberDisk | f1cf414dbfe8d0094d3ef11b37839f6caf58ae9f | [
"MIT"
] | null | null | null | Project/Temp/StagingArea/Data/il2cppOutput/UnityEngine_UI_UnityEngine_UI_LayoutRebuilder2155218138MethodDeclarations.h | Yuunagi-Yu/NumberDisk | f1cf414dbfe8d0094d3ef11b37839f6caf58ae9f | [
"MIT"
] | null | null | null | Project/Temp/StagingArea/Data/il2cppOutput/UnityEngine_UI_UnityEngine_UI_LayoutRebuilder2155218138MethodDeclarations.h | Yuunagi-Yu/NumberDisk | f1cf414dbfe8d0094d3ef11b37839f6caf58ae9f | [
"MIT"
] | null | null | null | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include <assert.h>
#include <exception>
// UnityEngine.UI.LayoutRebuilder
struct LayoutRebuilder_t2155218138;
// UnityEngine.RectTransform
struct RectTransform_t3349966182;
// UnityEngine.Transform
struct Transform_t3275118058;
// System.Collections.Generic.List`1<UnityEngine.Component>
struct List_1_t3188497603;
// UnityEngine.Events.UnityAction`1<UnityEngine.Component>
struct UnityAction_1_t890994926;
// System.Object
struct Il2CppObject;
// System.String
struct String_t;
// UnityEngine.Component
struct Component_t3819376471;
#include "codegen/il2cpp-codegen.h"
#include "UnityEngine_UnityEngine_RectTransform3349966182.h"
#include "UnityEngine_UI_UnityEngine_UI_CanvasUpdate1528800019.h"
#include "mscorlib_System_Object2689449295.h"
#include "UnityEngine_UI_UnityEngine_UI_LayoutRebuilder2155218138.h"
#include "UnityEngine_UnityEngine_Component3819376471.h"
// System.Void UnityEngine.UI.LayoutRebuilder::.cctor()
extern "C" void LayoutRebuilder__cctor_m4047868732 (Il2CppObject * __this /* static, unused */, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void UnityEngine.UI.LayoutRebuilder::.ctor()
extern "C" void LayoutRebuilder__ctor_m3739687501 (LayoutRebuilder_t2155218138 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void UnityEngine.UI.LayoutRebuilder::Initialize(UnityEngine.RectTransform)
extern "C" void LayoutRebuilder_Initialize_m2671585490 (LayoutRebuilder_t2155218138 * __this, RectTransform_t3349966182 * ___controller0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void UnityEngine.UI.LayoutRebuilder::Clear()
extern "C" void LayoutRebuilder_Clear_m2390054824 (LayoutRebuilder_t2155218138 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void UnityEngine.UI.LayoutRebuilder::ReapplyDrivenProperties(UnityEngine.RectTransform)
extern "C" void LayoutRebuilder_ReapplyDrivenProperties_m1809142560 (Il2CppObject * __this /* static, unused */, RectTransform_t3349966182 * ___driven0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// UnityEngine.Transform UnityEngine.UI.LayoutRebuilder::get_transform()
extern "C" Transform_t3275118058 * LayoutRebuilder_get_transform_m3358807864 (LayoutRebuilder_t2155218138 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Boolean UnityEngine.UI.LayoutRebuilder::IsDestroyed()
extern "C" bool LayoutRebuilder_IsDestroyed_m3442208294 (LayoutRebuilder_t2155218138 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void UnityEngine.UI.LayoutRebuilder::StripDisabledBehavioursFromList(System.Collections.Generic.List`1<UnityEngine.Component>)
extern "C" void LayoutRebuilder_StripDisabledBehavioursFromList_m3597654705 (Il2CppObject * __this /* static, unused */, List_1_t3188497603 * ___components0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void UnityEngine.UI.LayoutRebuilder::ForceRebuildLayoutImmediate(UnityEngine.RectTransform)
extern "C" void LayoutRebuilder_ForceRebuildLayoutImmediate_m566681977 (Il2CppObject * __this /* static, unused */, RectTransform_t3349966182 * ___layoutRoot0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void UnityEngine.UI.LayoutRebuilder::Rebuild(UnityEngine.UI.CanvasUpdate)
extern "C" void LayoutRebuilder_Rebuild_m3304459068 (LayoutRebuilder_t2155218138 * __this, int32_t ___executing0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void UnityEngine.UI.LayoutRebuilder::PerformLayoutControl(UnityEngine.RectTransform,UnityEngine.Events.UnityAction`1<UnityEngine.Component>)
extern "C" void LayoutRebuilder_PerformLayoutControl_m3946051172 (LayoutRebuilder_t2155218138 * __this, RectTransform_t3349966182 * ___rect0, UnityAction_1_t890994926 * ___action1, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void UnityEngine.UI.LayoutRebuilder::PerformLayoutCalculation(UnityEngine.RectTransform,UnityEngine.Events.UnityAction`1<UnityEngine.Component>)
extern "C" void LayoutRebuilder_PerformLayoutCalculation_m736744700 (LayoutRebuilder_t2155218138 * __this, RectTransform_t3349966182 * ___rect0, UnityAction_1_t890994926 * ___action1, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void UnityEngine.UI.LayoutRebuilder::MarkLayoutForRebuild(UnityEngine.RectTransform)
extern "C" void LayoutRebuilder_MarkLayoutForRebuild_m640589351 (Il2CppObject * __this /* static, unused */, RectTransform_t3349966182 * ___rect0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Boolean UnityEngine.UI.LayoutRebuilder::ValidLayoutGroup(UnityEngine.RectTransform,System.Collections.Generic.List`1<UnityEngine.Component>)
extern "C" bool LayoutRebuilder_ValidLayoutGroup_m490554819 (Il2CppObject * __this /* static, unused */, RectTransform_t3349966182 * ___parent0, List_1_t3188497603 * ___comps1, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Boolean UnityEngine.UI.LayoutRebuilder::ValidController(UnityEngine.RectTransform,System.Collections.Generic.List`1<UnityEngine.Component>)
extern "C" bool LayoutRebuilder_ValidController_m2595049322 (Il2CppObject * __this /* static, unused */, RectTransform_t3349966182 * ___layoutRoot0, List_1_t3188497603 * ___comps1, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void UnityEngine.UI.LayoutRebuilder::MarkLayoutRootForRebuild(UnityEngine.RectTransform)
extern "C" void LayoutRebuilder_MarkLayoutRootForRebuild_m2779623641 (Il2CppObject * __this /* static, unused */, RectTransform_t3349966182 * ___controller0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void UnityEngine.UI.LayoutRebuilder::LayoutComplete()
extern "C" void LayoutRebuilder_LayoutComplete_m498127808 (LayoutRebuilder_t2155218138 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void UnityEngine.UI.LayoutRebuilder::GraphicUpdateComplete()
extern "C" void LayoutRebuilder_GraphicUpdateComplete_m3773376591 (LayoutRebuilder_t2155218138 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Int32 UnityEngine.UI.LayoutRebuilder::GetHashCode()
extern "C" int32_t LayoutRebuilder_GetHashCode_m2745108660 (LayoutRebuilder_t2155218138 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Boolean UnityEngine.UI.LayoutRebuilder::Equals(System.Object)
extern "C" bool LayoutRebuilder_Equals_m376170852 (LayoutRebuilder_t2155218138 * __this, Il2CppObject * ___obj0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.String UnityEngine.UI.LayoutRebuilder::ToString()
extern "C" String_t* LayoutRebuilder_ToString_m710744868 (LayoutRebuilder_t2155218138 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void UnityEngine.UI.LayoutRebuilder::<s_Rebuilders>m__0(UnityEngine.UI.LayoutRebuilder)
extern "C" void LayoutRebuilder_U3Cs_RebuildersU3Em__0_m3768099182 (Il2CppObject * __this /* static, unused */, LayoutRebuilder_t2155218138 * ___x0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Boolean UnityEngine.UI.LayoutRebuilder::<StripDisabledBehavioursFromList>m__1(UnityEngine.Component)
extern "C" bool LayoutRebuilder_U3CStripDisabledBehavioursFromListU3Em__1_m3569508057 (Il2CppObject * __this /* static, unused */, Component_t3819376471 * ___e0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void UnityEngine.UI.LayoutRebuilder::<Rebuild>m__2(UnityEngine.Component)
extern "C" void LayoutRebuilder_U3CRebuildU3Em__2_m3239837417 (Il2CppObject * __this /* static, unused */, Component_t3819376471 * ___e0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void UnityEngine.UI.LayoutRebuilder::<Rebuild>m__3(UnityEngine.Component)
extern "C" void LayoutRebuilder_U3CRebuildU3Em__3_m777184612 (Il2CppObject * __this /* static, unused */, Component_t3819376471 * ___e0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void UnityEngine.UI.LayoutRebuilder::<Rebuild>m__4(UnityEngine.Component)
extern "C" void LayoutRebuilder_U3CRebuildU3Em__4_m2524920159 (Il2CppObject * __this /* static, unused */, Component_t3819376471 * ___e0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void UnityEngine.UI.LayoutRebuilder::<Rebuild>m__5(UnityEngine.Component)
extern "C" void LayoutRebuilder_U3CRebuildU3Em__5_m863475162 (Il2CppObject * __this /* static, unused */, Component_t3819376471 * ___e0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
| 89.978495 | 230 | 0.839866 | [
"object",
"transform"
] |
82aed6e4fbd949246a772bb8f21ff08d8c7b0714 | 4,399 | h | C | ParaViewCore/ClientServerCore/Rendering/vtk3DWidgetRepresentation.h | psavery/ParaView | 00074fbc7de29c2ab2f1b90624e07d1af53484ee | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | ParaViewCore/ClientServerCore/Rendering/vtk3DWidgetRepresentation.h | psavery/ParaView | 00074fbc7de29c2ab2f1b90624e07d1af53484ee | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | ParaViewCore/ClientServerCore/Rendering/vtk3DWidgetRepresentation.h | psavery/ParaView | 00074fbc7de29c2ab2f1b90624e07d1af53484ee | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
Program: ParaView
Module: vtk3DWidgetRepresentation.h
Copyright (c) Kitware, Inc.
All rights reserved.
See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/**
* @class vtk3DWidgetRepresentation
*
* vtk3DWidgetRepresentation is a vtkDataRepresentation subclass for 3D widgets
* and their representations. It makes it possible to add 3D widgets to
* vtkPVRenderView.
*/
#ifndef vtk3DWidgetRepresentation_h
#define vtk3DWidgetRepresentation_h
#include "vtkDataRepresentation.h"
#include "vtkPVClientServerCoreRenderingModule.h" //needed for exports
#include "vtkWeakPointer.h" // needed for vtkWeakPointer.
class vtkAbstractWidget;
class vtkPVRenderView;
class vtkWidgetRepresentation;
class VTKPVCLIENTSERVERCORERENDERING_EXPORT vtk3DWidgetRepresentation : public vtkDataRepresentation
{
public:
static vtk3DWidgetRepresentation* New();
vtkTypeMacro(vtk3DWidgetRepresentation, vtkDataRepresentation);
void PrintSelf(ostream& os, vtkIndent indent) override;
//@{
/**
* Get/Set the widget.
*/
void SetWidget(vtkAbstractWidget*);
vtkGetObjectMacro(Widget, vtkAbstractWidget);
//@}
//@{
/**
* Get/Set the representation.
*/
void SetRepresentation(vtkWidgetRepresentation*);
vtkGetObjectMacro(Representation, vtkWidgetRepresentation);
//@}
//@{
/**
* Set to true to add the vtkWidgetRepresentation to the non-composited
* renderer. false by default.
*/
vtkSetMacro(UseNonCompositedRenderer, bool);
vtkGetMacro(UseNonCompositedRenderer, bool);
vtkBooleanMacro(UseNonCompositedRenderer, bool);
//@}
//@{
/**
* Get/Set whether the widget is enabled.
*/
void SetEnabled(bool);
vtkGetMacro(Enabled, bool);
vtkBooleanMacro(Enabled, bool);
//@}
//@{
/**
* These are needed to support BoxWidget use-case where we want to support
* specification of the box using global transform or relative to some
* reference bounds. Since this may be applicable to other 3D widgets that
* have similar requirements, we add this ability to vtk3DWidgetRepresentation
* itself. All this does it based on the state of UseReferenceBounds,
* `vtkWidgetRepresentation::PlaceWidget` is called using either the
* `ReferenceBounds` or the bounds passed to `PlaceWidget`.
*/
void SetReferenceBounds(const double bds[6]);
void PlaceWidget(const double bds[6]);
void SetUseReferenceBounds(bool);
//@}
protected:
vtk3DWidgetRepresentation();
~vtk3DWidgetRepresentation() override;
/**
* Adds the representation to the view. This is called from
* vtkView::AddRepresentation(). Subclasses should override this method.
* Returns true if the addition succeeds.
*/
bool AddToView(vtkView* view) override;
/**
* Removes the representation to the view. This is called from
* vtkView::RemoveRepresentation(). Subclasses should override this method.
* Returns true if the removal succeeds.
*/
bool RemoveFromView(vtkView* view) override;
/**
* Updates 'Enabled' on this->Widget.
*/
void UpdateEnabled();
/**
* Callback whenever the representation is modified. We call UpdateEnabled()
* to ensure that the widget is not left enabled when the representation is
* hidden.
*/
void OnRepresentationModified();
/**
* Callback whenever the view is modified. If the view's interactor has
* changed, we will pass that to the vtkAbstractWidget instance and then call
* UpdateEnabled().
*/
void OnViewModified();
bool Enabled;
bool UseNonCompositedRenderer;
vtkAbstractWidget* Widget;
vtkWidgetRepresentation* Representation;
vtkWeakPointer<vtkPVRenderView> View;
private:
vtk3DWidgetRepresentation(const vtk3DWidgetRepresentation&) = delete;
void operator=(const vtk3DWidgetRepresentation&) = delete;
unsigned long RepresentationObserverTag;
unsigned long ViewObserverTag;
double ReferenceBounds[6];
bool UseReferenceBounds;
double PlaceWidgetBounds[6];
void PlaceWidget();
};
#endif
| 29.722973 | 100 | 0.714481 | [
"transform",
"3d"
] |
82b162702246805eac86f8ef52a231504dbac5ff | 6,148 | h | C | applications/ContactStructuralMechanicsApplication/custom_frictional_laws/frictional_law_with_derivative.h | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | null | null | null | applications/ContactStructuralMechanicsApplication/custom_frictional_laws/frictional_law_with_derivative.h | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | null | null | null | applications/ContactStructuralMechanicsApplication/custom_frictional_laws/frictional_law_with_derivative.h | lkusch/Kratos | e8072d8e24ab6f312765185b19d439f01ab7b27b | [
"BSD-4-Clause"
] | null | null | null | // KRATOS ______ __ __ _____ __ __ __
// / ____/___ ____ / /_____ ______/ /_/ ___// /________ _______/ /___ ___________ _/ /
// / / / __ \/ __ \/ __/ __ `/ ___/ __/\__ \/ __/ ___/ / / / ___/ __/ / / / ___/ __ `/ /
// / /___/ /_/ / / / / /_/ /_/ / /__/ /_ ___/ / /_/ / / /_/ / /__/ /_/ /_/ / / / /_/ / /
// \____/\____/_/ /_/\__/\__,_/\___/\__//____/\__/_/ \__,_/\___/\__/\__,_/_/ \__,_/_/ MECHANICS
//
// License: BSD License
// license: ContactStructuralMechanicsApplication/license.txt
//
// Main authors: Vicente Mataix Ferrandiz
//
#if !defined(FRICTIONAL_LAW_WITH_DERIVATIVE_H_DEFINED )
#define FRICTIONAL_LAW_WITH_DERIVATIVE_H_DEFINED
// System includes
// External includes
// Project includes
#include "custom_frictional_laws/frictional_law.h"
namespace Kratos
{
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@}
///@name Kratos Classes
///@{
/**
* @class FrictionalLawWithDerivative
* @ingroup ContactStructuralMechanicsApplication
* @brief This class defines the base class for frictional laws with derivative
* @details This class does nothing, define derived frictional laws in order to make use of it
* @author Vicente Mataix Ferrandiz
* @tparam TDim The dimension of work
* @tparam TNumNodes The number of nodes of the slave
* @tparam TFrictional If we are solving a frictional or frictionless problem
* @tparam TNormalVariation If we are consider normal variation
* @tparam TNumNodesMaster The number of nodes of the master
*/
template< std::size_t TDim, std::size_t TNumNodes, bool TNormalVariation, std::size_t TNumNodesMaster = TNumNodes>
class KRATOS_API(CONTACT_STRUCTURAL_MECHANICS_APPLICATION) FrictionalLawWithDerivative
: public FrictionalLaw
{
public:
///@name Type Definitions
///@{
/// Define the base class
typedef FrictionalLaw BaseType;
/// Node definition
typedef Node<3> NodeType;
/// Index type definition
typedef std::size_t IndexType;
/// Size type definition
typedef std::size_t SizeType;
/// Definition of the derivative data
typedef DerivativeDataFrictional<TDim, TNumNodes, TNormalVariation, TNumNodesMaster> DerivativeDataType;
/// The definition of the mortar operators
typedef MortarOperatorWithDerivatives<TDim, TNumNodes, true, TNormalVariation, TNumNodesMaster> MortarConditionMatrices;
/// Zero tolerance
static constexpr double ZeroTolerance = std::numeric_limits<double>::epsilon();
/// Counted pointer of FrictionalLawWithDerivative
KRATOS_CLASS_POINTER_DEFINITION( FrictionalLawWithDerivative );
///@}
///@name Life Cycle
///@{
/**
* @brief Default constructor
*/
FrictionalLawWithDerivative()
{
}
///Copy constructor (not really required)
FrictionalLawWithDerivative(const FrictionalLawWithDerivative& rhs)
{
}
/// Destructor.
~FrictionalLawWithDerivative()
{
}
///@}
///@name Operators
///@{
///@}
///@name Operations
///@{
/**
* @brief This method computes the threshold derivative value considered for computing friction
* @param rNode The node where the threshold derivative value is obtained
* @param rCondition The condition where the friction is computed
* @param rCurrentProcessInfo The current instance of the process info
* @param rDerivativeData The reference to the derivative database
* @param rMortarConditionMatrices The container of the mortar operators
* @param IndexDerivative The derivative index
* @param IndexNode The corresponding node index on the condition geometry
*/
virtual double GetDerivativeThresholdValue(
const NodeType& rNode,
const PairedCondition& rCondition,
const ProcessInfo& rCurrentProcessInfo,
const DerivativeDataType& rDerivativeData,
const MortarConditionMatrices& rMortarConditionMatrices,
const IndexType IndexDerivative,
const IndexType IndexNode
);
///@}
///@name Access
///@{
///@}
///@name Inquiry
///@{
///@}
///@name Input and output
///@{
/// Turn back information as a string.
std::string Info() const override
{
return "FrictionalLawWithDerivative";
}
/// Print information about this object.
void PrintInfo(std::ostream& rOStream) const override
{
rOStream << Info() << std::endl;
}
/// Print object's data.
void PrintData(std::ostream& rOStream) const override
{
rOStream << Info() << std::endl;
}
///@}
///@name Friends
///@{
///@}
protected:
///@name Protected static Member Variables
///@{
///@}
///@name Protected member Variables
///@{
///@}
///@name Protected Operators
///@{
///@}
///@name Protected Operations
///@{
///@}
///@name Protected Access
///@{
///@}
///@name Protected Inquiry
///@{
///@}
///@name Protected LifeCycle
///@{
///@}
private:
///@name Static Member Variables
///@{
///@}
///@name Member Variables
///@{
///@}
///@name Private Operators
///@{
///@}
///@name Private Operations
///@{
///@}
///@name Private Access
///@{
///@}
///@}
///@name Serialization
///@{
friend class Serializer;
void save(Serializer& rSerializer) const override
{
KRATOS_SERIALIZE_SAVE_BASE_CLASS(rSerializer, BaseType );
}
void load(Serializer& rSerializer) override
{
KRATOS_SERIALIZE_LOAD_BASE_CLASS(rSerializer, BaseType );
}
///@}
///@name Private Inquiry
///@{
///@}
///@name Unaccessible methods
///@{
///@}
}; // Class FrictionalLawWithDerivative
///@}
///@name Type Definitions
///@{
///@}
///@name Input and output
///@{
///@}
} // namespace Kratos.
#endif // FRICTIONAL_LAW_WITH_DERIVATIVE_H_DEFINED defined
| 23.287879 | 124 | 0.618575 | [
"geometry",
"object"
] |
82b1838bfcf4a42ddfc3b659769b37bc625db7f6 | 12,619 | h | C | headless/public/headless_browser.h | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 76 | 2020-09-02T03:05:41.000Z | 2022-03-30T04:40:55.000Z | headless/public/headless_browser.h | blueboxd/chromium-legacy | 07223bc94bd97499909c9ed3c3f5769d718fe2e0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 45 | 2020-09-02T03:21:37.000Z | 2022-03-31T22:19:45.000Z | headless/public/headless_browser.h | Yannic/chromium | ab32e8aacb08c9fce0dc4bf09eec456ba46e3710 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 8 | 2020-07-22T18:49:18.000Z | 2022-02-08T10:27:16.000Z | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef HEADLESS_PUBLIC_HEADLESS_BROWSER_H_
#define HEADLESS_PUBLIC_HEADLESS_BROWSER_H_
#include <memory>
#include <string>
#include <unordered_set>
#include <vector>
#include "base/callback.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "build/build_config.h"
#include "headless/public/headless_browser_context.h"
#include "headless/public/headless_devtools_channel.h"
#include "headless/public/headless_export.h"
#include "headless/public/headless_web_contents.h"
#include "net/base/host_port_pair.h"
#include "ui/gfx/font_render_params.h"
#include "ui/gfx/geometry/size.h"
#if defined(OS_WIN)
#include "sandbox/win/src/sandbox_types.h"
#endif
namespace base {
class MessagePump;
class SingleThreadTaskRunner;
}
namespace headless {
// This class represents the global headless browser instance. To get a pointer
// to one, call |HeadlessBrowserMain| to initiate the browser main loop. An
// instance of |HeadlessBrowser| will be passed to the callback given to that
// function.
class HEADLESS_EXPORT HeadlessBrowser {
public:
struct Options;
// Create a new browser context which can be used to create tabs and isolate
// them from one another.
// Pointer to HeadlessBrowserContext becomes invalid after:
// a) Calling HeadlessBrowserContext::Close or
// b) Calling HeadlessBrowser::Shutdown
virtual HeadlessBrowserContext::Builder CreateBrowserContextBuilder() = 0;
virtual std::vector<HeadlessBrowserContext*> GetAllBrowserContexts() = 0;
// Return a DevTools target corresponding to this browser. Note that this
// method only returns a valid target after browser has been initialized on
// the main thread. The target only supports the domains available on the
// browser endpoint excluding the Tethering domain.
// TODO(dgozman): remove together with HeadlessDevToolsTarget.
virtual HeadlessDevToolsTarget* GetDevToolsTarget() = 0;
// Creates a channel connected to the browser. Note that this
// method only returns a valid channel after browser has been initialized on
// the main thread. The channel only supports the domains available on the
// browser endpoint excluding the Tethering domain.
virtual std::unique_ptr<HeadlessDevToolsChannel> CreateDevToolsChannel() = 0;
// Returns the HeadlessWebContents associated with the
// |devtools_agent_host_id| if any. Otherwise returns null.
virtual HeadlessWebContents* GetWebContentsForDevToolsAgentHostId(
const std::string& devtools_agent_host_id) = 0;
// Returns HeadlessBrowserContext associated with the given id if any.
// Otherwise returns null.
virtual HeadlessBrowserContext* GetBrowserContextForId(
const std::string& id) = 0;
// Allows setting and getting the browser context that DevTools will create
// new targets in by default.
virtual void SetDefaultBrowserContext(
HeadlessBrowserContext* browser_context) = 0;
virtual HeadlessBrowserContext* GetDefaultBrowserContext() = 0;
// Returns a task runner for submitting work to the browser main thread.
virtual scoped_refptr<base::SingleThreadTaskRunner> BrowserMainThread()
const = 0;
// Requests browser to stop as soon as possible. |Run| will return as soon as
// browser stops.
// IMPORTANT: All pointers to HeadlessBrowserContexts and HeadlessWebContents
// become invalid after calling this function.
virtual void Shutdown() = 0;
protected:
HeadlessBrowser() {}
virtual ~HeadlessBrowser() {}
private:
DISALLOW_COPY_AND_ASSIGN(HeadlessBrowser);
};
// Embedding API overrides for the headless browser.
struct HEADLESS_EXPORT HeadlessBrowser::Options {
class Builder;
Options(Options&& options);
~Options();
Options& operator=(Options&& options);
// Command line options to be passed to browser. Initialized in constructor.
int argc;
const char** argv;
#if defined(OS_WIN)
// Set hardware instance if available, otherwise it defaults to 0.
HINSTANCE instance = 0;
// Set with sandbox information. This has to be already initialized.
sandbox::SandboxInterfaceInfo* sandbox_info = nullptr;
#endif
// Address at which DevTools should listen for connections. Disabled by
// default.
net::HostPortPair devtools_endpoint;
// Enables remote debug over stdio pipes [in=3, out=4].
bool devtools_pipe_enabled = false;
// A single way to test whether the devtools server has been requested.
bool DevtoolsServerEnabled();
// Optional message pump that overrides the default. Must outlive the browser.
base::MessagePump* message_pump = nullptr;
// Run the browser in single process mode instead of using separate renderer
// processes as per default. Note that this also disables any sandboxing of
// web content, which can be a security risk.
bool single_process_mode = false;
// Run the browser without renderer sandbox. This option can be
// a security risk and should be used with caution.
bool disable_sandbox = false;
// Whether or not to enable content::ResourceScheduler. Enabled by default.
bool enable_resource_scheduler = true;
// Choose the GL implementation to use for rendering. A suitable
// implementantion is selected by default. Setting this to an empty
// string can be used to disable GL rendering (e.g., WebGL support).
std::string gl_implementation;
// Choose the ANGLE implementation to use for rendering.
// Only relevant if the gl_implementation above is set to "angle".
std::string angle_implementation;
// Default per-context options, can be specialized on per-context basis.
std::string product_name_and_version;
std::string accept_language;
std::string user_agent;
// The ProxyConfig to use. The system proxy settings are used by default.
std::unique_ptr<net::ProxyConfig> proxy_config;
// Default window size. This is also used to create the window tree host and
// as initial screen size. Defaults to 800x600.
gfx::Size window_size;
// Path to user data directory, where browser will look for its state.
// If empty, default directory (where the binary is located) will be used.
base::FilePath user_data_dir;
// Run a browser context in an incognito mode. Enabled by default.
bool incognito_mode = true;
// If true, then all pop-ups and calls to window.open will fail.
bool block_new_web_contents = false;
// Whether or not BeginFrames will be issued over DevTools protocol
// (experimental).
bool enable_begin_frame_control = false;
// Whether or not all sites should have a dedicated process.
bool site_per_process = false;
// Set a callback that is invoked to override WebPreferences for RenderViews
// created within the HeadlessBrowser. Called whenever the WebPreferences of a
// RenderView change. Executed on the browser main thread.
//
// WARNING: We cannot provide any guarantees about the stability of the
// exposed WebPreferences API, so use with care.
base::RepeatingCallback<void(blink::web_pref::WebPreferences*)>
override_web_preferences_callback;
// Set a callback that is invoked when a new child process is spawned or
// forked and allows adding additional command line flags to the child
// process's command line. Executed on the browser main thread.
// |child_browser_context| points to the BrowserContext of the child
// process, but will only be set if the child process is a renderer process.
//
// NOTE: This callback may be called on the UI or IO thread even after the
// HeadlessBrowser has been destroyed.
using AppendCommandLineFlagsCallback = base::RepeatingCallback<void(
base::CommandLine* command_line,
HeadlessBrowserContext* child_browser_context,
const std::string& child_process_type,
int child_process_id)>;
AppendCommandLineFlagsCallback append_command_line_flags_callback;
// Minidump crash reporter settings. Crash reporting is disabled by default.
// By default crash dumps are written to the directory containing the
// executable.
bool enable_crash_reporter = false;
base::FilePath crash_dumps_dir;
// Font render hinting value to override any default settings
gfx::FontRenderParams::Hinting font_render_hinting;
// Reminder: when adding a new field here, do not forget to add it to
// HeadlessBrowserContextOptions (where appropriate).
private:
Options(int argc, const char** argv);
DISALLOW_COPY_AND_ASSIGN(Options);
};
class HEADLESS_EXPORT HeadlessBrowser::Options::Builder {
public:
Builder(int argc, const char** argv);
Builder();
Builder(const Builder&) = delete;
Builder& operator=(const Builder&) = delete;
~Builder();
// Browser-wide settings.
Builder& EnableDevToolsServer(const net::HostPortPair& endpoint);
Builder& EnableDevToolsPipe();
Builder& SetMessagePump(base::MessagePump* pump);
Builder& SetSingleProcessMode(bool single_process);
Builder& SetDisableSandbox(bool disable);
Builder& SetEnableResourceScheduler(bool enable);
Builder& SetGLImplementation(const std::string& implementation);
Builder& SetANGLEImplementation(const std::string& implementation);
Builder& SetAppendCommandLineFlagsCallback(
const Options::AppendCommandLineFlagsCallback& callback);
#if defined(OS_WIN)
Builder& SetInstance(HINSTANCE hinstance);
Builder& SetSandboxInfo(sandbox::SandboxInterfaceInfo* info);
#endif
// Per-context settings.
Builder& SetProductNameAndVersion(const std::string& name_and_version);
Builder& SetAcceptLanguage(const std::string& language);
Builder& SetEnableBeginFrameControl(bool enable);
Builder& SetUserAgent(const std::string& agent);
Builder& SetProxyConfig(std::unique_ptr<net::ProxyConfig> config);
Builder& SetWindowSize(const gfx::Size& size);
Builder& SetUserDataDir(const base::FilePath& dir);
Builder& SetIncognitoMode(bool incognito);
Builder& SetSitePerProcess(bool per_process);
Builder& SetBlockNewWebContents(bool block);
Builder& SetOverrideWebPreferencesCallback(
base::RepeatingCallback<void(blink::web_pref::WebPreferences*)> callback);
Builder& SetCrashReporterEnabled(bool enabled);
Builder& SetCrashDumpsDir(const base::FilePath& dir);
Builder& SetFontRenderHinting(gfx::FontRenderParams::Hinting hinting);
Options Build();
private:
Options options_;
};
#if !defined(OS_WIN)
// The headless browser may need to create child processes (e.g., a renderer
// which runs web content). This is done by re-executing the parent process as
// a zygote[1] and forking each child process from that zygote.
//
// For this to work, the embedder should call RunChildProcess as soon as
// possible (i.e., before creating any threads) to pass control to the headless
// library. In a browser process this function will return immediately, but in a
// child process it will never return. For example:
//
// int main(int argc, const char** argv) {
// headless::RunChildProcessIfNeeded(argc, argv);
// headless::HeadlessBrowser::Options::Builder builder(argc, argv);
// return headless::HeadlessBrowserMain(
// builder.Build(),
// base::OnceCallback<void(headless::HeadlessBrowser*)>());
// }
//
// [1]
// https://chromium.googlesource.com/chromium/src/+/main/docs/linux/zygote.md
void RunChildProcessIfNeeded(int argc, const char** argv);
#else
// In Windows, the headless browser may need to create child processes. This is
// done by re-executing the parent process which may have been initialized with
// different libraries (e.g. child_dll). In this case, the embedder has to pass
// the appropiate HINSTANCE and initalization sandbox_info to properly launch
// the child process.
void RunChildProcessIfNeeded(HINSTANCE instance,
sandbox::SandboxInterfaceInfo* sandbox_info);
#endif // !defined(OS_WIN)
// Main entry point for running the headless browser. This function constructs
// the headless browser instance, passing it to the given
// |on_browser_start_callback| callback. Note that since this function executes
// the main loop, it will only return after HeadlessBrowser::Shutdown() is
// called, returning the exit code for the process. It is not possible to
// initialize the browser again after it has been torn down.
int HeadlessBrowserMain(
HeadlessBrowser::Options options,
base::OnceCallback<void(HeadlessBrowser*)> on_browser_start_callback);
} // namespace headless
#endif // HEADLESS_PUBLIC_HEADLESS_BROWSER_H_
| 39.068111 | 80 | 0.762342 | [
"geometry",
"render",
"vector"
] |
82b3a078bf1bdc6d5dd09f23cc9526ec17af077e | 563 | h | C | console/command_line.h | volok-aleksej/twainet-esp8266 | 452c7256af49ab8713bcc364be61a6a31f4a03ca | [
"Apache-2.0"
] | null | null | null | console/command_line.h | volok-aleksej/twainet-esp8266 | 452c7256af49ab8713bcc364be61a6a31f4a03ca | [
"Apache-2.0"
] | null | null | null | console/command_line.h | volok-aleksej/twainet-esp8266 | 452c7256af49ab8713bcc364be61a6a31f4a03ca | [
"Apache-2.0"
] | null | null | null | #ifndef COMMAND_LINE_H
#define COMMAND_LINE_H
#include "vector.h"
#include "command.h"
#include "singleton.h"
class CommandLine : public Singleton<CommandLine>
{
protected:
friend class Singleton<CommandLine>;
CommandLine();
~CommandLine();
public:
void AddCommand(ICommand* command);
void DoCommand(const String& command, const twnstd::vector<String>& params);
twnstd::vector<String> GetNextCommandArgs(const twnstd::vector<String>& args, bool& new_word);
private:
twnstd::vector<ICommand*> m_commands;
};
#endif/*COMMAND_LINE_H*/
| 24.478261 | 98 | 0.738899 | [
"vector"
] |
82b783041db5be939b8c78c420382533ade4ba16 | 1,826 | h | C | source/prox/flexProx.h | HendrikMuenster/flexBox_CPP | b24fe192772ff84bf79a93985de4e5c0a94a5297 | [
"BSD-4-Clause-UC"
] | 2 | 2017-01-09T15:16:08.000Z | 2017-01-10T08:26:00.000Z | source/prox/flexProx.h | HendrikMuenster/flexBox_CPP | b24fe192772ff84bf79a93985de4e5c0a94a5297 | [
"BSD-4-Clause-UC"
] | 1 | 2018-01-18T14:13:26.000Z | 2018-02-02T09:35:45.000Z | source/prox/flexProx.h | HendrikMuenster/flexBox_CPP | b24fe192772ff84bf79a93985de4e5c0a94a5297 | [
"BSD-4-Clause-UC"
] | 2 | 2018-07-19T21:02:07.000Z | 2021-05-20T06:32:52.000Z | #ifndef flexProx_H
#define flexProx_H
#include <vector>
#include "tools.h"
#include "data/flexBoxData.h"
//! abstract base class for all proximals (prox)
/*!
flexProx combines the interface for all usable proximals (prox)
*/
template<typename T>
class flexProx
{
#ifdef __CUDACC__
typedef thrust::device_vector<T> Tdata;
#else
typedef std::vector<T> Tdata;
#endif
public:
const prox p; //!< type of prox \sa prox
//! initializes the prox
/*!
\param aP type of prox
*/
flexProx(prox aP) : p(aP)
{
}
~flexProx()
{
if (VERBOSE > 0) printf("Destructor prox\n!");
}
//! returns the type of prox
/*!
\return type of prox
*/
prox getProx()
{
return p;
}
//! applies prox for non-data terms
/*!
the function body should be empty if implemented prox is a data prox
\param alpha weight of term
\param data data object
\param dualNumbers vector of internal identifactions of dual numbers corresponding to the term \sa flexBox
\param primalNumbers vector of internal identifactions of primal numbers corresponding to the term \sa flexBox
*/
virtual void applyProx(T alpha, flexBoxData<T>* data, const std::vector<int> &dualNumbers, const std::vector<int> &primalNumbers) = 0;
//! applies prox for data terms
/*!
the function body should be empty if implemented prox is a non-data prox
\param alpha weight of term
\param data data object
\param dualNumbers vector of internal identifactions of dual numbers corresponding to the term \sa flexBox
\param primalNumbers vector of internal identifactions of primal numbers corresponding to the term \sa flexBox
\param fList data part of term
*/
virtual void applyProx(T alpha, flexBoxData<T>* data, const std::vector<int> &dualNumbers, const std::vector<int> &primalNumbers, std::vector<Tdata> &fList) = 0;
};
#endif
| 25.361111 | 162 | 0.722344 | [
"object",
"vector"
] |
82b84c735b4075e6469c1757185a3f5a218ea19a | 1,117 | h | C | Source/ImGUIBlueprintLibrary/Public/Converter.h | ademets/UnrealImGui | c1cb1a030c38fac5f786b888388c3b17b3e023d3 | [
"MIT"
] | null | null | null | Source/ImGUIBlueprintLibrary/Public/Converter.h | ademets/UnrealImGui | c1cb1a030c38fac5f786b888388c3b17b3e023d3 | [
"MIT"
] | null | null | null | Source/ImGUIBlueprintLibrary/Public/Converter.h | ademets/UnrealImGui | c1cb1a030c38fac5f786b888388c3b17b3e023d3 | [
"MIT"
] | 1 | 2021-06-18T19:30:34.000Z | 2021-06-18T19:30:34.000Z | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "ImGuiCommon.h"
/**
*
*/
class IMGUIBLUEPRINTLIBRARY_API Converter
{
public:
Converter();
// Vector
static FVector2D Float2ToFVector2D(int Value[2]);
static void FVector2DToFloat2(FVector2D Value,float* Result[2]);
static FVector Float3ToFVector(int Value[3]);
static FVector4 Float4ToFVector4(int Value[4]);
static FVector2D ImVec2ToFVector2D(ImVec2 Value);
static ImVec2 FVector2DToImVec2(FVector2D Value);
static FVector4 ImVec4ToFVector4(ImVec4 Value);
static ImVec4 FVector4ToImVec4(FVector4 Value);
// Rotator
static FRotator Float3ToFRotator(int Value[3]);
// Color
static FColor Float3ToFColor(int Value[3]);
static FColor Float4ToFColor(int Value[4]);
static FColor ImVec4ToFColor(ImVec4 Value);
static FLinearColor Float3ToFLinearColor(int Value[3]);
static FLinearColor Float4ToFLinearColor(int Value[4]);
static FLinearColor ImVec4ToFLinearColor(ImVec4 Value);
static const char* FloatFormat(const int FractionalDigits);
};
| 18.616667 | 78 | 0.769919 | [
"vector"
] |
82bd030170f630c98fa18153465643bd997a5252 | 27,884 | h | C | Binding/Sources/Godot/include/gdnative/variant.h | migueldeicaza/GodotSwift | 4018a58eac9cd43e7fcec2859d3d281a86dcefc4 | [
"MIT"
] | 39 | 2021-02-10T18:09:06.000Z | 2022-03-19T18:55:43.000Z | Binding/Sources/Godot/include/gdnative/variant.h | migueldeicaza/GodotSwift | 4018a58eac9cd43e7fcec2859d3d281a86dcefc4 | [
"MIT"
] | 6 | 2021-02-10T02:44:30.000Z | 2021-02-10T02:47:51.000Z | Binding/Sources/Godot/include/gdnative/variant.h | migueldeicaza/GodotSwift | 4018a58eac9cd43e7fcec2859d3d281a86dcefc4 | [
"MIT"
] | 5 | 2021-02-16T08:33:42.000Z | 2021-09-18T06:39:04.000Z | /*************************************************************************/
/* variant.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 GODOT_VARIANT_H
#define GODOT_VARIANT_H
#ifdef __cplusplus
extern "C" {
#endif
#include <gdnative/math_defs.h>
#define GODOT_VARIANT_SIZE (sizeof(godot_real_t) * 4 + sizeof(int64_t))
#ifndef GODOT_CORE_API_GODOT_VARIANT_TYPE_DEFINED
#define GODOT_CORE_API_GODOT_VARIANT_TYPE_DEFINED
typedef struct {
uint8_t _dont_touch_that[GODOT_VARIANT_SIZE];
} godot_variant;
#endif
typedef enum godot_variant_type {
GODOT_VARIANT_TYPE_NIL,
// atomic types
GODOT_VARIANT_TYPE_BOOL,
GODOT_VARIANT_TYPE_INT,
GODOT_VARIANT_TYPE_FLOAT,
GODOT_VARIANT_TYPE_STRING,
// math types
GODOT_VARIANT_TYPE_VECTOR2,
GODOT_VARIANT_TYPE_VECTOR2I,
GODOT_VARIANT_TYPE_RECT2,
GODOT_VARIANT_TYPE_RECT2I,
GODOT_VARIANT_TYPE_VECTOR3,
GODOT_VARIANT_TYPE_VECTOR3I,
GODOT_VARIANT_TYPE_TRANSFORM2D,
GODOT_VARIANT_TYPE_PLANE,
GODOT_VARIANT_TYPE_QUAT,
GODOT_VARIANT_TYPE_AABB,
GODOT_VARIANT_TYPE_BASIS,
GODOT_VARIANT_TYPE_TRANSFORM,
// misc types
GODOT_VARIANT_TYPE_COLOR,
GODOT_VARIANT_TYPE_STRING_NAME,
GODOT_VARIANT_TYPE_NODE_PATH,
GODOT_VARIANT_TYPE_RID,
GODOT_VARIANT_TYPE_OBJECT,
GODOT_VARIANT_TYPE_CALLABLE,
GODOT_VARIANT_TYPE_SIGNAL,
GODOT_VARIANT_TYPE_DICTIONARY,
GODOT_VARIANT_TYPE_ARRAY,
// arrays
GODOT_VARIANT_TYPE_PACKED_BYTE_ARRAY,
GODOT_VARIANT_TYPE_PACKED_INT32_ARRAY,
GODOT_VARIANT_TYPE_PACKED_INT64_ARRAY,
GODOT_VARIANT_TYPE_PACKED_FLOAT32_ARRAY,
GODOT_VARIANT_TYPE_PACKED_FLOAT64_ARRAY,
GODOT_VARIANT_TYPE_PACKED_STRING_ARRAY,
GODOT_VARIANT_TYPE_PACKED_VECTOR2_ARRAY,
GODOT_VARIANT_TYPE_PACKED_VECTOR3_ARRAY,
GODOT_VARIANT_TYPE_PACKED_COLOR_ARRAY,
} godot_variant_type;
typedef enum godot_variant_call_error_error {
GODOT_CALL_ERROR_CALL_OK,
GODOT_CALL_ERROR_CALL_ERROR_INVALID_METHOD,
GODOT_CALL_ERROR_CALL_ERROR_INVALID_ARGUMENT,
GODOT_CALL_ERROR_CALL_ERROR_TOO_MANY_ARGUMENTS,
GODOT_CALL_ERROR_CALL_ERROR_TOO_FEW_ARGUMENTS,
GODOT_CALL_ERROR_CALL_ERROR_INSTANCE_IS_NULL,
} godot_variant_call_error_error;
typedef struct godot_variant_call_error {
godot_variant_call_error_error error;
int argument;
godot_variant_type expected;
} godot_variant_call_error;
typedef enum godot_variant_operator {
// comparison
GODOT_VARIANT_OP_EQUAL,
GODOT_VARIANT_OP_NOT_EQUAL,
GODOT_VARIANT_OP_LESS,
GODOT_VARIANT_OP_LESS_EQUAL,
GODOT_VARIANT_OP_GREATER,
GODOT_VARIANT_OP_GREATER_EQUAL,
// mathematic
GODOT_VARIANT_OP_ADD,
GODOT_VARIANT_OP_SUBTRACT,
GODOT_VARIANT_OP_MULTIPLY,
GODOT_VARIANT_OP_DIVIDE,
GODOT_VARIANT_OP_NEGATE,
GODOT_VARIANT_OP_POSITIVE,
GODOT_VARIANT_OP_MODULE,
GODOT_VARIANT_OP_STRING_CONCAT,
// bitwise
GODOT_VARIANT_OP_SHIFT_LEFT,
GODOT_VARIANT_OP_SHIFT_RIGHT,
GODOT_VARIANT_OP_BIT_AND,
GODOT_VARIANT_OP_BIT_OR,
GODOT_VARIANT_OP_BIT_XOR,
GODOT_VARIANT_OP_BIT_NEGATE,
// logic
GODOT_VARIANT_OP_AND,
GODOT_VARIANT_OP_OR,
GODOT_VARIANT_OP_XOR,
GODOT_VARIANT_OP_NOT,
// containment
GODOT_VARIANT_OP_IN,
GODOT_VARIANT_OP_MAX,
} godot_variant_operator;
typedef enum godot_variant_utility_function_type {
GODOT_UTILITY_FUNC_TYPE_MATH,
GODOT_UTILITY_FUNC_TYPE_RANDOM,
GODOT_UTILITY_FUNC_TYPE_GENERAL,
} godot_variant_utility_function_type;
// Types for function pointers.
typedef void (*godot_validated_operator_evaluator)(const godot_variant *p_left, const godot_variant *p_right, godot_variant *r_result);
typedef void (*godot_ptr_operator_evaluator)(const void *p_left, const void *p_right, void *r_result);
typedef void (*godot_validated_builtin_method)(godot_variant *p_base, const godot_variant **p_args, int p_argument_count, godot_variant *r_return);
typedef void (*godot_ptr_builtin_method)(void *p_base, const void **p_args, void *r_return, int p_argument_count);
typedef void (*godot_validated_constructor)(godot_variant *p_base, const godot_variant **p_args);
typedef void (*godot_ptr_constructor)(void *p_base, const void **p_args);
typedef void (*godot_validated_setter)(godot_variant *p_base, const godot_variant *p_value);
typedef void (*godot_validated_getter)(const godot_variant *p_base, godot_variant *r_value);
typedef void (*godot_ptr_setter)(void *p_base, const void *p_value);
typedef void (*godot_ptr_getter)(const void *p_base, void *r_value);
typedef void (*godot_validated_indexed_setter)(godot_variant *p_base, godot_int p_index, const godot_variant *p_value, bool *r_oob);
typedef void (*godot_validated_indexed_getter)(const godot_variant *p_base, godot_int p_index, godot_variant *r_value, bool *r_oob);
typedef void (*godot_ptr_indexed_setter)(void *p_base, godot_int p_index, const void *p_value);
typedef void (*godot_ptr_indexed_getter)(const void *p_base, godot_int p_index, void *r_value);
typedef void (*godot_validated_keyed_setter)(godot_variant *p_base, const godot_variant *p_key, const godot_variant *p_value, bool *r_valid);
typedef void (*godot_validated_keyed_getter)(const godot_variant *p_base, const godot_variant *p_key, godot_variant *r_value, bool *r_valid);
typedef bool (*godot_validated_keyed_checker)(const godot_variant *p_base, const godot_variant *p_key, bool *r_valid);
typedef void (*godot_ptr_keyed_setter)(void *p_base, const void *p_key, const void *p_value);
typedef void (*godot_ptr_keyed_getter)(const void *p_base, const void *p_key, void *r_value);
typedef bool (*godot_ptr_keyed_checker)(const godot_variant *p_base, const godot_variant *p_key);
typedef void (*godot_validated_utility_function)(godot_variant *r_return, const godot_variant **p_arguments, int p_argument_count);
typedef void (*godot_ptr_utility_function)(void *r_return, const void **p_arguments, int p_argument_count);
#include <gdnative/aabb.h>
#include <gdnative/array.h>
#include <gdnative/basis.h>
#include <gdnative/callable.h>
#include <gdnative/color.h>
#include <gdnative/dictionary.h>
#include <gdnative/node_path.h>
#include <gdnative/packed_arrays.h>
#include <gdnative/plane.h>
#include <gdnative/quat.h>
#include <gdnative/rect2.h>
#include <gdnative/rid.h>
#include <gdnative/signal.h>
#include <gdnative/string.h>
#include <gdnative/string_name.h>
#include <gdnative/transform.h>
#include <gdnative/transform2d.h>
#include <gdnative/variant.h>
#include <gdnative/vector2.h>
#include <gdnative/vector3.h>
#include <gdnative/gdnative.h>
// Memory.
void GDAPI godot_variant_new_copy(godot_variant *r_dest, const godot_variant *p_src);
void GDAPI godot_variant_new_nil(godot_variant *r_dest);
void GDAPI godot_variant_new_bool(godot_variant *r_dest, const godot_bool p_b);
void GDAPI godot_variant_new_int(godot_variant *r_dest, const godot_int p_i);
void GDAPI godot_variant_new_float(godot_variant *r_dest, const godot_float p_f);
void GDAPI godot_variant_new_string(godot_variant *r_dest, const godot_string *p_s);
void GDAPI godot_variant_new_vector2(godot_variant *r_dest, const godot_vector2 *p_v2);
void GDAPI godot_variant_new_vector2i(godot_variant *r_dest, const godot_vector2i *p_v2);
void GDAPI godot_variant_new_rect2(godot_variant *r_dest, const godot_rect2 *p_rect2);
void GDAPI godot_variant_new_rect2i(godot_variant *r_dest, const godot_rect2i *p_rect2);
void GDAPI godot_variant_new_vector3(godot_variant *r_dest, const godot_vector3 *p_v3);
void GDAPI godot_variant_new_vector3i(godot_variant *r_dest, const godot_vector3i *p_v3);
void GDAPI godot_variant_new_transform2d(godot_variant *r_dest, const godot_transform2d *p_t2d);
void GDAPI godot_variant_new_plane(godot_variant *r_dest, const godot_plane *p_plane);
void GDAPI godot_variant_new_quat(godot_variant *r_dest, const godot_quat *p_quat);
void GDAPI godot_variant_new_aabb(godot_variant *r_dest, const godot_aabb *p_aabb);
void GDAPI godot_variant_new_basis(godot_variant *r_dest, const godot_basis *p_basis);
void GDAPI godot_variant_new_transform(godot_variant *r_dest, const godot_transform *p_trans);
void GDAPI godot_variant_new_color(godot_variant *r_dest, const godot_color *p_color);
void GDAPI godot_variant_new_string_name(godot_variant *r_dest, const godot_string_name *p_s);
void GDAPI godot_variant_new_node_path(godot_variant *r_dest, const godot_node_path *p_np);
void GDAPI godot_variant_new_rid(godot_variant *r_dest, const godot_rid *p_rid);
void GDAPI godot_variant_new_object(godot_variant *r_dest, const godot_object *p_obj);
void GDAPI godot_variant_new_callable(godot_variant *r_dest, const godot_callable *p_callable);
void GDAPI godot_variant_new_signal(godot_variant *r_dest, const godot_signal *p_signal);
void GDAPI godot_variant_new_dictionary(godot_variant *r_dest, const godot_dictionary *p_dict);
void GDAPI godot_variant_new_array(godot_variant *r_dest, const godot_array *p_arr);
void GDAPI godot_variant_new_packed_byte_array(godot_variant *r_dest, const godot_packed_byte_array *p_pba);
void GDAPI godot_variant_new_packed_int32_array(godot_variant *r_dest, const godot_packed_int32_array *p_pia);
void GDAPI godot_variant_new_packed_int64_array(godot_variant *r_dest, const godot_packed_int64_array *p_pia);
void GDAPI godot_variant_new_packed_float32_array(godot_variant *r_dest, const godot_packed_float32_array *p_pra);
void GDAPI godot_variant_new_packed_float64_array(godot_variant *r_dest, const godot_packed_float64_array *p_pra);
void GDAPI godot_variant_new_packed_string_array(godot_variant *r_dest, const godot_packed_string_array *p_psa);
void GDAPI godot_variant_new_packed_vector2_array(godot_variant *r_dest, const godot_packed_vector2_array *p_pv2a);
void GDAPI godot_variant_new_packed_vector3_array(godot_variant *r_dest, const godot_packed_vector3_array *p_pv3a);
void GDAPI godot_variant_new_packed_color_array(godot_variant *r_dest, const godot_packed_color_array *p_pca);
godot_bool GDAPI godot_variant_as_bool(const godot_variant *p_self);
godot_int GDAPI godot_variant_as_int(const godot_variant *p_self);
godot_float GDAPI godot_variant_as_float(const godot_variant *p_self);
godot_string GDAPI godot_variant_as_string(const godot_variant *p_self);
godot_vector2 GDAPI godot_variant_as_vector2(const godot_variant *p_self);
godot_vector2i GDAPI godot_variant_as_vector2i(const godot_variant *p_self);
godot_rect2 GDAPI godot_variant_as_rect2(const godot_variant *p_self);
godot_rect2i GDAPI godot_variant_as_rect2i(const godot_variant *p_self);
godot_vector3 GDAPI godot_variant_as_vector3(const godot_variant *p_self);
godot_vector3i GDAPI godot_variant_as_vector3i(const godot_variant *p_self);
godot_transform2d GDAPI godot_variant_as_transform2d(const godot_variant *p_self);
godot_plane GDAPI godot_variant_as_plane(const godot_variant *p_self);
godot_quat GDAPI godot_variant_as_quat(const godot_variant *p_self);
godot_aabb GDAPI godot_variant_as_aabb(const godot_variant *p_self);
godot_basis GDAPI godot_variant_as_basis(const godot_variant *p_self);
godot_transform GDAPI godot_variant_as_transform(const godot_variant *p_self);
godot_color GDAPI godot_variant_as_color(const godot_variant *p_self);
godot_string_name GDAPI godot_variant_as_string_name(const godot_variant *p_self);
godot_node_path GDAPI godot_variant_as_node_path(const godot_variant *p_self);
godot_rid GDAPI godot_variant_as_rid(const godot_variant *p_self);
godot_object GDAPI *godot_variant_as_object(const godot_variant *p_self);
godot_callable GDAPI godot_variant_as_callable(const godot_variant *p_self);
godot_signal GDAPI godot_variant_as_signal(const godot_variant *p_self);
godot_dictionary GDAPI godot_variant_as_dictionary(const godot_variant *p_self);
godot_array GDAPI godot_variant_as_array(const godot_variant *p_self);
godot_packed_byte_array GDAPI godot_variant_as_packed_byte_array(const godot_variant *p_self);
godot_packed_int32_array GDAPI godot_variant_as_packed_int32_array(const godot_variant *p_self);
godot_packed_int64_array GDAPI godot_variant_as_packed_int64_array(const godot_variant *p_self);
godot_packed_float32_array GDAPI godot_variant_as_packed_float32_array(const godot_variant *p_self);
godot_packed_float64_array GDAPI godot_variant_as_packed_float64_array(const godot_variant *p_self);
godot_packed_string_array GDAPI godot_variant_as_packed_string_array(const godot_variant *p_self);
godot_packed_vector2_array GDAPI godot_variant_as_packed_vector2_array(const godot_variant *p_self);
godot_packed_vector3_array GDAPI godot_variant_as_packed_vector3_array(const godot_variant *p_self);
godot_packed_color_array GDAPI godot_variant_as_packed_color_array(const godot_variant *p_self);
void GDAPI godot_variant_destroy(godot_variant *p_self);
// Dynamic interaction.
void GDAPI godot_variant_call(godot_variant *p_self, const godot_string_name *p_method, const godot_variant **p_args, const godot_int p_argument_count, godot_variant *r_return, godot_variant_call_error *r_error);
void GDAPI godot_variant_call_with_cstring(godot_variant *p_self, const char *p_method, const godot_variant **p_args, const godot_int p_argument_count, godot_variant *r_return, godot_variant_call_error *r_error);
void GDAPI godot_variant_evaluate(godot_variant_operator p_op, const godot_variant *p_a, const godot_variant *p_b, godot_variant *r_return, bool *r_valid);
void GDAPI godot_variant_set(godot_variant *p_self, const godot_variant *p_key, const godot_variant *p_value, bool *r_valid);
void GDAPI godot_variant_set_named(godot_variant *p_self, const godot_string_name *p_name, const godot_variant *p_value, bool *r_valid);
void GDAPI godot_variant_set_named_with_cstring(godot_variant *p_self, const char *p_name, const godot_variant *p_value, bool *r_valid);
void GDAPI godot_variant_set_keyed(godot_variant *p_self, const godot_variant *p_key, const godot_variant *p_value, bool *r_valid);
void GDAPI godot_variant_set_indexed(godot_variant *p_self, godot_int p_index, const godot_variant *p_value, bool *r_valid, bool *r_oob);
godot_variant GDAPI godot_variant_get(const godot_variant *p_self, const godot_variant *p_key, bool *r_valid);
godot_variant GDAPI godot_variant_get_named(const godot_variant *p_self, const godot_string_name *p_key, bool *r_valid);
godot_variant GDAPI godot_variant_get_named_with_cstring(const godot_variant *p_self, const char *p_key, bool *r_valid);
godot_variant GDAPI godot_variant_get_keyed(const godot_variant *p_self, const godot_variant *p_key, bool *r_valid);
godot_variant GDAPI godot_variant_get_indexed(const godot_variant *p_self, godot_int p_index, bool *r_valid, bool *r_oob);
/// Iteration.
bool GDAPI godot_variant_iter_init(const godot_variant *p_self, godot_variant *r_iter, bool *r_valid);
bool GDAPI godot_variant_iter_next(const godot_variant *p_self, godot_variant *r_iter, bool *r_valid);
godot_variant GDAPI godot_variant_iter_get(const godot_variant *p_self, godot_variant *r_iter, bool *r_valid);
/// Variant functions.
godot_bool GDAPI godot_variant_hash_compare(const godot_variant *p_self, const godot_variant *p_other);
godot_bool GDAPI godot_variant_booleanize(const godot_variant *p_self);
void GDAPI godot_variant_blend(const godot_variant *p_a, const godot_variant *p_b, float p_c, godot_variant *r_dst);
void GDAPI godot_variant_interpolate(const godot_variant *p_a, const godot_variant *p_b, float p_c, godot_variant *r_dst);
godot_variant GDAPI godot_variant_duplicate(const godot_variant *p_self, godot_bool p_deep);
godot_string GDAPI godot_variant_stringify(const godot_variant *p_self);
// Discovery API.
/// Operators.
godot_validated_operator_evaluator GDAPI godot_variant_get_validated_operator_evaluator(godot_variant_operator p_operator, godot_variant_type p_type_a, godot_variant_type p_type_b);
godot_ptr_operator_evaluator GDAPI godot_variant_get_ptr_operator_evaluator(godot_variant_operator p_operator, godot_variant_type p_type_a, godot_variant_type p_type_b);
godot_variant_type GDAPI godot_variant_get_operator_return_type(godot_variant_operator p_operator, godot_variant_type p_type_a, godot_variant_type p_type_b);
godot_string GDAPI godot_variant_get_operator_name(godot_variant_operator p_operator);
/// Built-in methods.
bool GDAPI godot_variant_has_builtin_method(godot_variant_type p_type, const godot_string_name *p_method);
bool GDAPI godot_variant_has_builtin_method_with_cstring(godot_variant_type p_type, const char *p_method);
godot_validated_builtin_method GDAPI godot_variant_get_validated_builtin_method(godot_variant_type p_type, const godot_string_name *p_method);
godot_validated_builtin_method GDAPI godot_variant_get_validated_builtin_method_with_cstring(godot_variant_type p_type, const char *p_method);
godot_ptr_builtin_method GDAPI godot_variant_get_ptr_builtin_method(godot_variant_type p_type, const godot_string_name *p_method);
godot_ptr_builtin_method GDAPI godot_variant_get_ptr_builtin_method_with_cstring(godot_variant_type p_type, const char *p_method);
int GDAPI godot_variant_get_builtin_method_argument_count(godot_variant_type p_type, const godot_string_name *p_method);
int GDAPI godot_variant_get_builtin_method_argument_count_with_cstring(godot_variant_type p_type, const char *p_method);
godot_variant_type GDAPI godot_variant_get_builtin_method_argument_type(godot_variant_type p_type, const godot_string_name *p_method, int p_argument);
godot_variant_type GDAPI godot_variant_get_builtin_method_argument_type_with_cstring(godot_variant_type p_type, const char *p_method, int p_argument);
godot_string GDAPI godot_variant_get_builtin_method_argument_name(godot_variant_type p_type, const godot_string_name *p_method, int p_argument);
godot_string GDAPI godot_variant_get_builtin_method_argument_name_with_cstring(godot_variant_type p_type, const char *p_method, int p_argument);
bool GDAPI godot_variant_has_builtin_method_return_value(godot_variant_type p_type, const godot_string_name *p_method);
bool GDAPI godot_variant_has_builtin_method_return_value_with_cstring(godot_variant_type p_type, const char *p_method);
godot_variant_type GDAPI godot_variant_get_builtin_method_return_type(godot_variant_type p_type, const godot_string_name *p_method);
godot_variant_type GDAPI godot_variant_get_builtin_method_return_type_with_cstring(godot_variant_type p_type, const char *p_method);
bool GDAPI godot_variant_is_builtin_method_const(godot_variant_type p_type, const godot_string_name *p_method);
bool GDAPI godot_variant_is_builtin_method_const_with_cstring(godot_variant_type p_type, const char *p_method);
bool GDAPI godot_variant_is_builtin_method_vararg(godot_variant_type p_type, const godot_string_name *p_method);
bool GDAPI godot_variant_is_builtin_method_vararg_with_cstring(godot_variant_type p_type, const char *p_method);
int GDAPI godot_variant_get_builtin_method_count(godot_variant_type p_type);
void GDAPI godot_variant_get_builtin_method_list(godot_variant_type p_type, godot_string_name *r_list);
/// Constructors.
int GDAPI godot_variant_get_constructor_count(godot_variant_type p_type);
godot_validated_constructor GDAPI godot_variant_get_validated_constructor(godot_variant_type p_type, int p_constructor);
godot_ptr_constructor GDAPI godot_variant_get_ptr_constructor(godot_variant_type p_type, int p_constructor);
int GDAPI godot_variant_get_constructor_argument_count(godot_variant_type p_type, int p_constructor);
godot_variant_type GDAPI godot_variant_get_constructor_argument_type(godot_variant_type p_type, int p_constructor, int p_argument);
godot_string GDAPI godot_variant_get_constructor_argument_name(godot_variant_type p_type, int p_constructor, int p_argument);
void GDAPI godot_variant_construct(godot_variant_type p_type, godot_variant *p_base, const godot_variant **p_args, int p_argument_count, godot_variant_call_error *r_error);
/// Properties.
godot_variant_type GDAPI godot_variant_get_member_type(godot_variant_type p_type, const godot_string_name *p_member);
godot_variant_type GDAPI godot_variant_get_member_type_with_cstring(godot_variant_type p_type, const char *p_member);
int GDAPI godot_variant_get_member_count(godot_variant_type p_type);
void GDAPI godot_variant_get_member_list(godot_variant_type p_type, godot_string_name *r_list);
godot_validated_setter GDAPI godot_variant_get_validated_setter(godot_variant_type p_type, const godot_string_name *p_member);
godot_validated_setter GDAPI godot_variant_get_validated_setter_with_cstring(godot_variant_type p_type, const char *p_member);
godot_validated_getter GDAPI godot_variant_get_validated_getter(godot_variant_type p_type, const godot_string_name *p_member);
godot_validated_getter GDAPI godot_variant_get_validated_getter_with_cstring(godot_variant_type p_type, const char *p_member);
godot_ptr_setter GDAPI godot_variant_get_ptr_setter(godot_variant_type p_type, const godot_string_name *p_member);
godot_ptr_setter GDAPI godot_variant_get_ptr_setter_with_cstring(godot_variant_type p_type, const char *p_member);
godot_ptr_getter GDAPI godot_variant_get_ptr_getter(godot_variant_type p_type, const godot_string_name *p_member);
godot_ptr_getter GDAPI godot_variant_get_ptr_getter_with_cstring(godot_variant_type p_type, const char *p_member);
/// Indexing.
bool GDAPI godot_variant_has_indexing(godot_variant_type p_type);
godot_variant_type GDAPI godot_variant_get_indexed_element_type(godot_variant_type p_type);
godot_validated_indexed_setter GDAPI godot_variant_get_validated_indexed_setter(godot_variant_type p_type);
godot_validated_indexed_getter GDAPI godot_variant_get_validated_indexed_getter(godot_variant_type p_type);
godot_ptr_indexed_setter GDAPI godot_variant_get_ptr_indexed_setter(godot_variant_type p_type);
godot_ptr_indexed_getter GDAPI godot_variant_get_ptr_indexed_getter(godot_variant_type p_type);
uint64_t GDAPI godot_variant_get_indexed_size(const godot_variant *p_self);
/// Keying.
bool GDAPI godot_variant_is_keyed(godot_variant_type p_type);
godot_validated_keyed_setter GDAPI godot_variant_get_validated_keyed_setter(godot_variant_type p_type);
godot_validated_keyed_getter GDAPI godot_variant_get_validated_keyed_getter(godot_variant_type p_type);
godot_validated_keyed_checker GDAPI godot_variant_get_validated_keyed_checker(godot_variant_type p_type);
godot_ptr_keyed_setter GDAPI godot_variant_get_ptr_keyed_setter(godot_variant_type p_type);
godot_ptr_keyed_getter GDAPI godot_variant_get_ptr_keyed_getter(godot_variant_type p_type);
godot_ptr_keyed_checker GDAPI godot_variant_get_ptr_keyed_checker(godot_variant_type p_type);
/// Constants.
int GDAPI godot_variant_get_constants_count(godot_variant_type p_type);
void GDAPI godot_variant_get_constants_list(godot_variant_type p_type, godot_string_name *r_list);
bool GDAPI godot_variant_has_constant(godot_variant_type p_type, const godot_string_name *p_constant);
bool GDAPI godot_variant_has_constant_with_cstring(godot_variant_type p_type, const char *p_constant);
godot_variant GDAPI godot_variant_get_constant_value(godot_variant_type p_type, const godot_string_name *p_constant);
godot_variant GDAPI godot_variant_get_constant_value_with_cstring(godot_variant_type p_type, const char *p_constant);
/// Utilities.
bool GDAPI godot_variant_has_utility_function(const godot_string_name *p_function);
bool GDAPI godot_variant_has_utility_function_with_cstring(const char *p_function);
void GDAPI godot_variant_call_utility_function(const godot_string_name *p_function, godot_variant *r_ret, const godot_variant **p_args, int p_argument_count, godot_variant_call_error *r_error);
void GDAPI godot_variant_call_utility_function_with_cstring(const char *p_function, godot_variant *r_ret, const godot_variant **p_args, int p_argument_count, godot_variant_call_error *r_error);
godot_variant_utility_function_type GDAPI godot_variant_get_utility_function_type(const godot_string_name *p_function);
godot_variant_utility_function_type GDAPI godot_variant_get_utility_function_type_with_cstring(const char *p_function);
int GDAPI godot_variant_get_utility_function_argument_count(const godot_string_name *p_function);
int GDAPI godot_variant_get_utility_function_argument_count_with_cstring(const char *p_function);
godot_variant_type GDAPI godot_variant_get_utility_function_argument_type(const godot_string_name *p_function, int p_argument);
godot_variant_type GDAPI godot_variant_get_utility_function_argument_type_with_cstring(const char *p_function, int p_argument);
godot_string GDAPI godot_variant_get_utility_function_argument_name(const godot_string_name *p_function, int p_argument);
godot_string GDAPI godot_variant_get_utility_function_argument_name_with_cstring(const char *p_function, int p_argument);
bool GDAPI godot_variant_has_utility_function_return_value(const godot_string_name *p_function);
bool GDAPI godot_variant_has_utility_function_return_value_with_cstring(const char *p_function);
godot_variant_type GDAPI godot_variant_get_utility_function_return_type(const godot_string_name *p_function);
godot_variant_type GDAPI godot_variant_get_utility_function_return_type_with_cstring(const char *p_function);
bool GDAPI godot_variant_is_utility_function_vararg(const godot_string_name *p_function);
bool GDAPI godot_variant_is_utility_function_vararg_with_cstring(const char *p_function);
int GDAPI godot_variant_get_utility_function_count();
void GDAPI godot_variant_get_utility_function_list(godot_string_name *r_functions);
// Introspection.
godot_variant_type GDAPI godot_variant_get_type(const godot_variant *p_self);
bool GDAPI godot_variant_has_method(const godot_variant *p_self, const godot_string_name *p_method);
bool GDAPI godot_variant_has_member(godot_variant_type p_type, const godot_string_name *p_member);
bool GDAPI godot_variant_has_key(const godot_variant *p_self, const godot_variant *p_key, bool *r_valid);
godot_string GDAPI godot_variant_get_type_name(godot_variant_type p_type);
bool GDAPI godot_variant_can_convert(godot_variant_type p_from, godot_variant_type p_to);
bool GDAPI godot_variant_can_convert_strict(godot_variant_type p_from, godot_variant_type p_to);
#ifdef __cplusplus
}
#endif
#endif
| 65.455399 | 212 | 0.836681 | [
"transform"
] |
82c3e8335abdb570b476365a3099882eb97928e6 | 413 | c | C | adm/simul_efun/archp.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-07-19T05:24:44.000Z | 2021-11-18T04:08:19.000Z | adm/simul_efun/archp.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 4 | 2021-03-15T18:56:39.000Z | 2021-08-17T17:08:22.000Z | adm/simul_efun/archp.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-09-12T06:22:38.000Z | 2022-01-31T01:15:12.000Z | // /adm/simul_efun/archp.c
// from the Nightmare mudlib
// returns true if a player is an arch
// created by Descartes of Borg 18 february 1993
int archp(object ob) {
string who;
if(!ob) return 0;
if(!userp(ob)) return 0;
who = (string)ob->query_name();
if(!objectp(ob)) return 0;
if(!wizardp(ob)) return 0;
return (member_group(who, "assist") || member_group(who, "superuser"));
}
| 24.294118 | 75 | 0.646489 | [
"object"
] |
82c50dfea56b1b92deb21a4ce2d98ef187f7a0ed | 8,239 | h | C | third-party/slapi/mac/LayOutAPI.framework/headers/model/grid.h | TommyKaneko/SketchUp-API-C-Wrapper | 6879346ce7ca292962e40246e4f587020fcc9273 | [
"MIT"
] | null | null | null | third-party/slapi/mac/LayOutAPI.framework/headers/model/grid.h | TommyKaneko/SketchUp-API-C-Wrapper | 6879346ce7ca292962e40246e4f587020fcc9273 | [
"MIT"
] | null | null | null | third-party/slapi/mac/LayOutAPI.framework/headers/model/grid.h | TommyKaneko/SketchUp-API-C-Wrapper | 6879346ce7ca292962e40246e4f587020fcc9273 | [
"MIT"
] | null | null | null | // Copyright 2015-2020 Trimble Inc. All rights reserved.
// This file is intended for public distribution.
#ifndef LAYOUT_MODEL_GRID_H_
#define LAYOUT_MODEL_GRID_H_
#include <LayOutAPI/common.h>
#include <LayOutAPI/model/defs.h>
#include <SketchUpAPI/color.h>
/**
@struct LOGridRef
@brief References a document's grid settings.
*/
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
/**
@brief Gets the major space size of the grid.
@param[in] grid The grid object.
@param[out] spacing The spacing of the major divisions of the grid.
@return
- \ref SU_ERROR_NONE on success
- \ref SU_ERROR_INVALID_INPUT if grid does not refer to a valid object
- \ref SU_ERROR_NULL_POINTER_OUTPUT if spacing is NULL
*/
LO_RESULT LOGridGetMajorSpacing(LOGridRef grid, double* spacing);
/**
@brief Sets the gap between major grid lines for the grid.
@since LayOut 2020.1, API 5.1
@param[in] grid The grid object.
@param[in] divisions The number of minor grid lines to have between major
grid lines. Must be positive.
@return
- \ref SU_ERROR_NONE on success
- \ref SU_ERROR_INVALID_INPUT if grid does not refer to a valid object
- \ref SU_ERROR_OUT_OF_RANGE if divisions is less than zero
*/
LO_RESULT LOGridSetMajorSpacing(LOGridRef grid, double spacing);
/**
@brief Gets the number of minor divisions of the grid.
@param[in] grid The grid object.
@param[out] divisions The minor division count.
@return
- \ref SU_ERROR_NONE on success
- \ref SU_ERROR_INVALID_INPUT if grid does not refer to a valid object
- \ref SU_ERROR_NULL_POINTER_OUTPUT if divisions is NULL
*/
LO_RESULT LOGridGetMinorDivisions(LOGridRef grid, int* divisions);
/**
@brief Sets the number of minor divisions for the grid.
@since LayOut 2020.1, API 5.1
@param[in] grid The grid object.
@param[in] divisions The number of minor grid lines to have between major
grid lines. Must not be negative.
@return
- \ref SU_ERROR_NONE on success
- \ref SU_ERROR_INVALID_INPUT if grid does not refer to a valid object
- \ref SU_ERROR_OUT_OF_RANGE if divisions is less than zero
*/
LO_RESULT LOGridSetMinorDivisions(LOGridRef grid, int divisions);
/**
@brief Gets the color for the major grid lines.
@param[in] grid The grid object.
@param[out] color The color of the major grid lines.
@return
- \ref SU_ERROR_NONE on success
- \ref SU_ERROR_INVALID_INPUT if grid does not refer to a valid object
- \ref SU_ERROR_NULL_POINTER_OUTPUT if color is NULL
*/
LO_RESULT LOGridGetMajorColor(LOGridRef grid, SUColor* color);
/**
@brief Sets the color for the major grid lines.
@since LayOut 2020.1, API 5.1
@param[in] grid The grid object.
@param[in] color The new color for the major grid lines.
@return
- \ref SU_ERROR_NONE on success
- \ref SU_ERROR_INVALID_INPUT if grid does not refer to a valid object
*/
LO_RESULT LOGridSetMajorColor(LOGridRef grid, SUColor color);
/**
@brief Gets the color for the minor grid lines.
@param[in] grid The grid object.
@param[out] color The color of the minor grid lines.
@return
- \ref SU_ERROR_NONE on success
- \ref SU_ERROR_INVALID_INPUT if grid does not refer to a valid object
- \ref SU_ERROR_NULL_POINTER_OUTPUT if color is NULL
*/
LO_RESULT LOGridGetMinorColor(LOGridRef grid, SUColor* color);
/**
@brief Sets the color for the minor grid lines.
@since LayOut 2020.1, API 5.1
@param[in] grid The grid object.
@param[in] color The new color for the minor grid lines.
@return
- \ref SU_ERROR_NONE on success
- \ref SU_ERROR_INVALID_INPUT if grid does not refer to a valid object
*/
LO_RESULT LOGridSetMinorColor(LOGridRef grid, SUColor color);
/**
@brief Gets whether or not the grid is visible.
@param[in] grid The grid object.
@param[out] show Whether or not the grid is visible.
@return
- \ref SU_ERROR_NONE on success
- \ref SU_ERROR_INVALID_INPUT if grid does not refer to a valid object
- \ref SU_ERROR_NULL_POINTER_OUTPUT if show is NULL
*/
LO_RESULT LOGridGetShow(LOGridRef grid, bool* show);
/**
@brief Sets whether or not the grid is visible.
@since LayOut 2020.1, API 5.1
@param[in] grid The grid object.
@param[in] show Whether or not the grid is visible.
@return
- \ref SU_ERROR_NONE on success
- \ref SU_ERROR_INVALID_INPUT if grid does not refer to a valid object
*/
LO_RESULT LOGridSetShow(LOGridRef grid, bool show);
/**
@brief Gets whether or not the major grid lines are visible.
@param[in] grid The grid object.
@param[out] show Whether or not the major grid lines are visible.
@return
- \ref SU_ERROR_NONE on success
- \ref SU_ERROR_INVALID_INPUT if grid does not refer to a valid object
- \ref SU_ERROR_NULL_POINTER_OUTPUT if show is NULL
*/
LO_RESULT LOGridGetShowMajor(LOGridRef grid, bool* show);
/**
@brief Sets whether or not the major grid lines are visible.
@since LayOut 2020.1, API 5.1
@param[in] grid The grid object.
@param[in] show Whether or not the major grid lines are visible.
@return
- \ref SU_ERROR_NONE on success
- \ref SU_ERROR_INVALID_INPUT if grid does not refer to a valid object
*/
LO_RESULT LOGridSetShowMajor(LOGridRef grid, bool show);
/**
@brief Gets whether or not the minor grid lines are visible.
@param[in] grid The grid object.
@param[out] show Whether or not the minor grid lines are visible.
@return
- \ref SU_ERROR_NONE on success
- \ref SU_ERROR_INVALID_INPUT if grid does not refer to a valid object
- \ref SU_ERROR_NULL_POINTER_OUTPUT if show is NULL
*/
LO_RESULT LOGridGetShowMinor(LOGridRef grid, bool* show);
/**
@brief Sets whether or not the minor grid lines are visible.
@since LayOut 2020.1, API 5.1
@param[in] grid The grid object.
@param[in] show Whether or not the minor grid lines are visible.
@return
- \ref SU_ERROR_NONE on success
- \ref SU_ERROR_INVALID_INPUT if grid does not refer to a valid object
*/
LO_RESULT LOGridSetShowMinor(LOGridRef grid, bool show);
/**
@brief Gets whether or not the grid will be printed.
@param[in] grid The grid object.
@param[out] print Whether or not the grid will be printed.
@return
- \ref SU_ERROR_NONE on success
- \ref SU_ERROR_INVALID_INPUT if grid does not refer to a valid object
- \ref SU_ERROR_NULL_POINTER_OUTPUT if print is NULL
*/
LO_RESULT LOGridGetPrint(LOGridRef grid, bool* print);
/**
@brief Sets whether or not the grid is will be printed.
@since LayOut 2020.1, API 5.1
@param[in] grid The grid object.
@param[in] print Whether or not the grid will be printed.
@return
- \ref SU_ERROR_NONE on success
- \ref SU_ERROR_INVALID_INPUT if grid does not refer to a valid object
*/
LO_RESULT LOGridSetPrint(LOGridRef grid, bool print);
/**
@brief Gets whether or not the grid is drawn on top of entities.
@since LayOut 2020.1, API 5.1
@param[in] grid The grid object.
@param[out] in_front Whether or not the grid is on top of entities.
@return
- \ref SU_ERROR_NONE on success
- \ref SU_ERROR_INVALID_INPUT if grid does not refer to a valid object
- \ref SU_ERROR_NULL_POINTER_OUTPUT if in_front is NULL
*/
LO_RESULT LOGridGetInFront(LOGridRef grid, bool* in_front);
/**
@brief Sets whether or not the grid is drawn on top of entities.
@since LayOut 2020.1, API 5.1
@param[in] grid The grid object.
@param[in] in_front Whether or not the grid is on top of entities.
@return
- \ref SU_ERROR_NONE on success
- \ref SU_ERROR_INVALID_INPUT if grid does not refer to a valid object
*/
LO_RESULT LOGridSetInFront(LOGridRef grid, bool in_front);
/**
@brief Gets whether or not the grid is clipped to the paper margins.
@since LayOut 2020.1, API 5.1
@param[in] grid The grid object.
@param[out] clip Whether or not the grid is on top of entities.
@return
- \ref SU_ERROR_NONE on success
- \ref SU_ERROR_INVALID_INPUT if grid does not refer to a valid object
- \ref SU_ERROR_NULL_POINTER_OUTPUT if clipped is NULL
*/
LO_RESULT LOGridGetClipToMargins(LOGridRef grid, bool* clip);
/**
@brief Sets whether or not the grid is clipped to the paper margins.
@since LayOut 2020.1, API 5.1
@param[in] grid The grid object.
@param[in] clip Whether or not the grid is clipped to the paper margins.
@return
- \ref SU_ERROR_NONE on success
- \ref SU_ERROR_INVALID_INPUT if grid does not refer to a valid object
*/
LO_RESULT LOGridSetClipToMargins(LOGridRef grid, bool clip);
#ifdef __cplusplus
}
#endif // __cplusplus
#endif // LAYOUT_MODEL_GRID_H_
| 32.694444 | 73 | 0.762107 | [
"object",
"model"
] |
82c568b59081276e2642ba48b7eb9c2e1c163b6e | 5,323 | h | C | test/cctest/compiler/simplified-graph-builder.h | ConnectionMaster/v8 | f78806eadde090709536d270a0486badb1521d18 | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | 1 | 2016-01-29T18:07:44.000Z | 2016-01-29T18:07:44.000Z | test/cctest/compiler/simplified-graph-builder.h | ConnectionMaster/v8 | f78806eadde090709536d270a0486badb1521d18 | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | null | null | null | test/cctest/compiler/simplified-graph-builder.h | ConnectionMaster/v8 | f78806eadde090709536d270a0486badb1521d18 | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | 4 | 2015-08-30T19:51:38.000Z | 2019-05-08T02:14:42.000Z | // Copyright 2014 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_CCTEST_COMPILER_SIMPLIFIED_GRAPH_BUILDER_H_
#define V8_CCTEST_COMPILER_SIMPLIFIED_GRAPH_BUILDER_H_
#include "src/compiler/common-operator.h"
#include "src/compiler/graph-builder.h"
#include "src/compiler/machine-operator.h"
#include "src/compiler/simplified-operator.h"
#include "test/cctest/cctest.h"
#include "test/cctest/compiler/call-tester.h"
namespace v8 {
namespace internal {
namespace compiler {
class SimplifiedGraphBuilder : public GraphBuilder {
public:
SimplifiedGraphBuilder(Graph* graph, CommonOperatorBuilder* common,
MachineOperatorBuilder* machine,
SimplifiedOperatorBuilder* simplified);
virtual ~SimplifiedGraphBuilder() {}
Zone* zone() const { return graph()->zone(); }
Isolate* isolate() const { return zone()->isolate(); }
CommonOperatorBuilder* common() const { return common_; }
MachineOperatorBuilder* machine() const { return machine_; }
SimplifiedOperatorBuilder* simplified() const { return simplified_; }
// Initialize graph and builder.
void Begin(int num_parameters);
void Return(Node* value);
// Close the graph.
void End();
Node* PointerConstant(void* value) {
intptr_t intptr_value = reinterpret_cast<intptr_t>(value);
return kPointerSize == 8 ? NewNode(common()->Int64Constant(intptr_value))
: Int32Constant(static_cast<int>(intptr_value));
}
Node* Int32Constant(int32_t value) {
return NewNode(common()->Int32Constant(value));
}
Node* HeapConstant(Handle<HeapObject> object) {
Unique<HeapObject> val = Unique<HeapObject>::CreateUninitialized(object);
return NewNode(common()->HeapConstant(val));
}
Node* BooleanNot(Node* a) { return NewNode(simplified()->BooleanNot(), a); }
Node* NumberEqual(Node* a, Node* b) {
return NewNode(simplified()->NumberEqual(), a, b);
}
Node* NumberLessThan(Node* a, Node* b) {
return NewNode(simplified()->NumberLessThan(), a, b);
}
Node* NumberLessThanOrEqual(Node* a, Node* b) {
return NewNode(simplified()->NumberLessThanOrEqual(), a, b);
}
Node* NumberAdd(Node* a, Node* b) {
return NewNode(simplified()->NumberAdd(), a, b);
}
Node* NumberSubtract(Node* a, Node* b) {
return NewNode(simplified()->NumberSubtract(), a, b);
}
Node* NumberMultiply(Node* a, Node* b) {
return NewNode(simplified()->NumberMultiply(), a, b);
}
Node* NumberDivide(Node* a, Node* b) {
return NewNode(simplified()->NumberDivide(), a, b);
}
Node* NumberModulus(Node* a, Node* b) {
return NewNode(simplified()->NumberModulus(), a, b);
}
Node* NumberToInt32(Node* a) {
return NewNode(simplified()->NumberToInt32(), a);
}
Node* NumberToUint32(Node* a) {
return NewNode(simplified()->NumberToUint32(), a);
}
Node* StringEqual(Node* a, Node* b) {
return NewNode(simplified()->StringEqual(), a, b);
}
Node* StringLessThan(Node* a, Node* b) {
return NewNode(simplified()->StringLessThan(), a, b);
}
Node* StringLessThanOrEqual(Node* a, Node* b) {
return NewNode(simplified()->StringLessThanOrEqual(), a, b);
}
Node* StringAdd(Node* a, Node* b) {
return NewNode(simplified()->StringAdd(), a, b);
}
Node* ChangeTaggedToInt32(Node* a) {
return NewNode(simplified()->ChangeTaggedToInt32(), a);
}
Node* ChangeTaggedToUint32(Node* a) {
return NewNode(simplified()->ChangeTaggedToUint32(), a);
}
Node* ChangeTaggedToFloat64(Node* a) {
return NewNode(simplified()->ChangeTaggedToFloat64(), a);
}
Node* ChangeInt32ToTagged(Node* a) {
return NewNode(simplified()->ChangeInt32ToTagged(), a);
}
Node* ChangeUint32ToTagged(Node* a) {
return NewNode(simplified()->ChangeUint32ToTagged(), a);
}
Node* ChangeFloat64ToTagged(Node* a) {
return NewNode(simplified()->ChangeFloat64ToTagged(), a);
}
Node* ChangeBoolToBit(Node* a) {
return NewNode(simplified()->ChangeBoolToBit(), a);
}
Node* ChangeBitToBool(Node* a) {
return NewNode(simplified()->ChangeBitToBool(), a);
}
Node* LoadField(const FieldAccess& access, Node* object) {
return NewNode(simplified()->LoadField(access), object);
}
Node* StoreField(const FieldAccess& access, Node* object, Node* value) {
return NewNode(simplified()->StoreField(access), object, value);
}
Node* LoadElement(const ElementAccess& access, Node* object, Node* index,
Node* length) {
return NewNode(simplified()->LoadElement(access), object, index, length);
}
Node* StoreElement(const ElementAccess& access, Node* object, Node* index,
Node* length, Node* value) {
return NewNode(simplified()->StoreElement(access), object, index, length,
value);
}
protected:
virtual Node* MakeNode(const Operator* op, int value_input_count,
Node** value_inputs) FINAL;
private:
Node* effect_;
Node* return_;
CommonOperatorBuilder* common_;
MachineOperatorBuilder* machine_;
SimplifiedOperatorBuilder* simplified_;
};
} // namespace compiler
} // namespace internal
} // namespace v8
#endif // V8_CCTEST_COMPILER_SIMPLIFIED_GRAPH_BUILDER_H_
| 33.904459 | 78 | 0.684201 | [
"object"
] |
82c5ab9ae9315eff1ce713ee54da171dcb0873c6 | 2,423 | c | C | GraphBLAS/Source/GrB_Col_assign.c | puckbee/suitesparse | 306d7f11792aca524571f4ae142bcd8b7e38c362 | [
"Apache-2.0"
] | 29 | 2019-11-27T00:43:07.000Z | 2020-02-25T14:35:54.000Z | GraphBLAS/Source/GrB_Col_assign.c | puckbee/suitesparse | 306d7f11792aca524571f4ae142bcd8b7e38c362 | [
"Apache-2.0"
] | null | null | null | GraphBLAS/Source/GrB_Col_assign.c | puckbee/suitesparse | 306d7f11792aca524571f4ae142bcd8b7e38c362 | [
"Apache-2.0"
] | 4 | 2019-11-27T05:19:03.000Z | 2020-03-23T22:49:53.000Z | //------------------------------------------------------------------------------
// GrB_Col_assign: C<mask>(I,j) = accum (C(I,j),u)
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2018, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
#include "GB.h"
GrB_Info GrB_Col_assign // C<mask>(I,j) = accum (C(I,j),u)
(
GrB_Matrix C, // input/output matrix for results
const GrB_Vector mask, // optional mask for C(:,j), unused if NULL
const GrB_BinaryOp accum, // optional accum for z=accum(C(I,j),t)
const GrB_Vector u, // input vector
const GrB_Index *I, // row indices
const GrB_Index ni, // number of row indices
const GrB_Index j, // column index
const GrB_Descriptor desc // descriptor for C(:,j) and mask
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
WHERE ("GrB_Col_assign (C, mask, accum, u, I, ni, j, desc)") ;
RETURN_IF_NULL_OR_UNINITIALIZED (C) ;
RETURN_IF_UNINITIALIZED (mask) ;
RETURN_IF_NULL_OR_UNINITIALIZED (u) ;
// get the descriptor
GET_DESCRIPTOR (info, desc, C_replace, Mask_comp, ignore1, ignore2) ;
//--------------------------------------------------------------------------
// C(I,j)<mask> = accum (C(I,j), u) and variations
//--------------------------------------------------------------------------
// construct the column index list J = [ j ] of length nj = 1
GrB_Index J [1] ;
J [0] = j ;
return (GB_assign (
C, C_replace, // C matrix and its descriptor
(GrB_Matrix) mask, Mask_comp, // mask and its descriptor
accum, // for accum (C(I,j),u)
(GrB_Matrix) u, false, // u as a matrix; never transposed
I, ni, // row indices
J, 1, // column indices
false, NULL, 0, // no scalar expansion
true, false)) ; // GrB_Col_assign
}
| 42.508772 | 80 | 0.413124 | [
"vector"
] |
82c8d6de784ea51075f61aa3c1974ba6ff8b3881 | 1,467 | h | C | CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/java/security/acl/Acl.h | chewaiwai/huaweicloud-sdk-c-obs | fbcd3dadd910c22af3a91aeb73ca0fee94d759fb | [
"Apache-2.0"
] | 22 | 2019-06-13T01:16:44.000Z | 2022-03-29T02:42:39.000Z | CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/java/security/acl/Acl.h | chewaiwai/huaweicloud-sdk-c-obs | fbcd3dadd910c22af3a91aeb73ca0fee94d759fb | [
"Apache-2.0"
] | 26 | 2019-09-20T06:46:05.000Z | 2022-03-11T08:07:14.000Z | CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/java/security/acl/Acl.h | chewaiwai/huaweicloud-sdk-c-obs | fbcd3dadd910c22af3a91aeb73ca0fee94d759fb | [
"Apache-2.0"
] | 14 | 2019-07-15T06:42:39.000Z | 2022-02-15T10:32:28.000Z |
// DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*-
#ifndef __java_security_acl_Acl__
#define __java_security_acl_Acl__
#pragma interface
#include <java/lang/Object.h>
extern "Java"
{
namespace java
{
namespace security
{
class Principal;
namespace acl
{
class Acl;
class AclEntry;
class Permission;
}
}
}
}
class java::security::acl::Acl : public ::java::lang::Object
{
public:
virtual ::java::lang::String * getName() = 0;
virtual void setName(::java::security::Principal *, ::java::lang::String *) = 0;
virtual jboolean addEntry(::java::security::Principal *, ::java::security::acl::AclEntry *) = 0;
virtual jboolean removeEntry(::java::security::Principal *, ::java::security::acl::AclEntry *) = 0;
virtual ::java::util::Enumeration * entries() = 0;
virtual jboolean checkPermission(::java::security::Principal *, ::java::security::acl::Permission *) = 0;
virtual ::java::util::Enumeration * getPermissions(::java::security::Principal *) = 0;
virtual ::java::lang::String * toString() = 0;
virtual jboolean addOwner(::java::security::Principal *, ::java::security::Principal *) = 0;
virtual jboolean deleteOwner(::java::security::Principal *, ::java::security::Principal *) = 0;
virtual jboolean isOwner(::java::security::Principal *) = 0;
static ::java::lang::Class class$;
} __attribute__ ((java_interface));
#endif // __java_security_acl_Acl__
| 31.891304 | 107 | 0.663258 | [
"object"
] |
82ce4078cc52569f42096ee26271df311991fbab | 698 | h | C | ViAn/Project/Analysis/interval.h | NFCSKL/NFC-ViAn | ce04b78b4c9695374d71198f57d4236a5cad1525 | [
"MIT"
] | 1 | 2019-12-08T03:53:03.000Z | 2019-12-08T03:53:03.000Z | ViAn/Project/Analysis/interval.h | NFCSKL/NFC-ViAn | ce04b78b4c9695374d71198f57d4236a5cad1525 | [
"MIT"
] | 182 | 2018-02-08T11:03:26.000Z | 2019-06-27T15:27:47.000Z | ViAn/Project/Analysis/interval.h | NFCSKL/NFC-ViAn | ce04b78b4c9695374d71198f57d4236a5cad1525 | [
"MIT"
] | null | null | null | #ifndef INTERVAL_H
#define INTERVAL_H
#include "basicanalysis.h"
#include <QJsonObject>
#include <vector>
class Interval : public BasicAnalysis
{
public:
Interval(QString name = "");
~Interval() override;
virtual int get_type() const override;
virtual void read(const QJsonObject& json) override;
virtual void write(QJsonObject& json) override;
void add_area(int start, int end);
void add_area(std::pair<int, int> interval);
void remove_area_by_frame(int frame);
void remove_area(std::pair<int, int> interval);
bool does_overlap(std::pair<int, int> a, std::pair<int, int> b);
std::vector<std::pair<int, int>> m_area_list;
};
#endif // INTERVAL_H
| 23.266667 | 68 | 0.700573 | [
"vector"
] |
82ce607612a84f70ae7162e3e6f6d78adfb59f52 | 2,575 | h | C | VulkanRenderer/VulkanRendererWindows/MainRenderer/Structs/BufferData.h | Bulletdrone/VulkanRenderer | c4aee857e33ba20d96eb3706f3a81be957164bc2 | [
"MIT"
] | null | null | null | VulkanRenderer/VulkanRendererWindows/MainRenderer/Structs/BufferData.h | Bulletdrone/VulkanRenderer | c4aee857e33ba20d96eb3706f3a81be957164bc2 | [
"MIT"
] | null | null | null | VulkanRenderer/VulkanRendererWindows/MainRenderer/Structs/BufferData.h | Bulletdrone/VulkanRenderer | c4aee857e33ba20d96eb3706f3a81be957164bc2 | [
"MIT"
] | null | null | null | #pragma once
#include <Vulkan/vulkan.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <array>
#include <vector>
struct ViewProjection
{
alignas(16) glm::mat4 view;
alignas(16) glm::mat4 proj;
};
struct InstanceModel
{
alignas(16) glm::mat4 model;
};
struct Vertex
{
glm::vec3 position;
glm::vec3 color;
glm::vec2 texCoord;
static VkVertexInputBindingDescription GetBindingDescription()
{
VkVertexInputBindingDescription t_BindingDescription{};
t_BindingDescription.binding = 0;
t_BindingDescription.stride = sizeof(Vertex);
t_BindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
return t_BindingDescription;
}
static std::array<VkVertexInputAttributeDescription, 3> GetAttributeDescriptions()
{
std::array<VkVertexInputAttributeDescription, 3> attributeDescriptions{};
attributeDescriptions[0].binding = 0;
attributeDescriptions[0].location = 0;
attributeDescriptions[0].format = VK_FORMAT_R32G32B32_SFLOAT;
attributeDescriptions[0].offset = offsetof(Vertex, position);
attributeDescriptions[1].binding = 0;
attributeDescriptions[1].location = 1;
attributeDescriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT;
attributeDescriptions[1].offset = offsetof(Vertex, color);
attributeDescriptions[2].binding = 0;
attributeDescriptions[2].location = 2;
attributeDescriptions[2].format = VK_FORMAT_R32G32_SFLOAT;
attributeDescriptions[2].offset = offsetof(Vertex, texCoord);
return attributeDescriptions;
}
};
template <typename T>
class BufferData
{
public:
BufferData(const std::vector<T> a_Elements);
~BufferData();
void DeleteBuffers(VkDevice& r_Device);
const VkDeviceSize CreateBufferSize() const;
const std::vector<T>& GetElements() const { return elements; }
const size_t GetElementCount() const { return elements.size(); }
VkBuffer& GetBuffer() { return vkBuffer; }
VkDeviceMemory& GetBufferMemory() { return vkBufferMemory; }
private:
const std::vector<T> elements;
VkBuffer vkBuffer;
VkDeviceMemory vkBufferMemory;
};
template<typename T>
inline BufferData<T>::BufferData(const std::vector<T> a_Elements)
: elements(a_Elements)
{}
template<typename T>
inline BufferData<T>::~BufferData()
{}
template<typename T>
inline void BufferData<T>::DeleteBuffers(VkDevice & r_Device)
{
vkDestroyBuffer(r_Device, vkBuffer, nullptr);
vkFreeMemory(r_Device, vkBufferMemory, nullptr);
}
template <typename T>
inline const VkDeviceSize BufferData<T>::CreateBufferSize() const //Returns the vertexBuffer in bytes.
{
return sizeof(elements[0]) * elements.size();
} | 23.842593 | 102 | 0.768155 | [
"vector",
"model"
] |
82d10906bfa88687823978558b2a08dd4ba91281 | 20,766 | c | C | usr.sbin/ppp/chat.c | masami256/dfly-3.0.2-bhyve | 6f6c18db6fa90734135a2044769035eb82b821c1 | [
"BSD-3-Clause"
] | 3 | 2017-03-06T14:12:57.000Z | 2019-11-23T09:35:10.000Z | usr.sbin/ppp/chat.c | masami256/dfly-3.0.2-bhyve | 6f6c18db6fa90734135a2044769035eb82b821c1 | [
"BSD-3-Clause"
] | null | null | null | usr.sbin/ppp/chat.c | masami256/dfly-3.0.2-bhyve | 6f6c18db6fa90734135a2044769035eb82b821c1 | [
"BSD-3-Clause"
] | null | null | null | /*-
* Copyright (c) 1998 Brian Somers <brian@Awfulhak.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 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 AUTHOR 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 AUTHOR 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.
*
* $FreeBSD: src/usr.sbin/ppp/chat.c,v 1.70.2.3 2002/09/01 02:12:23 brian Exp $
* $DragonFly: src/usr.sbin/ppp/chat.c,v 1.2 2003/06/17 04:30:00 dillon Exp $
*/
#include <sys/param.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>
#include <fcntl.h>
#include <paths.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <termios.h>
#include <unistd.h>
#include "layer.h"
#include "mbuf.h"
#include "log.h"
#include "defs.h"
#include "timer.h"
#include "lqr.h"
#include "hdlc.h"
#include "throughput.h"
#include "fsm.h"
#include "lcp.h"
#include "ccp.h"
#include "link.h"
#include "async.h"
#include "descriptor.h"
#include "physical.h"
#include "chat.h"
#include "mp.h"
#include "auth.h"
#include "chap.h"
#include "slcompress.h"
#include "iplist.h"
#include "ncpaddr.h"
#include "ipcp.h"
#include "filter.h"
#include "cbcp.h"
#include "command.h"
#include "datalink.h"
#ifndef NORADIUS
#include "radius.h"
#endif
#include "ipv6cp.h"
#include "ncp.h"
#include "bundle.h"
#include "id.h"
#define BUFLEFT(c) (sizeof (c)->buf - ((c)->bufend - (c)->buf))
static void ExecStr(struct physical *, char *, char *, int);
static char *ExpandString(struct chat *, const char *, char *, int, int);
static void
chat_PauseTimer(void *v)
{
struct chat *c = (struct chat *)v;
timer_Stop(&c->pause);
c->pause.load = 0;
}
static void
chat_Pause(struct chat *c, u_long load)
{
timer_Stop(&c->pause);
c->pause.load += load;
c->pause.func = chat_PauseTimer;
c->pause.name = "chat pause";
c->pause.arg = c;
timer_Start(&c->pause);
}
static void
chat_TimeoutTimer(void *v)
{
struct chat *c = (struct chat *)v;
timer_Stop(&c->timeout);
c->TimedOut = 1;
}
static void
chat_SetTimeout(struct chat *c)
{
timer_Stop(&c->timeout);
if (c->TimeoutSec > 0) {
c->timeout.load = SECTICKS * c->TimeoutSec;
c->timeout.func = chat_TimeoutTimer;
c->timeout.name = "chat timeout";
c->timeout.arg = c;
timer_Start(&c->timeout);
}
}
static char *
chat_NextChar(char *ptr, char ch)
{
for (; *ptr; ptr++)
if (*ptr == ch)
return ptr;
else if (*ptr == '\\')
if (*++ptr == '\0')
return NULL;
return NULL;
}
static int
chat_UpdateSet(struct fdescriptor *d, fd_set *r, fd_set *w, fd_set *e, int *n)
{
struct chat *c = descriptor2chat(d);
int special, gotabort, gottimeout, needcr;
int TimedOut = c->TimedOut;
static char arg_term; /* An empty string */
if (c->pause.state == TIMER_RUNNING)
return 0;
if (TimedOut) {
log_Printf(LogCHAT, "Expect timeout\n");
if (c->nargptr == NULL)
c->state = CHAT_FAILED;
else {
/* c->state = CHAT_EXPECT; */
c->argptr = &arg_term;
}
c->TimedOut = 0;
}
if (c->state != CHAT_EXPECT && c->state != CHAT_SEND)
return 0;
gottimeout = gotabort = 0;
if (c->arg < c->argc && (c->arg < 0 || *c->argptr == '\0')) {
/* Go get the next string */
if (c->arg < 0 || c->state == CHAT_SEND)
c->state = CHAT_EXPECT;
else
c->state = CHAT_SEND;
special = 1;
while (special && (c->nargptr || c->arg < c->argc - 1)) {
if (c->arg < 0 || (!TimedOut && c->state == CHAT_SEND))
c->nargptr = NULL;
if (c->nargptr != NULL) {
/* We're doing expect-send-expect.... */
c->argptr = c->nargptr;
/* Put the '-' back in case we ever want to rerun our script */
c->nargptr[-1] = '-';
c->nargptr = chat_NextChar(c->nargptr, '-');
if (c->nargptr != NULL)
*c->nargptr++ = '\0';
} else {
int minus;
if ((c->argptr = c->argv[++c->arg]) == NULL) {
/* End of script - all ok */
c->state = CHAT_DONE;
return 0;
}
if (c->state == CHAT_EXPECT) {
/* Look for expect-send-expect sequence */
c->nargptr = c->argptr;
minus = 0;
while ((c->nargptr = chat_NextChar(c->nargptr, '-'))) {
c->nargptr++;
minus++;
}
if (minus % 2)
log_Printf(LogWARN, "chat_UpdateSet: \"%s\": Uneven number of"
" '-' chars, all ignored\n", c->argptr);
else if (minus) {
c->nargptr = chat_NextChar(c->argptr, '-');
*c->nargptr++ = '\0';
}
}
}
/*
* c->argptr now temporarily points into c->script (via c->argv)
* If it's an expect-send-expect sequence, we've just got the correct
* portion of that sequence.
*/
needcr = c->state == CHAT_SEND &&
(*c->argptr != '!' || c->argptr[1] == '!');
/* We leave room for a potential HDLC header in the target string */
ExpandString(c, c->argptr, c->exp + 2, sizeof c->exp - 2, needcr);
/*
* Now read our string. If it's not a special string, we unset
* ``special'' to break out of the loop.
*/
if (gotabort) {
if (c->abort.num < MAXABORTS) {
int len, i;
len = strlen(c->exp+2);
for (i = 0; i < c->abort.num; i++)
if (len > c->abort.string[i].len) {
int last;
for (last = c->abort.num; last > i; last--) {
c->abort.string[last].data = c->abort.string[last-1].data;
c->abort.string[last].len = c->abort.string[last-1].len;
}
break;
}
c->abort.string[i].len = len;
c->abort.string[i].data = (char *)malloc(len+1);
memcpy(c->abort.string[i].data, c->exp+2, len+1);
c->abort.num++;
} else
log_Printf(LogERROR, "chat_UpdateSet: too many abort strings\n");
gotabort = 0;
} else if (gottimeout) {
c->TimeoutSec = atoi(c->exp + 2);
if (c->TimeoutSec <= 0)
c->TimeoutSec = 30;
gottimeout = 0;
} else if (c->nargptr == NULL && !strcmp(c->exp+2, "ABORT"))
gotabort = 1;
else if (c->nargptr == NULL && !strcmp(c->exp+2, "TIMEOUT"))
gottimeout = 1;
else {
if (c->exp[2] == '!' && c->exp[3] != '!')
ExecStr(c->physical, c->exp + 3, c->exp + 3, sizeof c->exp - 3);
if (c->exp[2] == '\0') {
/* Empty string, reparse (this may be better as a `goto start') */
c->argptr = &arg_term;
return chat_UpdateSet(d, r, w, e, n);
}
special = 0;
}
}
if (special) {
if (gottimeout)
log_Printf(LogWARN, "chat_UpdateSet: TIMEOUT: Argument expected\n");
else if (gotabort)
log_Printf(LogWARN, "chat_UpdateSet: ABORT: Argument expected\n");
/* End of script - all ok */
c->state = CHAT_DONE;
return 0;
}
/* set c->argptr to point in the right place */
c->argptr = c->exp + (c->exp[2] == '!' ? 3 : 2);
c->arglen = strlen(c->argptr);
if (c->state == CHAT_EXPECT) {
/* We must check to see if the string's already been found ! */
char *begin, *end;
end = c->bufend - c->arglen + 1;
if (end < c->bufstart)
end = c->bufstart;
for (begin = c->bufstart; begin < end; begin++)
if (!strncmp(begin, c->argptr, c->arglen)) {
c->bufstart = begin + c->arglen;
c->argptr += c->arglen;
c->arglen = 0;
/* Continue - we've already read our expect string */
return chat_UpdateSet(d, r, w, e, n);
}
log_Printf(LogCHAT, "Expect(%d): %s\n", c->TimeoutSec, c->argptr);
chat_SetTimeout(c);
}
}
/*
* We now have c->argptr pointing at what we want to expect/send and
* c->state saying what we want to do... we now know what to put in
* the fd_set :-)
*/
if (c->state == CHAT_EXPECT)
return physical_doUpdateSet(&c->physical->desc, r, NULL, e, n, 1);
else
return physical_doUpdateSet(&c->physical->desc, NULL, w, e, n, 1);
}
static int
chat_IsSet(struct fdescriptor *d, const fd_set *fdset)
{
struct chat *c = descriptor2chat(d);
return c->argptr && physical_IsSet(&c->physical->desc, fdset);
}
static void
chat_UpdateLog(struct chat *c, int in)
{
if (log_IsKept(LogCHAT) || log_IsKept(LogCONNECT)) {
/*
* If a linefeed appears in the last `in' characters of `c's input
* buffer, output from there, all the way back to the last linefeed.
* This is called for every read of `in' bytes.
*/
char *ptr, *end, *stop, ch;
int level;
level = log_IsKept(LogCHAT) ? LogCHAT : LogCONNECT;
if (in == -1)
end = ptr = c->bufend;
else {
ptr = c->bufend - in;
for (end = c->bufend - 1; end >= ptr; end--)
if (*end == '\n')
break;
}
if (end >= ptr) {
for (ptr = c->bufend - (in == -1 ? 1 : in + 1); ptr >= c->bufstart; ptr--)
if (*ptr == '\n')
break;
ptr++;
stop = NULL;
while (stop < end) {
if ((stop = memchr(ptr, '\n', end - ptr)) == NULL)
stop = end;
ch = *stop;
*stop = '\0';
if (level == LogCHAT || strstr(ptr, "CONNECT"))
log_Printf(level, "Received: %s\n", ptr);
*stop = ch;
ptr = stop + 1;
}
}
}
}
static void
chat_Read(struct fdescriptor *d, struct bundle *bundle, const fd_set *fdset)
{
struct chat *c = descriptor2chat(d);
if (c->state == CHAT_EXPECT) {
ssize_t in;
char *abegin, *ebegin, *begin, *aend, *eend, *end;
int n;
/*
* XXX - should this read only 1 byte to guarantee that we don't
* swallow any ppp talk from the peer ?
*/
in = BUFLEFT(c);
if (in > sizeof c->buf / 2)
in = sizeof c->buf / 2;
in = physical_Read(c->physical, c->bufend, in);
if (in <= 0)
return;
/* `begin' and `end' delimit where we're going to strncmp() from */
ebegin = c->bufend - c->arglen + 1;
eend = ebegin + in;
if (ebegin < c->bufstart)
ebegin = c->bufstart;
if (c->abort.num) {
abegin = c->bufend - c->abort.string[0].len + 1;
aend = c->bufend - c->abort.string[c->abort.num-1].len + in + 1;
if (abegin < c->bufstart)
abegin = c->bufstart;
} else {
abegin = ebegin;
aend = eend;
}
begin = abegin < ebegin ? abegin : ebegin;
end = aend < eend ? eend : aend;
c->bufend += in;
chat_UpdateLog(c, in);
if (c->bufend > c->buf + sizeof c->buf / 2) {
/* Shuffle our receive buffer back a bit */
int chop;
for (chop = begin - c->buf; chop; chop--)
if (c->buf[chop] == '\n')
/* found some already-logged garbage to remove :-) */
break;
if (!chop)
chop = begin - c->buf;
if (chop) {
char *from, *to;
to = c->buf;
from = to + chop;
while (from < c->bufend)
*to++ = *from++;
c->bufstart -= chop;
c->bufend -= chop;
begin -= chop;
end -= chop;
abegin -= chop;
aend -= chop;
ebegin -= chop;
eend -= chop;
}
}
for (; begin < end; begin++)
if (begin >= ebegin && begin < eend &&
!strncmp(begin, c->argptr, c->arglen)) {
/* Got it ! */
timer_Stop(&c->timeout);
if (memchr(begin + c->arglen - 1, '\n',
c->bufend - begin - c->arglen + 1) == NULL) {
/* force it into the log */
end = c->bufend;
c->bufend = begin + c->arglen;
chat_UpdateLog(c, -1);
c->bufend = end;
}
c->bufstart = begin + c->arglen;
c->argptr += c->arglen;
c->arglen = 0;
break;
} else if (begin >= abegin && begin < aend) {
for (n = c->abort.num - 1; n >= 0; n--) {
if (begin + c->abort.string[n].len > c->bufend)
break;
if (!strncmp(begin, c->abort.string[n].data,
c->abort.string[n].len)) {
if (memchr(begin + c->abort.string[n].len - 1, '\n',
c->bufend - begin - c->abort.string[n].len + 1) == NULL) {
/* force it into the log */
end = c->bufend;
c->bufend = begin + c->abort.string[n].len;
chat_UpdateLog(c, -1);
c->bufend = end;
}
c->bufstart = begin + c->abort.string[n].len;
c->state = CHAT_FAILED;
return;
}
}
}
}
}
static int
chat_Write(struct fdescriptor *d, struct bundle *bundle, const fd_set *fdset)
{
struct chat *c = descriptor2chat(d);
int result = 0;
if (c->state == CHAT_SEND) {
int wrote;
if (strstr(c->argv[c->arg], "\\P")) /* Don't log the password */
log_Printf(LogCHAT, "Send: %s\n", c->argv[c->arg]);
else {
int sz;
sz = c->arglen - 1;
while (sz >= 0 && c->argptr[sz] == '\n')
sz--;
log_Printf(LogCHAT, "Send: %.*s\n", sz + 1, c->argptr);
}
if (physical_IsSync(c->physical)) {
/*
* XXX: Fix me
* This data should be stuffed down through the link layers
*/
/* There's always room for the HDLC header */
c->argptr -= 2;
c->arglen += 2;
memcpy(c->argptr, "\377\003", 2); /* Prepend HDLC header */
}
wrote = physical_Write(c->physical, c->argptr, c->arglen);
result = wrote > 0 ? 1 : 0;
if (wrote == -1) {
if (errno != EINTR) {
log_Printf(LogWARN, "chat_Write: %s\n", strerror(errno));
result = -1;
}
if (physical_IsSync(c->physical)) {
c->argptr += 2;
c->arglen -= 2;
}
} else if (wrote < 2 && physical_IsSync(c->physical)) {
/* Oops - didn't even write our HDLC header ! */
c->argptr += 2;
c->arglen -= 2;
} else {
c->argptr += wrote;
c->arglen -= wrote;
}
}
return result;
}
void
chat_Init(struct chat *c, struct physical *p)
{
c->desc.type = CHAT_DESCRIPTOR;
c->desc.UpdateSet = chat_UpdateSet;
c->desc.IsSet = chat_IsSet;
c->desc.Read = chat_Read;
c->desc.Write = chat_Write;
c->physical = p;
*c->script = '\0';
c->argc = 0;
c->arg = -1;
c->argptr = NULL;
c->nargptr = NULL;
c->bufstart = c->bufend = c->buf;
memset(&c->pause, '\0', sizeof c->pause);
memset(&c->timeout, '\0', sizeof c->timeout);
}
int
chat_Setup(struct chat *c, const char *data, const char *phone)
{
c->state = CHAT_EXPECT;
if (data == NULL) {
*c->script = '\0';
c->argc = 0;
} else {
strncpy(c->script, data, sizeof c->script - 1);
c->script[sizeof c->script - 1] = '\0';
c->argc = MakeArgs(c->script, c->argv, VECSIZE(c->argv), PARSE_NOHASH);
}
c->arg = -1;
c->argptr = NULL;
c->nargptr = NULL;
c->TimeoutSec = 30;
c->TimedOut = 0;
c->phone = phone;
c->abort.num = 0;
timer_Stop(&c->pause);
timer_Stop(&c->timeout);
return c->argc >= 0;
}
void
chat_Finish(struct chat *c)
{
timer_Stop(&c->pause);
timer_Stop(&c->timeout);
while (c->abort.num)
free(c->abort.string[--c->abort.num].data);
c->abort.num = 0;
}
void
chat_Destroy(struct chat *c)
{
chat_Finish(c);
}
/*
* \c don't add a cr
* \d Sleep a little (delay 2 seconds
* \n Line feed character
* \P Auth Key password
* \p pause 0.25 sec
* \r Carrige return character
* \s Space character
* \T Telephone number(s) (defined via `set phone')
* \t Tab character
* \U Auth User
*/
static char *
ExpandString(struct chat *c, const char *str, char *result, int reslen, int cr)
{
int len;
result[--reslen] = '\0';
while (*str && reslen > 0) {
switch (*str) {
case '\\':
str++;
switch (*str) {
case 'c':
cr = 0;
break;
case 'd': /* Delay 2 seconds */
chat_Pause(c, 2 * SECTICKS);
break;
case 'p':
chat_Pause(c, SECTICKS / 4);
break; /* Delay 0.25 seconds */
case 'n':
*result++ = '\n';
reslen--;
break;
case 'r':
*result++ = '\r';
reslen--;
break;
case 's':
*result++ = ' ';
reslen--;
break;
case 't':
*result++ = '\t';
reslen--;
break;
case 'P':
strncpy(result, c->physical->dl->bundle->cfg.auth.key, reslen);
len = strlen(result);
reslen -= len;
result += len;
break;
case 'T':
if (c->phone) {
strncpy(result, c->phone, reslen);
len = strlen(result);
reslen -= len;
result += len;
}
break;
case 'U':
strncpy(result, c->physical->dl->bundle->cfg.auth.name, reslen);
len = strlen(result);
reslen -= len;
result += len;
break;
default:
reslen--;
*result++ = *str;
break;
}
if (*str)
str++;
break;
case '^':
str++;
if (*str) {
*result++ = *str++ & 0x1f;
reslen--;
}
break;
default:
*result++ = *str++;
reslen--;
break;
}
}
if (--reslen > 0) {
if (cr)
*result++ = '\r';
}
if (--reslen > 0)
*result++ = '\0';
return (result);
}
static void
ExecStr(struct physical *physical, char *command, char *out, int olen)
{
pid_t pid;
int fids[2];
char *argv[MAXARGS], *vector[MAXARGS], *startout, *endout;
int stat, nb, argc, i;
log_Printf(LogCHAT, "Exec: %s\n", command);
if ((argc = MakeArgs(command, vector, VECSIZE(vector),
PARSE_REDUCE|PARSE_NOHASH)) <= 0) {
if (argc < 0)
log_Printf(LogWARN, "Syntax error in exec command\n");
*out = '\0';
return;
}
if (pipe(fids) < 0) {
log_Printf(LogCHAT, "Unable to create pipe in ExecStr: %s\n",
strerror(errno));
*out = '\0';
return;
}
if ((pid = fork()) == 0) {
command_Expand(argv, argc, (char const *const *)vector,
physical->dl->bundle, 0, getpid());
close(fids[0]);
timer_TermService();
if (fids[1] == STDIN_FILENO)
fids[1] = dup(fids[1]);
dup2(physical->fd, STDIN_FILENO);
dup2(fids[1], STDERR_FILENO);
dup2(STDIN_FILENO, STDOUT_FILENO);
close(3);
if (open(_PATH_TTY, O_RDWR) != 3)
open(_PATH_DEVNULL, O_RDWR); /* Leave it closed if it fails... */
for (i = getdtablesize(); i > 3; i--)
fcntl(i, F_SETFD, 1);
#ifndef NOSUID
setuid(ID0realuid());
#endif
execvp(argv[0], argv);
fprintf(stderr, "execvp: %s: %s\n", argv[0], strerror(errno));
_exit(127);
} else {
char *name = strdup(vector[0]);
close(fids[1]);
endout = out + olen - 1;
startout = out;
while (out < endout) {
nb = read(fids[0], out, 1);
if (nb <= 0)
break;
out++;
}
*out = '\0';
close(fids[0]);
close(fids[1]);
waitpid(pid, &stat, WNOHANG);
if (WIFSIGNALED(stat)) {
log_Printf(LogWARN, "%s: signal %d\n", name, WTERMSIG(stat));
free(name);
*out = '\0';
return;
} else if (WIFEXITED(stat)) {
switch (WEXITSTATUS(stat)) {
case 0:
free(name);
break;
case 127:
log_Printf(LogWARN, "%s: %s\n", name, startout);
free(name);
*out = '\0';
return;
break;
default:
log_Printf(LogWARN, "%s: exit %d\n", name, WEXITSTATUS(stat));
free(name);
*out = '\0';
return;
break;
}
} else {
log_Printf(LogWARN, "%s: Unexpected exit result\n", name);
free(name);
*out = '\0';
return;
}
}
}
| 26.08794 | 80 | 0.539006 | [
"vector"
] |
82d420911f221c2f730cdbf7a610e5c722c56399 | 1,151 | h | C | components/arc/mojom/arc_gfx_mojom_traits.h | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/arc/mojom/arc_gfx_mojom_traits.h | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/arc/mojom/arc_gfx_mojom_traits.h | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_ARC_MOJOM_ARC_GFX_MOJOM_TRAITS_H_
#define COMPONENTS_ARC_MOJOM_ARC_GFX_MOJOM_TRAITS_H_
#include "components/arc/mojom/gfx.mojom.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/range/range.h"
namespace mojo {
template <>
struct StructTraits<arc::mojom::RectDataView, gfx::Rect> {
static int32_t left(const gfx::Rect& r) { return r.x(); }
static int32_t top(const gfx::Rect& r) { return r.y(); }
static int32_t right(const gfx::Rect& r) { return r.right(); }
static int32_t bottom(const gfx::Rect& r) { return r.bottom(); }
static bool Read(arc::mojom::RectDataView data, gfx::Rect* out);
};
template <>
struct StructTraits<arc::mojom::RangeDataView, gfx::Range> {
static uint32_t start(const gfx::Range& r) { return r.start(); }
static uint32_t end(const gfx::Range& r) { return r.end(); }
static bool Read(arc::mojom::RangeDataView data, gfx::Range* out);
};
} // namespace mojo
#endif // COMPONENTS_ARC_MOJOM_ARC_GFX_MOJOM_TRAITS_H_
| 32.885714 | 73 | 0.727194 | [
"geometry"
] |
82d6af53f5f09658e204167bff3a78021e97880f | 3,575 | h | C | MemoryCrawler/MemoryCrawler/Crawler/stat.h | donaldwuid/MemoryProfiler | dd42d050af3a754c416c657879959e5626c606c0 | [
"MIT"
] | 184 | 2019-05-11T10:42:57.000Z | 2022-03-18T11:43:47.000Z | MemoryCrawler/MemoryCrawler/Crawler/stat.h | zhouxingchi999/MemoryProfiler | 6566c35f0f186542b1fb606a9c7294ca01a76c2e | [
"MIT"
] | 5 | 2019-05-31T06:47:28.000Z | 2020-12-30T06:25:05.000Z | MemoryCrawler/MemoryCrawler/Crawler/stat.h | larryhou/MemoryProfiler | b8babea897c934573e7f4cb045c6169b7b3a1529 | [
"MIT"
] | 48 | 2019-05-14T06:08:55.000Z | 2022-03-07T16:05:24.000Z | //
// stat.h
// MemoryCrawler
//
// Created by larryhou on 2019/4/19.
// Copyright © 2019 larryhou. All rights reserved.
//
#ifndef stat_h
#define stat_h
#include <vector>
#include <map>
#include <stdio.h>
#include <math.h>
template <class T>
class Statistics
{
std::vector<T> __samples;
public:
constexpr static float CI95_TAIL = 1.28156;
constexpr static float CI95_BODY = 1.64489;
T minimum;
T maximum;
T reasonableMinimum;
T reasonableMaximum;
T sum;
double mean;
double standardDeviation;
public:
Statistics();
void collect(T sample);
void summarize();
void clear();
int32_t size();
void iterateUnusualMaximums(std::function<void(int32_t, T)> callback);
void iterateUnusualMinimums(std::function<void(int32_t, T)> callback);
};
template <class T>
Statistics<T>::Statistics()
{
static_assert(std::is_arithmetic<T>::value, "NOT summarizable type");
}
template <class T>
void Statistics<T>::collect(T sample)
{
__samples.push_back(sample);
}
template <class T>
void Statistics<T>::summarize()
{
sum = 0;
minimum = __samples[0];
maximum = 0;
for (auto iter = __samples.begin(); iter != __samples.end(); iter++)
{
auto v = *iter;
sum += v;
if (v > maximum) {maximum = v;}
if (v < minimum) {minimum = v;}
}
mean = (double)sum / (double)__samples.size();
double variance = 0;
for (auto iter = __samples.begin(); iter != __samples.end(); iter++)
{
variance += pow((double)*iter - mean, 2);
}
standardDeviation = pow(variance / (double)(__samples.size() - 1), 0.5);
auto upper = mean + 3 * standardDeviation;
auto lower = mean - 3 * standardDeviation;
reasonableMaximum = minimum;
reasonableMinimum = maximum;
for (auto iter = __samples.begin(); iter != __samples.end(); iter++)
{
auto v = *iter;
if (v > reasonableMaximum && v <= upper) {reasonableMaximum = v;}
if (v < reasonableMinimum && v >= lower) {reasonableMinimum = v;}
}
}
template <class T>
void Statistics<T>::iterateUnusualMaximums(std::function<void (int32_t/*index*/, T)> callback)
{
int32_t index = 0;
for (auto iter = __samples.begin(); iter != __samples.end(); iter++)
{
auto value = *iter;
if (value > reasonableMaximum) { callback(index, value); }
++index;
}
}
template <class T>
void Statistics<T>::iterateUnusualMinimums(std::function<void (int32_t/*index*/, T)> callback)
{
int32_t index = 0;
for (auto iter = __samples.begin(); iter != __samples.end(); iter++)
{
auto value = *iter;
if (value < reasonableMinimum) { callback(index, value); }
++index;
}
}
template <class T>
int32_t Statistics<T>::size()
{
return (int32_t)__samples.size();
}
template <class T>
void Statistics<T>::clear()
{
__samples.clear();
}
class TrackStatistics
{
using sample_t = std::tuple<int32_t/*element_index*/, int32_t/*type_index*/, int32_t/*element_size*/>;
private:
std::vector<sample_t> __samples;
std::map<int32_t, int32_t> __memory;
public:
void summarize(bool reverse = false);
void collect(int32_t itemIndex, int32_t typeIndex, int32_t size);
void foreach(std::function<void(int32_t/*itemIndex*/, int32_t/*typeIndex*/, int32_t/*typeMemory*/, uint64_t/*detail*/)> callback, int32_t depth = 10);
void reverse();
};
template <class T>
struct IterRange
{
T begin;
T end;
};
#endif /* stat_h */
| 22.770701 | 154 | 0.622098 | [
"vector"
] |
82d6b894411f8740dbc4937cdbaec7c591064a5b | 30,729 | h | C | source_code/ElementaryCyclesSearch.h | EbtehalTurkiAlotaibi/PushAndSpin | 3a8f964d7849fe3ff56d3cbab7a24eaffa5d1941 | [
"BSD-3-Clause"
] | 5 | 2017-06-07T08:20:52.000Z | 2021-06-21T16:03:11.000Z | source_code/ElementaryCyclesSearch.h | EbtehalTurkiAlotaibi/PushAndSpin | 3a8f964d7849fe3ff56d3cbab7a24eaffa5d1941 | [
"BSD-3-Clause"
] | 1 | 2018-04-21T08:53:50.000Z | 2019-03-22T02:29:06.000Z | source_code/ElementaryCyclesSearch.h | EbtehalTurkiAlotaibi/PushAndSpin | 3a8f964d7849fe3ff56d3cbab7a24eaffa5d1941 | [
"BSD-3-Clause"
] | null | null | null | #ifndef ELEMENTARYCYCLESSEARCH_H
#define ELEMENTARYCYCLESSEARCH_H
#include <vector>
#include <algorithm>
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
#include <set>
#include <hash_set>
#include <stddef.h>
#include <cstddef>
#define nullptr NULL
//*****************************************************************************************************************************//
// class SCCResult //
//*****************************************************************************************************************************//
/// <summary>
/// Calculates a adjacency-list for a given array of an adjacency-matrix.
/// </summary>
/// <param name="adjacencyMatrix"> array with the adjacency-matrix that represents
/// the graph </param>
/// <returns> int[][]-array of the adjacency-list of given nodes. The first
/// dimension in the array represents the same node as in the given
/// adjacency, the second dimension represents the indicies of those nodes,
/// that are direct successornodes of the node. </returns>
class SCCResult
{
private:
std::set<int> nodeIDsOfSCC;
std::vector<std::vector<int> > adjList;
int lowestNodeId;
public:
SCCResult(std::vector<std::vector<int> > &adjList, int lowestNodeId)
{
this->adjList = adjList;
this->lowestNodeId = lowestNodeId;
this->nodeIDsOfSCC = std::set<int>();
if (this->adjList.size() > 0)
{
for (unsigned int i = this->lowestNodeId; i < this->adjList.size(); i++)
{
if (this->adjList[i].size() > 0)
{
this->nodeIDsOfSCC.insert(int(i));
}
}
}
}
std::vector<std::vector<int> > getAdjList()
{
return adjList;
}
virtual int getLowestNodeId()
{
return lowestNodeId;
}
};
std::vector<std::vector<int> > adjList;
int lowestNodeId=-1;
//**************************************************************************************************************************//
// StrongConnectedComponents class //
//**************************************************************************************************************************//
/// <summary>
/// This is a helpclass for the search of all elementary cycles in a graph
/// with the algorithm of Johnson. For this it searches for strong connected
/// components, using the algorithm of Tarjan. The constructor gets an
/// adjacency-list of a graph. Based on this graph, it gets a nodenumber s,
/// for which it calculates the subgraph, containing all nodes
/// {s, s + 1, ..., n}, where n is the highest nodenumber in the original
/// graph (e.g. it builds a subgraph with all nodes with higher or same
/// nodenumbers like the given node s). It returns the strong connected
/// component of this subgraph which contains the lowest nodenumber of all
/// nodes in the subgraph.<br><br>
///
/// For a description of the algorithm for calculating the strong connected
/// components see:<br>
/// Robert Tarjan: Depth-first search and linear graph algorithms. In: SIAM
/// Journal on Computing. Volume 1, Nr. 2 (1972), pp. 146-160.<br>
/// For a description of the algorithm for searching all elementary cycles in
/// a directed graph see:<br>
/// Donald B. Johnson: Finding All the Elementary Circuits of a Directed Graph.
/// SIAM Journal on Computing. Volumne 4, Nr. 1 (1975), pp. 77-84.<br><br>
///
/// @author Frank Meyer, web_at_normalisiert_dot_de
/// @version 1.1, 22.03.2009
///
/// </summary>
class StrongConnectedComponents
{
/// <summary>
/// Adjacency-list of original graph </summary>
public:
std::vector<std::vector<int> > adjListOriginal;
/// <summary>
/// Adjacency-list of currently viewed subgraph </summary>
std::vector<std::vector<int> > adjList;
/// <summary>
/// Helpattribute for finding scc's </summary>
std::vector<bool> visited;
/// <summary>
/// Helpattribute for finding scc's </summary>
std::vector<int> stack;
/// <summary>
/// Helpattribute for finding scc's </summary>
std::vector<int> lowlink;
/// <summary>
/// Helpattribute for finding scc's </summary>
std::vector<int> number;
/// <summary>
/// Helpattribute for finding scc's </summary>
int sccCounter;
/// <summary>
/// Helpattribute for finding scc's </summary>
std::vector<std::vector<int> > currentSCCs;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="adjList"> adjacency-list of the graph </param>
public:
StrongConnectedComponents(std::vector<std::vector<int> > &adjList) : adjListOriginal (adjList)
{
this->sccCounter=0;
}
/// <summary>
/// This method returns the adjacency-structure of the strong connected
/// component with the least vertex in a subgraph of the original graph
/// induced by the nodes {s, s + 1, ..., n}, where s is a given node. Note
/// that trivial strong connected components with just one node will not
/// be returned.
/// </summary>
/// <param name="node"> node s </param>
/// <returns> SCCResult with adjacency-structure of the strong
/// connected component; null, if no such component exists </returns>
SCCResult *getAdjacencyList(int node)
{
this->visited = std::vector<bool>(this->adjListOriginal.size());
this->lowlink = std::vector<int>(this->adjListOriginal.size());
this->number = std::vector<int>(this->adjListOriginal.size());
this->visited = std::vector<bool>(this->adjListOriginal.size());
this->stack = std::vector<int>();
this->currentSCCs = std::vector<std::vector<int> >();
this->makeAdjListSubgraph(node);
for (int i = node; i < this->adjListOriginal.size(); i++)
{
if (!this->visited[i])
{
this->getStrongConnectedComponents(i);
std::vector<int> nodes = this->getLowestIdComponent(); // FILL NODES WITH ZEROS!
if ( (nodes.size() > 0) && (std::find(nodes.begin(), nodes.end(), int(node)) == nodes.end()) && (std::find(nodes.begin(), nodes.end(), int(node+1)) == nodes.end()) )
{
return this->getAdjacencyList(node + 1);
}
else
{
std::vector<std::vector<int> > adjacencyList = this->getAdjList(nodes);
if (adjacencyList.size() > 0)
{
for (int j = 0; j < this->adjListOriginal.size(); j++)
{
if (adjacencyList[j].size() > 0) // ALWAYS ZERO !!!!!
{
SCCResult* ss = new SCCResult(adjacencyList, j);
return ss;
}
}
}
}
}
}
return nullptr;
}
/// <summary>
/// Builds the adjacency-list for a subgraph containing just nodes
/// >= a given index.
/// </summary>
/// <param name="node"> Node with lowest index in the subgraph </param>
void makeAdjListSubgraph(int node)
{
this->adjList = std::vector<std::vector<int> >(this->adjListOriginal.size(), std::vector<int>(0,0));
for (int i = node; i < this->adjList.size(); i++)
{
std::vector<int> successors = std::vector<int>();
for (int j = 0; j < this->adjListOriginal[i].size(); j++)
{
if (this->adjListOriginal[i][j] >= node)
{
successors.push_back(int(this->adjListOriginal[i][j]));
}
}
if (successors.size() > 0)
{
this->adjList[i] = std::vector<int>(successors.size());
for (int j = 0; j < successors.size(); j++)
{
int succ = static_cast<int>(successors[j]);
this->adjList[i][j] = succ;
}
}
}
}
/// <summary>
/// Calculates the strong connected component out of a set of scc's, that
/// contains the node with the lowest index.
/// </summary>
/// <returns> Vector::Integer of the scc containing the lowest nodenumber </returns>
std::vector<int> getLowestIdComponent()
{
int min = this->adjList.size();
std::vector<int> currScc;
for (int i = 0; i < this->currentSCCs.size(); i++)
{
std::vector<int> scc = std::vector<int> (this->currentSCCs[i]);
for (int j = 0; j < scc.size(); j++)
{
//std::cout<<scc[j]<<"\n";
int node = scc[j];
if (node < min)
{
currScc = scc;
min = node;
}
}
}
return currScc;
}
/// <returns> Vector[]::Integer representing the adjacency-structure of the
/// strong connected component with least vertex in the currently viewed
/// subgraph </returns>
std::vector<std::vector<int> > getAdjList(std::vector<int>& nodes)
{
std::vector<std::vector<int> > lowestIdAdjacencyList = std::vector<std::vector<int> >(this->adjList.size());
if (nodes.size() > 0)
{
for (int i = 0; i < lowestIdAdjacencyList.size(); i++)
{
lowestIdAdjacencyList[i] = std::vector<int>();
}
for (int i = 0; i < nodes.size(); i++)
{
int node = (static_cast<int>(nodes[i]));
for (int j = 0; j < this->adjList[node].size(); j++)
{
int succ = this->adjList[node][j];
if (std::find(nodes.begin(), nodes.end(), int(succ)) != nodes.end())
{
lowestIdAdjacencyList[node].push_back(int(succ));
}
}
}
}
return lowestIdAdjacencyList;
}
void getStrongConnectedComponents(int root)
{
this->sccCounter++;
this->lowlink[root] = this->sccCounter;
this->number[root] = this->sccCounter;
this->visited[root] = true;
this->stack.push_back(int(root));
for (int i = 0; i < this->adjList[root].size(); i++)
{
int w = this->adjList[root][i];
if (!this->visited[w])
{
this->getStrongConnectedComponents(w);
this->lowlink[root] = std::min(lowlink[root], lowlink[w]);
}
else if (this->number[w] < this->number[root])
{
if (std::find(this->stack.begin(), this->stack.end(), int(w)) != this->stack.end())
{
lowlink[root] = std::min(this->lowlink[root], this->number[w]);
}
}
}
if ((lowlink[root] == number[root]) && (stack.size() > 0))
{
int next = -1;
std::vector<int> scc = std::vector<int>();
do
{
next = (static_cast<int>(this->stack[stack.size() - 1]));
this->stack.pop_back();
scc.push_back(int(next));
} while (this->number[next] > this->number[root]);
// simple scc's with just one node will not be added
if (scc.size() > 1)
{
this->currentSCCs.push_back (scc);
}
}
}
};
//********************************************************************************************************************************//
// AdjacencyList Class //
//********************************************************************************************************************************//
std::vector<std::vector<int> > getAdjacencyList(std::vector<std::vector<bool> > &adjacencyMatrix)
{
std::vector<std::vector<int> > list(adjacencyMatrix.size());
for (int i = 0; i < adjacencyMatrix.size(); i++)
{
std::vector<int> v = std::vector<int>();
for (int j = 0; j < adjacencyMatrix[i].size(); j++)
{
if (adjacencyMatrix[i][j])
{
v.push_back(int(j));
}
}
list[i] = std::vector<int>(v.size());
for (int j = 0; j < v.size(); j++)
{
int in_Renamed = static_cast<int>(v[j]);
list[i][j] = in_Renamed;
}
}
return list;
}
//********************************************************************************************************************************//
//********************************************************************************************************************************//
//----------------------------------------------------------------------------------------
// Copyright \A9 2007 - 2015 Tangible Software Solutions Inc.
// This class can be used by anyone provided that the copyright notice remains intact.
//
// This class includes methods to convert multidimensional arrays to C++ vectors.
//----------------------------------------------------------------------------------------
std::vector<std::vector<bool> >& ReturnRectangularBoolVector(int size1, int size2)
{
std::vector<std::vector<bool> > newVector(size1);
for (int vector1 = 0; vector1 < size1; vector1++)
{
newVector[vector1] = std::vector<bool>(size2);
for (int x = 0 ; x <size2 ; x++)
newVector[vector1][x] = false;
}
return newVector;
}
//*****************************************************************************************************************************//
// class ElementaryCyclesSearch //
//*****************************************************************************************************************************//
/// <summary>
/// Searchs all elementary cycles in a given directed graph. The implementation
/// is independent from the concrete objects that represent the graphnodes, it
/// just needs an array of the objects representing the nodes the graph
/// and an adjacency-matrix of type boolean, representing the edges of the
/// graph. It then calculates based on the adjacency-matrix the elementary
/// cycles and returns a list, which contains lists itself with the objects of the
/// concrete graphnodes-implementation. Each of these lists represents an
/// elementary cycle.<br><br>
///
/// The implementation uses the algorithm of Donald B. Johnson for the search of
/// the elementary cycles. For a description of the algorithm see:<br>
/// Donald B. Johnson: Finding All the Elementary Circuits of a Directed Graph.
/// SIAM Journal on Computing. Volumne 4, Nr. 1 (1975), pp. 77-84.<br><br>
///
/// The algorithm of Johnson is based on the search for strong connected
/// components in a graph. For a description of this part see:<br>
/// Robert Tarjan: Depth-first search and linear graph algorithms. In: SIAM
/// Journal on Computing. Volume 1, Nr. 2 (1972), pp. 146-160.<br>
///
/// @author Frank Meyer, web_at_normalisiert_dot_de
/// @version 1.2, 22.03.2009
///
/// </summary>
class ElementaryCyclesSearch
{
/// <summary>
/// List of cycles </summary>
private:
std::vector<std::vector<unsigned int> >cycles;
/// <summary>
/// Adjacency-list of graph </summary>
std::vector<std::vector<int> > adjList;
/// <summary>
/// Graphnodes </summary>
std::vector<int> graphNodes;
/// <summary>
/// Blocked nodes, used by the algorithm of Johnson </summary>
std::vector<bool> blocked;
/// <summary>
/// B-Lists, used by the algorithm of Johnson </summary>
std::vector<std::vector<int> > B;
/// <summary>
/// Stack for nodes, used by the algorithm of Johnson </summary>
std::vector<int> stack;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="matrix"> adjacency-matrix of the graph </param>
/// <param name="graphNodes"> array of the graphnodes of the graph; this is used to
/// build sets of the elementary cycles containing the objects of the original
/// graph-representation </param>
public:
ElementaryCyclesSearch(std::vector<std::vector<bool> > &matrix, std::vector<int> &graphNodes)
{
this->graphNodes = graphNodes;
this->adjList = getAdjacencyList(matrix);
}
/// <summary>
/// Returns List::List::Object with the Lists of nodes of all elementary
/// cycles in the graph.
/// </summary>
/// <returns> List::List::Object with the Lists of the elementary cycles. </returns>
std::vector<std::vector<unsigned int> >getElementaryCycles()
{
cycles = std::vector<std::vector<unsigned int> >();
blocked = std::vector<bool>( adjList.size());
B = std::vector<std::vector<int> >( adjList.size());
stack = std::vector<int>();
StrongConnectedComponents sccs (adjList);
int s = 0;
while (true)
{
SCCResult* sccResult = sccs.getAdjacencyList(s);
if (sccResult!= nullptr)
{
std::vector<std::vector<int> > scc (sccResult->getAdjList());
s = (sccResult->getLowestNodeId());
for (int j = 0; j < scc.size(); j++)
{
if ((scc[j].size() > 0) && (scc[j].size() > 0))
{
blocked[j] = false;
B[j] = std::vector<int>();
}
}
findCycles(s, s, scc);
s++;
}
else
{
break;
}
}
return cycles;
}
/// <summary>
/// Calculates the cycles containing a given node in a strongly connected
/// component. The method calls itself recursivly.
/// </summary>
/// <param name="v"> </param>
/// <param name="s"> </param>
/// <param name="adjList"> adjacency-list with the subgraph of the strongly
/// connected component s is part of. </param>
/// <returns> true, if cycle found; false otherwise </returns>
private:
bool isBlocked (std::vector<unsigned int> cycle) {
// 1- check if cycle is subset any registered cycle
for (int c=0; c<cycle.size(); c++) {
int ptr = cycle[c];
for (int i=0; i<this->cycles.size(); i++)
for (int j=0; j<this->cycles[i].size(); j++){
if (ptr == this->cycles[i][j]) { // if one node is inside the cycle [i][j], check others
int cntr=0;
for (int p=0; p<cycle.size(); p++) {
if (std::find(this->cycles[i].begin(),this->cycles[i].end(),cycle[p])!=this->cycles[i].end())
cntr++;
}
if (cntr == cycle.size()) { // cycle is subset of other cycle !
this->cycles.erase(this->cycles.begin()+i);
this->cycles.push_back(cycle);
return true;
}
}
}
}
// 2- check if cycle is superset of any registered cycle
for (int c=0; c<cycle.size(); c++) {
for (int i=0; i<this->cycles.size(); i++)
for (int j=0; j<this->cycles[i].size(); j++){
int ptr = this->cycles[i][j];
if (ptr == cycle[c]) {
int cntr=0;
for (int p=0; p<this->cycles[i].size(); p++) {
if (std::find(cycle.begin(),cycle.end(),this->cycles[i][p])!=cycle.end())
cntr++;
}
if (cntr == this->cycles[i].size()) { // cycle is superset of other cycle !
return true;
}
}
}
}
return false;
}
bool findCycles(int v, int s, std::vector<std::vector<int> > &adjList)
{
bool f = false;
stack.push_back(int(v)); // we want to procces v
blocked[v] = true; // v is blocked
for (int i = 0; i < adjList[v].size(); i++) // for all neighbours of v
{
int w = (static_cast<int>(adjList[v][i])); // w = neighbours of v
// found cycle C = all stack nodes
if ((w == s))
{
std::vector<unsigned int> cycle = std::vector<unsigned int>();
for (int j = 0; j < stack.size(); j++)
{
int index = (static_cast<int>( stack[j]));
cycle.push_back( graphNodes[index]);
}
// if this cycle is not contains other registered cycle or not a part of other cycle
this->cycles.push_back(cycle);
f = true;
}
else if (! blocked[w])
{
if ( findCycles(w, s, adjList))
{
f = true;
}
}
}
if (f)
{
unblock(v);
}
else
{
for (int i = 0; i < adjList[v].size(); i++)
{
int w = (static_cast<int>(adjList[v][i]));
if (std::find( B[w].begin(), B[w].end(), int(v)) == B[w].end())
{
B[w].push_back(int(v));
}
}
}
stack.erase (std::remove(stack.begin(),stack.end(),v),stack.end());
//stack.erase(stack.begin()+(v));
return f;
}
/// <summary>
/// Unblocks recursivly all blocked nodes, starting with a given node.
/// </summary>
/// <param name="node"> node to unblock </param>
void unblock(int node)
{
blocked[node] = false;
std::vector<int> Bnode = B[node];
while (Bnode.size() > 0)
{
int w = static_cast<int>(Bnode[0]);
Bnode.erase(Bnode.begin()+0);
if ( blocked[w])
{
unblock(w);
}
}
}
};
#endif // ELEMENTARYCYCLESSEARCH_H
| 46.986239 | 197 | 0.357382 | [
"object",
"vector"
] |
82d7c9709a289117bdf7e465e67aeacba2916ab2 | 537 | h | C | gcc-build/i686-pc-linux-gnu/libjava/java/lang/ref/SoftReference.h | giraffe/jrate | 764bbf973d1de4e38f93ba9b9c7be566f1541e16 | [
"Xnet",
"Linux-OpenIB",
"X11"
] | 1 | 2021-06-15T05:43:22.000Z | 2021-06-15T05:43:22.000Z | gcc-build/i686-pc-linux-gnu/libjava/java/lang/ref/SoftReference.h | giraffe/jrate | 764bbf973d1de4e38f93ba9b9c7be566f1541e16 | [
"Xnet",
"Linux-OpenIB",
"X11"
] | null | null | null | gcc-build/i686-pc-linux-gnu/libjava/java/lang/ref/SoftReference.h | giraffe/jrate | 764bbf973d1de4e38f93ba9b9c7be566f1541e16 | [
"Xnet",
"Linux-OpenIB",
"X11"
] | null | null | null | // DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*-
#ifndef __java_lang_ref_SoftReference__
#define __java_lang_ref_SoftReference__
#pragma interface
#include <java/lang/ref/Reference.h>
class ::java::lang::ref::SoftReference : public ::java::lang::ref::Reference
{
public:
SoftReference (::java::lang::Object *);
SoftReference (::java::lang::Object *, ::java::lang::ref::ReferenceQueue *);
virtual ::java::lang::Object *get ();
static ::java::lang::Class class$;
};
#endif /* __java_lang_ref_SoftReference__ */
| 25.571429 | 78 | 0.705773 | [
"object"
] |
82da8921a39cb1ccdb3bd8523f1307e0d972c377 | 1,003 | h | C | include/tgbot/net/HttpParser.h | DanteG41/tgbot-cpp | 601fd7fa0e879084c01ebd59741d73c8f8144b88 | [
"MIT"
] | 1 | 2022-01-27T07:21:16.000Z | 2022-01-27T07:21:16.000Z | include/tgbot/net/HttpParser.h | DanteG41/tgbot-cpp | 601fd7fa0e879084c01ebd59741d73c8f8144b88 | [
"MIT"
] | 1 | 2019-12-12T15:51:19.000Z | 2019-12-12T18:03:52.000Z | include/tgbot/net/HttpParser.h | DanteG41/tgbot-cpp | 601fd7fa0e879084c01ebd59741d73c8f8144b88 | [
"MIT"
] | null | null | null | #ifndef TGBOT_HTTPPARSER_H
#define TGBOT_HTTPPARSER_H
#include <string>
#include <unordered_map>
#include <vector>
#include "tgbot/net/Url.h"
#include "tgbot/net/HttpReqArg.h"
namespace TgBot {
class HttpParser {
public:
std::string generateRequest(const Url& url, const std::vector<HttpReqArg>& args, bool isKeepAlive = false) const;
std::string generateMultipartFormData(const std::vector<HttpReqArg>& args, const std::string& bondary) const;
std::string generateMultipartBoundary(const std::vector<HttpReqArg>& args) const;
std::string generateWwwFormUrlencoded(const std::vector<HttpReqArg>& args) const;
std::string generateResponse(const std::string& data, const std::string& mimeType, unsigned short statusCode, const std::string& statusStr, bool isKeepAlive) const;
std::unordered_map<std::string, std::string> parseHeader(const std::string& data, bool isRequest) const;
std::string extractBody(const std::string& data) const;
};
}
#endif //TGBOT_HTTPPARSER_H
| 35.821429 | 168 | 0.759721 | [
"vector"
] |
82da9e4d6e19e20f8151bc1f8d15e9148d7cafc9 | 13,920 | c | C | source/ti/sail/tmp006/tmp006.c | seank-com/azure-iot-sdk-tirtos-cc3220 | 7d7d89195cda2a5698fd9fdd5f153caf410bb4c7 | [
"MIT"
] | null | null | null | source/ti/sail/tmp006/tmp006.c | seank-com/azure-iot-sdk-tirtos-cc3220 | 7d7d89195cda2a5698fd9fdd5f153caf410bb4c7 | [
"MIT"
] | null | null | null | source/ti/sail/tmp006/tmp006.c | seank-com/azure-iot-sdk-tirtos-cc3220 | 7d7d89195cda2a5698fd9fdd5f153caf410bb4c7 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2016-2017, Texas Instruments Incorporated
* 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 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.
*/
/*
* ======== tmp006.c ========
*/
#include <stdint.h>
#include <stdbool.h>
#include <math.h>
/* Driver Header files */
#include <ti/drivers/GPIO.h>
#include <ti/drivers/I2C.h>
/* Module Header */
#include <ti/sail/tmp006/tmp006.h>
/* POSIX Header files */
#include <unistd.h>
/* It is recommended to wait for some time(in few ms, defined by below macro)
before TMP006 module is used after issuing a reset*/
#define WAIT_POST_RESET 5U /* Wait time in ms after reset */
#define CELSIUS_FAHREN_CONST 1.8F /* Multiplier for conversion */
#define CELSIUS_FAHREN_ADD 32U /* Celsius to Fahrenheit added factor */
#define CELSIUS_TO_KELVIN 273.15F /* Celsius to Kelvin addition factor */
#define CELSIUS_PER_LSB 0.03125F /* Degrees celsius per LSB */
#define READ_BUF_SIZE 2U
#define WRITE_BUF_SIZE 3U
/* TMP006 Configuration Register Bits */
#define CFG_SW_RST 0x8000U /* Software reset */
#define CFG_CONV_ON 0x7000U /* Conversion on mode */
#define CFG_DATARDY 0x0100U /* Data Ready pin enable */
#define CFG_DATARDY_STATUS 0x0080U /* Data Ready pin enable */
/*
* The target object temperature calculations consist of a series of equations
* that can be used to solve for the target object temperature (TOBJ) in Kelvins.
* These equations and constants which have been defined here have been clearly
* exlained the TMP006 users guide - SBOU107. Please refer to the user guide for
* more information on these constants
*/
#define TMP006_CCONST_A1 1.75E-3
#define TMP006_CCONST_A2 -1.678E-5
#define TMP006_CCONST_TREF 298.15
#define TMP006_CCONST_B0 -2.94E-5
#define TMP006_CCONST_B1 -5.7E-7
#define TMP006_CCONST_B2 4.63E-9
#define TMP006_CCONST_C2 13.4
#define TMP006_CCONST_LSB_SIZE 156.25E-9
/* Default TMP006 parameters structure */
const TMP006_Params TMP006_defaultParams = {
TMP006_4CONV, /* 4 ADC Conversions Averaged per Sample */
TMP006_DataReadyDisable, /* Data ready pin disabled */
NULL, /* Callback Function */
6.4E-14 /* Calibration factor(to be calibrated) */
};
extern TMP006_Config TMP006_config[];
/*
* ======== TMP006_close ========
* Closes an instance of a TMP006 sensor.
*/
bool TMP006_close(TMP006_Handle handle)
{
TMP006_Object *obj = (TMP006_Object *)(handle->object);
if (obj->callback != NULL)
{
TMP006_disableDataReady(handle);
}
if (TMP006_disableConversions(handle))
{
obj->i2cHandle = NULL;
return (true);
}
return (false);
}
/*
* ======== TMP006_disableDataReady ========
* Disables data ready signal from a TMP006 sensor.
*/
bool TMP006_disableDataReady(TMP006_Handle handle)
{
uint16_t reg = 0U;
if (((TMP006_Object *)(handle->object))->callback == NULL)
{
return (true);
}
if (TMP006_readRegister(handle, ®, TMP006_CONFIG))
{
reg &= ~CFG_DATARDY;
if (TMP006_writeRegister(handle, reg, TMP006_CONFIG))
{
GPIO_disableInt(((TMP006_HWAttrs *) (handle->hwAttrs))->gpioIndex);
return (true);
}
}
return (false);
}
/*
* ======== TMP006_disableConversions ========
* Turns ADC conversion off on a specified TMP006 sensor.
*/
bool TMP006_disableConversions(TMP006_Handle handle)
{
uint16_t reg = 0U; /* Prevent warning */
if (TMP006_readRegister(handle, ®, TMP006_CONFIG))
{
reg &= ~CFG_CONV_ON;
if (TMP006_writeRegister(handle, reg, TMP006_CONFIG))
{
return (true);
}
}
return (false);
}
/*
* ======== TMP006_enableDataReady ========
* Enables data ready interrupt from a TMP006 sensor.
*/
bool TMP006_enableDataReady(TMP006_Handle handle)
{
uint16_t reg = 0U; /* Prevent warning */
if (((TMP006_Object *) (handle->object))->callback != NULL)
{
if (TMP006_readRegister(handle, ®, TMP006_CONFIG))
{
reg |= CFG_DATARDY;
if (TMP006_writeRegister(handle, reg, TMP006_CONFIG))
{
GPIO_enableInt(((TMP006_HWAttrs *) (handle->hwAttrs))
->gpioIndex);
return (true);
}
}
}
return (false);
}
/*
* ======== TMP006_enableConversions ========
* Turns on ADC conversion on a specified TMP006 sensor.
*/
bool TMP006_enableConversions(TMP006_Handle handle)
{
uint16_t reg = 0U;
if (TMP006_readRegister(handle, ®, TMP006_CONFIG))
{
reg |= CFG_CONV_ON;
if (TMP006_writeRegister(handle, reg, TMP006_CONFIG))
{
return (true);
}
}
return (false);
}
/*
* ======== TMP006_getDieTemp ========
*/
bool TMP006_getDieTemp(TMP006_Handle handle, TMP006_TempScale scale,
float *data)
{
int16_t temp;
if (TMP006_readRegister(handle, (uint16_t *) &temp, TMP006_DIE_TEMP))
{
/* Shift out first 2 don't care bits, convert to Celsius */
*data =(double)temp / 128.0;
switch (scale)
{
case TMP006_KELVIN:
*data += CELSIUS_TO_KELVIN;
break;
case TMP006_FAHREN:
*data = *data * CELSIUS_FAHREN_CONST + CELSIUS_FAHREN_ADD;
break;
default:
break;
}
return (true);
}
return (false);
}
//****************************************************************************
//
//! \brief Compute the temperature value from the sensor voltage and die temp.
//!
//! \param[in] Vobject the sensor voltage value
//! \param[in] TDie the local die temperature
//!
//! \return temperature value
//
//****************************************************************************
static double ComputeTemperature(TMP006_Handle handle,double Vobject,
double Tdie)
{
/*
* This algo is obtained from
* http://processors.wiki.ti.com/index.php/SensorTag_User_Guide
* http://www.ti.com/lit/ug/sbou107/sbou107.pdf
* #IR_Temperature_Sensor
*/
double Tdie2 = Tdie + CELSIUS_TO_KELVIN;
const double a1 = TMP006_CCONST_A1;
const double a2 = TMP006_CCONST_A2;
const double b0 = TMP006_CCONST_B0;
const double b1 = TMP006_CCONST_B1;
const double b2 = TMP006_CCONST_B2;
const double c2 = TMP006_CCONST_C2;
const double Tref = TMP006_CCONST_TREF;
double S = ((TMP006_Object *)(handle->object))->S0 * (1U+a1 *
(Tdie2 - Tref)+ a2 * pow((Tdie2 - Tref),2U));
double Vos = b0 + b1 * (Tdie2 - Tref) + b2 * pow((Tdie2 - Tref),2U);
double fObj = (Vobject - Vos) + c2 * pow((Vobject - Vos),2U);
double tObj = pow(pow(Tdie2,4U) + (fObj/S),.25);
tObj = (tObj - CELSIUS_TO_KELVIN);
return tObj;
}
/*
* ======== TMP006_getObjTemp ========
*/
bool TMP006_getObjTemp(TMP006_Handle handle, TMP006_TempScale scale,
float *data)
{
int16_t temp;
double objectVoltage,dieTemp;
if (false == TMP006_readRegister(handle, (uint16_t *) &temp,
TMP006_DIE_TEMP))
{
return (false);
}
/* Converting the integer temperature result of the TMP006 and TMP006B to
* physical temperature is done by rightshifting the last two LSBs followed
* by a divide-by-32 of TDIE to obtain the physical temperature result in
* degrees Celsius.Which is equivalent to dividing by 128.
* Please check the tmp006 data sheet for more information.
*/
dieTemp = ((short)temp) / 128U;
if (false == TMP006_readRegister(handle, (uint16_t *) &temp, TMP006_VOBJ))
{
return (false);
}
/* LSB is 156.25 nv*/
objectVoltage = ((short)temp) * 156.25e-9;
*data = ComputeTemperature(handle,objectVoltage, dieTemp);
switch (scale)
{
case TMP006_KELVIN:
*data += CELSIUS_TO_KELVIN;
break;
case TMP006_FAHREN:
*data = *data * CELSIUS_FAHREN_CONST + CELSIUS_FAHREN_ADD;
break;
default:
break;
}
return (true);
}
/*
* ======== TMP006_getDataReadyStatus ========
*/
bool TMP006_getDataReadyStatus(TMP006_Handle handle,
TMP006_ConversionStatus *conversionStatus)
{
int16_t data;
if (false == TMP006_readRegister(handle, (uint16_t *) &data, TMP006_CONFIG))
{
return false;
}
if(0U == (data & CFG_DATARDY_STATUS))
{
*conversionStatus = TMP006_DataNotReady;
}
else
{
*conversionStatus = TMP006_DataReady;
}
return true;
}
/*
* ======== TMP006_init ========
*/
void TMP006_init()
{
static bool initFlag = false;
unsigned char i;
if (initFlag == false)
{
for (i = 0U; TMP006_config[i].object != NULL; i++)
{
((TMP006_Object *)(TMP006_config[i].object))->i2cHandle = NULL;
}
initFlag = true;
}
}
/*
* ======== TMP006_open ========
* Setups TMP006 sensor and returns TMP006_Handle
*/
TMP006_Handle TMP006_open(unsigned int tmp006Index, I2C_Handle i2cHandle,
TMP006_Params *params)
{
TMP006_Handle handle = &TMP006_config[tmp006Index];
TMP006_Object *obj = (TMP006_Object*)(TMP006_config[tmp006Index].object);
TMP006_HWAttrs *hw = (TMP006_HWAttrs*)(TMP006_config[tmp006Index].hwAttrs);
uint16_t data;
if (obj->i2cHandle != NULL)
{
return (NULL);
}
obj->i2cHandle = i2cHandle;
if (params == NULL)
{
params = (TMP006_Params *) &TMP006_defaultParams;
}
obj->S0 = params->S0;
/* Perform a software TMP006 Reset */
if (TMP006_writeRegister(handle, CFG_SW_RST, TMP006_CONFIG))
{
usleep(WAIT_POST_RESET * 1000U);
data = (uint16_t)params->conversions | (uint16_t)params->dataReady
| CFG_CONV_ON;
if (TMP006_writeRegister(handle, data, TMP006_CONFIG))
{
if (params->callback != NULL)
{
obj->callback = params->callback;
GPIO_setCallback(hw->gpioIndex, obj->callback);
}
return (handle);
}
}
obj->i2cHandle = NULL;
return (NULL);
}
/*
* ======== TMP006_Params_init ========
* Initialize a TMP006_Params struct to default settings.
*/
void TMP006_Params_init(TMP006_Params *params)
{
*params = TMP006_defaultParams;
}
/*
* ======== TMP006_readRegister ========
* Reads a specified register from a TMP006 sensor.
*/
bool TMP006_readRegister(TMP006_Handle handle, uint16_t *data,
uint8_t registerAddress)
{
I2C_Transaction i2cTransaction;
unsigned char writeBuffer = registerAddress;
unsigned char readBuffer[READ_BUF_SIZE];
i2cTransaction.writeBuf = &writeBuffer;
i2cTransaction.writeCount = 1U;
i2cTransaction.readBuf = readBuffer;
i2cTransaction.readCount = READ_BUF_SIZE;
i2cTransaction.slaveAddress = ((TMP006_HWAttrs *)(handle->hwAttrs))
->slaveAddress;
if (!I2C_transfer(((TMP006_Object *)(handle->object))->i2cHandle,
&i2cTransaction))
{
return (false);
}
*data = (readBuffer[0U] << 8U) | readBuffer[1U];
return (true);
}
/*
* ======== TMP006_writeRegister ========
* Writes data to the specified register and TMP006 sensor.
*/
bool TMP006_writeRegister(TMP006_Handle handle, uint16_t data,
uint8_t registerAddress)
{
I2C_Transaction i2cTransaction;
uint8_t writeBuffer[WRITE_BUF_SIZE] = {registerAddress, (data >> 8U), data};
i2cTransaction.writeBuf = writeBuffer;
i2cTransaction.writeCount = WRITE_BUF_SIZE;
i2cTransaction.readCount = 0U;
i2cTransaction.slaveAddress = ((TMP006_HWAttrs *)(handle->hwAttrs))
->slaveAddress;
/* If transaction success */
if (!I2C_transfer(((TMP006_Object *)(handle->object))
->i2cHandle, &i2cTransaction))
{
return (false);
}
return (true);
}
| 28.292683 | 81 | 0.613793 | [
"object"
] |
82daccc9ea6233fdc336cdf0e6de4f888063a167 | 58,086 | c | C | drivers/memstick/core/ms_block.c | fergy/aplit_linux-5 | a6ef4cb0e17e1eec9743c064e65f730c49765711 | [
"MIT"
] | null | null | null | drivers/memstick/core/ms_block.c | fergy/aplit_linux-5 | a6ef4cb0e17e1eec9743c064e65f730c49765711 | [
"MIT"
] | null | null | null | drivers/memstick/core/ms_block.c | fergy/aplit_linux-5 | a6ef4cb0e17e1eec9743c064e65f730c49765711 | [
"MIT"
] | null | null | null | /*
* ms_block.c - Sony MemoryStick (legacy) storage support
* Copyright (C) 2013 Maxim Levitsky <maximlevitsky@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* Minor portions of the driver were copied from mspro_block.c which is
* Copyright (C) 2007 Alex Dubov <oakad@yahoo.com>
*
*/
#define DRIVER_NAME "ms_block"
#define pr_fmt(fmt) DRIVER_NAME ": " fmt
#include <linux/module.h>
#include <linux/blk-mq.h>
#include <linux/memstick.h>
#include <linux/idr.h>
#include <linux/hdreg.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/random.h>
#include <linux/bitmap.h>
#include <linux/scatterlist.h>
#include <linux/jiffies.h>
#include <linux/workqueue.h>
#include <linux/mutex.h>
#include "ms_block.h"
static int debug;
static int cache_flush_timeout = 1000;
static bool verify_writes;
/*
* Copies section of 'sg_from' starting from offset 'offset' and with length
* 'len' To another scatterlist of to_nents enties
*/
static size_t msb_sg_copy(struct scatterlist *sg_from,
struct scatterlist *sg_to, int to_nents, size_t offset, size_t len)
{
size_t copied = 0;
while (offset > 0) {
if (offset >= sg_from->length) {
if (sg_is_last(sg_from))
return 0;
offset -= sg_from->length;
sg_from = sg_next(sg_from);
continue;
}
copied = min(len, sg_from->length - offset);
sg_set_page(sg_to, sg_page(sg_from),
copied, sg_from->offset + offset);
len -= copied;
offset = 0;
if (sg_is_last(sg_from) || !len)
goto out;
sg_to = sg_next(sg_to);
to_nents--;
sg_from = sg_next(sg_from);
}
while (len > sg_from->length && to_nents--) {
len -= sg_from->length;
copied += sg_from->length;
sg_set_page(sg_to, sg_page(sg_from),
sg_from->length, sg_from->offset);
if (sg_is_last(sg_from) || !len)
goto out;
sg_from = sg_next(sg_from);
sg_to = sg_next(sg_to);
}
if (len && to_nents) {
sg_set_page(sg_to, sg_page(sg_from), len, sg_from->offset);
copied += len;
}
out:
sg_mark_end(sg_to);
return copied;
}
/*
* Compares section of 'sg' starting from offset 'offset' and with length 'len'
* to linear buffer of length 'len' at address 'buffer'
* Returns 0 if equal and -1 otherwice
*/
static int msb_sg_compare_to_buffer(struct scatterlist *sg,
size_t offset, u8 *buffer, size_t len)
{
int retval = 0, cmplen;
struct sg_mapping_iter miter;
sg_miter_start(&miter, sg, sg_nents(sg),
SG_MITER_ATOMIC | SG_MITER_FROM_SG);
while (sg_miter_next(&miter) && len > 0) {
if (offset >= miter.length) {
offset -= miter.length;
continue;
}
cmplen = min(miter.length - offset, len);
retval = memcmp(miter.addr + offset, buffer, cmplen) ? -1 : 0;
if (retval)
break;
buffer += cmplen;
len -= cmplen;
offset = 0;
}
if (!retval && len)
retval = -1;
sg_miter_stop(&miter);
return retval;
}
/* Get zone at which block with logical address 'lba' lives
* Flash is broken into zones.
* Each zone consists of 512 eraseblocks, out of which in first
* zone 494 are used and 496 are for all following zones.
* Therefore zone #0 hosts blocks 0-493, zone #1 blocks 494-988, etc...
*/
static int msb_get_zone_from_lba(int lba)
{
if (lba < 494)
return 0;
return ((lba - 494) / 496) + 1;
}
/* Get zone of physical block. Trivial */
static int msb_get_zone_from_pba(int pba)
{
return pba / MS_BLOCKS_IN_ZONE;
}
/* Debug test to validate free block counts */
static int msb_validate_used_block_bitmap(struct msb_data *msb)
{
int total_free_blocks = 0;
int i;
if (!debug)
return 0;
for (i = 0; i < msb->zone_count; i++)
total_free_blocks += msb->free_block_count[i];
if (msb->block_count - bitmap_weight(msb->used_blocks_bitmap,
msb->block_count) == total_free_blocks)
return 0;
pr_err("BUG: free block counts don't match the bitmap");
msb->read_only = true;
return -EINVAL;
}
/* Mark physical block as used */
static void msb_mark_block_used(struct msb_data *msb, int pba)
{
int zone = msb_get_zone_from_pba(pba);
if (test_bit(pba, msb->used_blocks_bitmap)) {
pr_err(
"BUG: attempt to mark already used pba %d as used", pba);
msb->read_only = true;
return;
}
if (msb_validate_used_block_bitmap(msb))
return;
/* No races because all IO is single threaded */
__set_bit(pba, msb->used_blocks_bitmap);
msb->free_block_count[zone]--;
}
/* Mark physical block as free */
static void msb_mark_block_unused(struct msb_data *msb, int pba)
{
int zone = msb_get_zone_from_pba(pba);
if (!test_bit(pba, msb->used_blocks_bitmap)) {
pr_err("BUG: attempt to mark already unused pba %d as unused" , pba);
msb->read_only = true;
return;
}
if (msb_validate_used_block_bitmap(msb))
return;
/* No races because all IO is single threaded */
__clear_bit(pba, msb->used_blocks_bitmap);
msb->free_block_count[zone]++;
}
/* Invalidate current register window */
static void msb_invalidate_reg_window(struct msb_data *msb)
{
msb->reg_addr.w_offset = offsetof(struct ms_register, id);
msb->reg_addr.w_length = sizeof(struct ms_id_register);
msb->reg_addr.r_offset = offsetof(struct ms_register, id);
msb->reg_addr.r_length = sizeof(struct ms_id_register);
msb->addr_valid = false;
}
/* Start a state machine */
static int msb_run_state_machine(struct msb_data *msb, int (*state_func)
(struct memstick_dev *card, struct memstick_request **req))
{
struct memstick_dev *card = msb->card;
WARN_ON(msb->state != -1);
msb->int_polling = false;
msb->state = 0;
msb->exit_error = 0;
memset(&card->current_mrq, 0, sizeof(card->current_mrq));
card->next_request = state_func;
memstick_new_req(card->host);
wait_for_completion(&card->mrq_complete);
WARN_ON(msb->state != -1);
return msb->exit_error;
}
/* State machines call that to exit */
static int msb_exit_state_machine(struct msb_data *msb, int error)
{
WARN_ON(msb->state == -1);
msb->state = -1;
msb->exit_error = error;
msb->card->next_request = h_msb_default_bad;
/* Invalidate reg window on errors */
if (error)
msb_invalidate_reg_window(msb);
complete(&msb->card->mrq_complete);
return -ENXIO;
}
/* read INT register */
static int msb_read_int_reg(struct msb_data *msb, long timeout)
{
struct memstick_request *mrq = &msb->card->current_mrq;
WARN_ON(msb->state == -1);
if (!msb->int_polling) {
msb->int_timeout = jiffies +
msecs_to_jiffies(timeout == -1 ? 500 : timeout);
msb->int_polling = true;
} else if (time_after(jiffies, msb->int_timeout)) {
mrq->data[0] = MEMSTICK_INT_CMDNAK;
return 0;
}
if ((msb->caps & MEMSTICK_CAP_AUTO_GET_INT) &&
mrq->need_card_int && !mrq->error) {
mrq->data[0] = mrq->int_reg;
mrq->need_card_int = false;
return 0;
} else {
memstick_init_req(mrq, MS_TPC_GET_INT, NULL, 1);
return 1;
}
}
/* Read a register */
static int msb_read_regs(struct msb_data *msb, int offset, int len)
{
struct memstick_request *req = &msb->card->current_mrq;
if (msb->reg_addr.r_offset != offset ||
msb->reg_addr.r_length != len || !msb->addr_valid) {
msb->reg_addr.r_offset = offset;
msb->reg_addr.r_length = len;
msb->addr_valid = true;
memstick_init_req(req, MS_TPC_SET_RW_REG_ADRS,
&msb->reg_addr, sizeof(msb->reg_addr));
return 0;
}
memstick_init_req(req, MS_TPC_READ_REG, NULL, len);
return 1;
}
/* Write a card register */
static int msb_write_regs(struct msb_data *msb, int offset, int len, void *buf)
{
struct memstick_request *req = &msb->card->current_mrq;
if (msb->reg_addr.w_offset != offset ||
msb->reg_addr.w_length != len || !msb->addr_valid) {
msb->reg_addr.w_offset = offset;
msb->reg_addr.w_length = len;
msb->addr_valid = true;
memstick_init_req(req, MS_TPC_SET_RW_REG_ADRS,
&msb->reg_addr, sizeof(msb->reg_addr));
return 0;
}
memstick_init_req(req, MS_TPC_WRITE_REG, buf, len);
return 1;
}
/* Handler for absence of IO */
static int h_msb_default_bad(struct memstick_dev *card,
struct memstick_request **mrq)
{
return -ENXIO;
}
/*
* This function is a handler for reads of one page from device.
* Writes output to msb->current_sg, takes sector address from msb->reg.param
* Can also be used to read extra data only. Set params accordintly.
*/
static int h_msb_read_page(struct memstick_dev *card,
struct memstick_request **out_mrq)
{
struct msb_data *msb = memstick_get_drvdata(card);
struct memstick_request *mrq = *out_mrq = &card->current_mrq;
struct scatterlist sg[2];
u8 command, intreg;
if (mrq->error) {
dbg("read_page, unknown error");
return msb_exit_state_machine(msb, mrq->error);
}
again:
switch (msb->state) {
case MSB_RP_SEND_BLOCK_ADDRESS:
/* msb_write_regs sometimes "fails" because it needs to update
the reg window, and thus it returns request for that.
Then we stay in this state and retry */
if (!msb_write_regs(msb,
offsetof(struct ms_register, param),
sizeof(struct ms_param_register),
(unsigned char *)&msb->regs.param))
return 0;
msb->state = MSB_RP_SEND_READ_COMMAND;
return 0;
case MSB_RP_SEND_READ_COMMAND:
command = MS_CMD_BLOCK_READ;
memstick_init_req(mrq, MS_TPC_SET_CMD, &command, 1);
msb->state = MSB_RP_SEND_INT_REQ;
return 0;
case MSB_RP_SEND_INT_REQ:
msb->state = MSB_RP_RECEIVE_INT_REQ_RESULT;
/* If dont actually need to send the int read request (only in
serial mode), then just fall through */
if (msb_read_int_reg(msb, -1))
return 0;
/* fallthrough */
case MSB_RP_RECEIVE_INT_REQ_RESULT:
intreg = mrq->data[0];
msb->regs.status.interrupt = intreg;
if (intreg & MEMSTICK_INT_CMDNAK)
return msb_exit_state_machine(msb, -EIO);
if (!(intreg & MEMSTICK_INT_CED)) {
msb->state = MSB_RP_SEND_INT_REQ;
goto again;
}
msb->int_polling = false;
msb->state = (intreg & MEMSTICK_INT_ERR) ?
MSB_RP_SEND_READ_STATUS_REG : MSB_RP_SEND_OOB_READ;
goto again;
case MSB_RP_SEND_READ_STATUS_REG:
/* read the status register to understand source of the INT_ERR */
if (!msb_read_regs(msb,
offsetof(struct ms_register, status),
sizeof(struct ms_status_register)))
return 0;
msb->state = MSB_RP_RECEIVE_STATUS_REG;
return 0;
case MSB_RP_RECEIVE_STATUS_REG:
msb->regs.status = *(struct ms_status_register *)mrq->data;
msb->state = MSB_RP_SEND_OOB_READ;
/* fallthrough */
case MSB_RP_SEND_OOB_READ:
if (!msb_read_regs(msb,
offsetof(struct ms_register, extra_data),
sizeof(struct ms_extra_data_register)))
return 0;
msb->state = MSB_RP_RECEIVE_OOB_READ;
return 0;
case MSB_RP_RECEIVE_OOB_READ:
msb->regs.extra_data =
*(struct ms_extra_data_register *) mrq->data;
msb->state = MSB_RP_SEND_READ_DATA;
/* fallthrough */
case MSB_RP_SEND_READ_DATA:
/* Skip that state if we only read the oob */
if (msb->regs.param.cp == MEMSTICK_CP_EXTRA) {
msb->state = MSB_RP_RECEIVE_READ_DATA;
goto again;
}
sg_init_table(sg, ARRAY_SIZE(sg));
msb_sg_copy(msb->current_sg, sg, ARRAY_SIZE(sg),
msb->current_sg_offset,
msb->page_size);
memstick_init_req_sg(mrq, MS_TPC_READ_LONG_DATA, sg);
msb->state = MSB_RP_RECEIVE_READ_DATA;
return 0;
case MSB_RP_RECEIVE_READ_DATA:
if (!(msb->regs.status.interrupt & MEMSTICK_INT_ERR)) {
msb->current_sg_offset += msb->page_size;
return msb_exit_state_machine(msb, 0);
}
if (msb->regs.status.status1 & MEMSTICK_UNCORR_ERROR) {
dbg("read_page: uncorrectable error");
return msb_exit_state_machine(msb, -EBADMSG);
}
if (msb->regs.status.status1 & MEMSTICK_CORR_ERROR) {
dbg("read_page: correctable error");
msb->current_sg_offset += msb->page_size;
return msb_exit_state_machine(msb, -EUCLEAN);
} else {
dbg("read_page: INT error, but no status error bits");
return msb_exit_state_machine(msb, -EIO);
}
}
BUG();
}
/*
* Handler of writes of exactly one block.
* Takes address from msb->regs.param.
* Writes same extra data to blocks, also taken
* from msb->regs.extra
* Returns -EBADMSG if write fails due to uncorrectable error, or -EIO if
* device refuses to take the command or something else
*/
static int h_msb_write_block(struct memstick_dev *card,
struct memstick_request **out_mrq)
{
struct msb_data *msb = memstick_get_drvdata(card);
struct memstick_request *mrq = *out_mrq = &card->current_mrq;
struct scatterlist sg[2];
u8 intreg, command;
if (mrq->error)
return msb_exit_state_machine(msb, mrq->error);
again:
switch (msb->state) {
/* HACK: Jmicon handling of TPCs between 8 and
* sizeof(memstick_request.data) is broken due to hardware
* bug in PIO mode that is used for these TPCs
* Therefore split the write
*/
case MSB_WB_SEND_WRITE_PARAMS:
if (!msb_write_regs(msb,
offsetof(struct ms_register, param),
sizeof(struct ms_param_register),
&msb->regs.param))
return 0;
msb->state = MSB_WB_SEND_WRITE_OOB;
return 0;
case MSB_WB_SEND_WRITE_OOB:
if (!msb_write_regs(msb,
offsetof(struct ms_register, extra_data),
sizeof(struct ms_extra_data_register),
&msb->regs.extra_data))
return 0;
msb->state = MSB_WB_SEND_WRITE_COMMAND;
return 0;
case MSB_WB_SEND_WRITE_COMMAND:
command = MS_CMD_BLOCK_WRITE;
memstick_init_req(mrq, MS_TPC_SET_CMD, &command, 1);
msb->state = MSB_WB_SEND_INT_REQ;
return 0;
case MSB_WB_SEND_INT_REQ:
msb->state = MSB_WB_RECEIVE_INT_REQ;
if (msb_read_int_reg(msb, -1))
return 0;
/* fallthrough */
case MSB_WB_RECEIVE_INT_REQ:
intreg = mrq->data[0];
msb->regs.status.interrupt = intreg;
/* errors mean out of here, and fast... */
if (intreg & (MEMSTICK_INT_CMDNAK))
return msb_exit_state_machine(msb, -EIO);
if (intreg & MEMSTICK_INT_ERR)
return msb_exit_state_machine(msb, -EBADMSG);
/* for last page we need to poll CED */
if (msb->current_page == msb->pages_in_block) {
if (intreg & MEMSTICK_INT_CED)
return msb_exit_state_machine(msb, 0);
msb->state = MSB_WB_SEND_INT_REQ;
goto again;
}
/* for non-last page we need BREQ before writing next chunk */
if (!(intreg & MEMSTICK_INT_BREQ)) {
msb->state = MSB_WB_SEND_INT_REQ;
goto again;
}
msb->int_polling = false;
msb->state = MSB_WB_SEND_WRITE_DATA;
/* fallthrough */
case MSB_WB_SEND_WRITE_DATA:
sg_init_table(sg, ARRAY_SIZE(sg));
if (msb_sg_copy(msb->current_sg, sg, ARRAY_SIZE(sg),
msb->current_sg_offset,
msb->page_size) < msb->page_size)
return msb_exit_state_machine(msb, -EIO);
memstick_init_req_sg(mrq, MS_TPC_WRITE_LONG_DATA, sg);
mrq->need_card_int = 1;
msb->state = MSB_WB_RECEIVE_WRITE_CONFIRMATION;
return 0;
case MSB_WB_RECEIVE_WRITE_CONFIRMATION:
msb->current_page++;
msb->current_sg_offset += msb->page_size;
msb->state = MSB_WB_SEND_INT_REQ;
goto again;
default:
BUG();
}
return 0;
}
/*
* This function is used to send simple IO requests to device that consist
* of register write + command
*/
static int h_msb_send_command(struct memstick_dev *card,
struct memstick_request **out_mrq)
{
struct msb_data *msb = memstick_get_drvdata(card);
struct memstick_request *mrq = *out_mrq = &card->current_mrq;
u8 intreg;
if (mrq->error) {
dbg("send_command: unknown error");
return msb_exit_state_machine(msb, mrq->error);
}
again:
switch (msb->state) {
/* HACK: see h_msb_write_block */
case MSB_SC_SEND_WRITE_PARAMS: /* write param register*/
if (!msb_write_regs(msb,
offsetof(struct ms_register, param),
sizeof(struct ms_param_register),
&msb->regs.param))
return 0;
msb->state = MSB_SC_SEND_WRITE_OOB;
return 0;
case MSB_SC_SEND_WRITE_OOB:
if (!msb->command_need_oob) {
msb->state = MSB_SC_SEND_COMMAND;
goto again;
}
if (!msb_write_regs(msb,
offsetof(struct ms_register, extra_data),
sizeof(struct ms_extra_data_register),
&msb->regs.extra_data))
return 0;
msb->state = MSB_SC_SEND_COMMAND;
return 0;
case MSB_SC_SEND_COMMAND:
memstick_init_req(mrq, MS_TPC_SET_CMD, &msb->command_value, 1);
msb->state = MSB_SC_SEND_INT_REQ;
return 0;
case MSB_SC_SEND_INT_REQ:
msb->state = MSB_SC_RECEIVE_INT_REQ;
if (msb_read_int_reg(msb, -1))
return 0;
/* fallthrough */
case MSB_SC_RECEIVE_INT_REQ:
intreg = mrq->data[0];
if (intreg & MEMSTICK_INT_CMDNAK)
return msb_exit_state_machine(msb, -EIO);
if (intreg & MEMSTICK_INT_ERR)
return msb_exit_state_machine(msb, -EBADMSG);
if (!(intreg & MEMSTICK_INT_CED)) {
msb->state = MSB_SC_SEND_INT_REQ;
goto again;
}
return msb_exit_state_machine(msb, 0);
}
BUG();
}
/* Small handler for card reset */
static int h_msb_reset(struct memstick_dev *card,
struct memstick_request **out_mrq)
{
u8 command = MS_CMD_RESET;
struct msb_data *msb = memstick_get_drvdata(card);
struct memstick_request *mrq = *out_mrq = &card->current_mrq;
if (mrq->error)
return msb_exit_state_machine(msb, mrq->error);
switch (msb->state) {
case MSB_RS_SEND:
memstick_init_req(mrq, MS_TPC_SET_CMD, &command, 1);
mrq->need_card_int = 0;
msb->state = MSB_RS_CONFIRM;
return 0;
case MSB_RS_CONFIRM:
return msb_exit_state_machine(msb, 0);
}
BUG();
}
/* This handler is used to do serial->parallel switch */
static int h_msb_parallel_switch(struct memstick_dev *card,
struct memstick_request **out_mrq)
{
struct msb_data *msb = memstick_get_drvdata(card);
struct memstick_request *mrq = *out_mrq = &card->current_mrq;
struct memstick_host *host = card->host;
if (mrq->error) {
dbg("parallel_switch: error");
msb->regs.param.system &= ~MEMSTICK_SYS_PAM;
return msb_exit_state_machine(msb, mrq->error);
}
switch (msb->state) {
case MSB_PS_SEND_SWITCH_COMMAND:
/* Set the parallel interface on memstick side */
msb->regs.param.system |= MEMSTICK_SYS_PAM;
if (!msb_write_regs(msb,
offsetof(struct ms_register, param),
1,
(unsigned char *)&msb->regs.param))
return 0;
msb->state = MSB_PS_SWICH_HOST;
return 0;
case MSB_PS_SWICH_HOST:
/* Set parallel interface on our side + send a dummy request
to see if card responds */
host->set_param(host, MEMSTICK_INTERFACE, MEMSTICK_PAR4);
memstick_init_req(mrq, MS_TPC_GET_INT, NULL, 1);
msb->state = MSB_PS_CONFIRM;
return 0;
case MSB_PS_CONFIRM:
return msb_exit_state_machine(msb, 0);
}
BUG();
}
static int msb_switch_to_parallel(struct msb_data *msb);
/* Reset the card, to guard against hw errors beeing treated as bad blocks */
static int msb_reset(struct msb_data *msb, bool full)
{
bool was_parallel = msb->regs.param.system & MEMSTICK_SYS_PAM;
struct memstick_dev *card = msb->card;
struct memstick_host *host = card->host;
int error;
/* Reset the card */
msb->regs.param.system = MEMSTICK_SYS_BAMD;
if (full) {
error = host->set_param(host,
MEMSTICK_POWER, MEMSTICK_POWER_OFF);
if (error)
goto out_error;
msb_invalidate_reg_window(msb);
error = host->set_param(host,
MEMSTICK_POWER, MEMSTICK_POWER_ON);
if (error)
goto out_error;
error = host->set_param(host,
MEMSTICK_INTERFACE, MEMSTICK_SERIAL);
if (error) {
out_error:
dbg("Failed to reset the host controller");
msb->read_only = true;
return -EFAULT;
}
}
error = msb_run_state_machine(msb, h_msb_reset);
if (error) {
dbg("Failed to reset the card");
msb->read_only = true;
return -ENODEV;
}
/* Set parallel mode */
if (was_parallel)
msb_switch_to_parallel(msb);
return 0;
}
/* Attempts to switch interface to parallel mode */
static int msb_switch_to_parallel(struct msb_data *msb)
{
int error;
error = msb_run_state_machine(msb, h_msb_parallel_switch);
if (error) {
pr_err("Switch to parallel failed");
msb->regs.param.system &= ~MEMSTICK_SYS_PAM;
msb_reset(msb, true);
return -EFAULT;
}
msb->caps |= MEMSTICK_CAP_AUTO_GET_INT;
return 0;
}
/* Changes overwrite flag on a page */
static int msb_set_overwrite_flag(struct msb_data *msb,
u16 pba, u8 page, u8 flag)
{
if (msb->read_only)
return -EROFS;
msb->regs.param.block_address = cpu_to_be16(pba);
msb->regs.param.page_address = page;
msb->regs.param.cp = MEMSTICK_CP_OVERWRITE;
msb->regs.extra_data.overwrite_flag = flag;
msb->command_value = MS_CMD_BLOCK_WRITE;
msb->command_need_oob = true;
dbg_verbose("changing overwrite flag to %02x for sector %d, page %d",
flag, pba, page);
return msb_run_state_machine(msb, h_msb_send_command);
}
static int msb_mark_bad(struct msb_data *msb, int pba)
{
pr_notice("marking pba %d as bad", pba);
msb_reset(msb, true);
return msb_set_overwrite_flag(
msb, pba, 0, 0xFF & ~MEMSTICK_OVERWRITE_BKST);
}
static int msb_mark_page_bad(struct msb_data *msb, int pba, int page)
{
dbg("marking page %d of pba %d as bad", page, pba);
msb_reset(msb, true);
return msb_set_overwrite_flag(msb,
pba, page, ~MEMSTICK_OVERWRITE_PGST0);
}
/* Erases one physical block */
static int msb_erase_block(struct msb_data *msb, u16 pba)
{
int error, try;
if (msb->read_only)
return -EROFS;
dbg_verbose("erasing pba %d", pba);
for (try = 1; try < 3; try++) {
msb->regs.param.block_address = cpu_to_be16(pba);
msb->regs.param.page_address = 0;
msb->regs.param.cp = MEMSTICK_CP_BLOCK;
msb->command_value = MS_CMD_BLOCK_ERASE;
msb->command_need_oob = false;
error = msb_run_state_machine(msb, h_msb_send_command);
if (!error || msb_reset(msb, true))
break;
}
if (error) {
pr_err("erase failed, marking pba %d as bad", pba);
msb_mark_bad(msb, pba);
}
dbg_verbose("erase success, marking pba %d as unused", pba);
msb_mark_block_unused(msb, pba);
__set_bit(pba, msb->erased_blocks_bitmap);
return error;
}
/* Reads one page from device */
static int msb_read_page(struct msb_data *msb,
u16 pba, u8 page, struct ms_extra_data_register *extra,
struct scatterlist *sg, int offset)
{
int try, error;
if (pba == MS_BLOCK_INVALID) {
unsigned long flags;
struct sg_mapping_iter miter;
size_t len = msb->page_size;
dbg_verbose("read unmapped sector. returning 0xFF");
local_irq_save(flags);
sg_miter_start(&miter, sg, sg_nents(sg),
SG_MITER_ATOMIC | SG_MITER_TO_SG);
while (sg_miter_next(&miter) && len > 0) {
int chunklen;
if (offset && offset >= miter.length) {
offset -= miter.length;
continue;
}
chunklen = min(miter.length - offset, len);
memset(miter.addr + offset, 0xFF, chunklen);
len -= chunklen;
offset = 0;
}
sg_miter_stop(&miter);
local_irq_restore(flags);
if (offset)
return -EFAULT;
if (extra)
memset(extra, 0xFF, sizeof(*extra));
return 0;
}
if (pba >= msb->block_count) {
pr_err("BUG: attempt to read beyond the end of the card at pba %d", pba);
return -EINVAL;
}
for (try = 1; try < 3; try++) {
msb->regs.param.block_address = cpu_to_be16(pba);
msb->regs.param.page_address = page;
msb->regs.param.cp = MEMSTICK_CP_PAGE;
msb->current_sg = sg;
msb->current_sg_offset = offset;
error = msb_run_state_machine(msb, h_msb_read_page);
if (error == -EUCLEAN) {
pr_notice("correctable error on pba %d, page %d",
pba, page);
error = 0;
}
if (!error && extra)
*extra = msb->regs.extra_data;
if (!error || msb_reset(msb, true))
break;
}
/* Mark bad pages */
if (error == -EBADMSG) {
pr_err("uncorrectable error on read of pba %d, page %d",
pba, page);
if (msb->regs.extra_data.overwrite_flag &
MEMSTICK_OVERWRITE_PGST0)
msb_mark_page_bad(msb, pba, page);
return -EBADMSG;
}
if (error)
pr_err("read of pba %d, page %d failed with error %d",
pba, page, error);
return error;
}
/* Reads oob of page only */
static int msb_read_oob(struct msb_data *msb, u16 pba, u16 page,
struct ms_extra_data_register *extra)
{
int error;
BUG_ON(!extra);
msb->regs.param.block_address = cpu_to_be16(pba);
msb->regs.param.page_address = page;
msb->regs.param.cp = MEMSTICK_CP_EXTRA;
if (pba > msb->block_count) {
pr_err("BUG: attempt to read beyond the end of card at pba %d", pba);
return -EINVAL;
}
error = msb_run_state_machine(msb, h_msb_read_page);
*extra = msb->regs.extra_data;
if (error == -EUCLEAN) {
pr_notice("correctable error on pba %d, page %d",
pba, page);
return 0;
}
return error;
}
/* Reads a block and compares it with data contained in scatterlist orig_sg */
static int msb_verify_block(struct msb_data *msb, u16 pba,
struct scatterlist *orig_sg, int offset)
{
struct scatterlist sg;
int page = 0, error;
sg_init_one(&sg, msb->block_buffer, msb->block_size);
while (page < msb->pages_in_block) {
error = msb_read_page(msb, pba, page,
NULL, &sg, page * msb->page_size);
if (error)
return error;
page++;
}
if (msb_sg_compare_to_buffer(orig_sg, offset,
msb->block_buffer, msb->block_size))
return -EIO;
return 0;
}
/* Writes exectly one block + oob */
static int msb_write_block(struct msb_data *msb,
u16 pba, u32 lba, struct scatterlist *sg, int offset)
{
int error, current_try = 1;
BUG_ON(sg->length < msb->page_size);
if (msb->read_only)
return -EROFS;
if (pba == MS_BLOCK_INVALID) {
pr_err(
"BUG: write: attempt to write MS_BLOCK_INVALID block");
return -EINVAL;
}
if (pba >= msb->block_count || lba >= msb->logical_block_count) {
pr_err(
"BUG: write: attempt to write beyond the end of device");
return -EINVAL;
}
if (msb_get_zone_from_lba(lba) != msb_get_zone_from_pba(pba)) {
pr_err("BUG: write: lba zone mismatch");
return -EINVAL;
}
if (pba == msb->boot_block_locations[0] ||
pba == msb->boot_block_locations[1]) {
pr_err("BUG: write: attempt to write to boot blocks!");
return -EINVAL;
}
while (1) {
if (msb->read_only)
return -EROFS;
msb->regs.param.cp = MEMSTICK_CP_BLOCK;
msb->regs.param.page_address = 0;
msb->regs.param.block_address = cpu_to_be16(pba);
msb->regs.extra_data.management_flag = 0xFF;
msb->regs.extra_data.overwrite_flag = 0xF8;
msb->regs.extra_data.logical_address = cpu_to_be16(lba);
msb->current_sg = sg;
msb->current_sg_offset = offset;
msb->current_page = 0;
error = msb_run_state_machine(msb, h_msb_write_block);
/* Sector we just wrote to is assumed erased since its pba
was erased. If it wasn't erased, write will succeed
and will just clear the bits that were set in the block
thus test that what we have written,
matches what we expect.
We do trust the blocks that we erased */
if (!error && (verify_writes ||
!test_bit(pba, msb->erased_blocks_bitmap)))
error = msb_verify_block(msb, pba, sg, offset);
if (!error)
break;
if (current_try > 1 || msb_reset(msb, true))
break;
pr_err("write failed, trying to erase the pba %d", pba);
error = msb_erase_block(msb, pba);
if (error)
break;
current_try++;
}
return error;
}
/* Finds a free block for write replacement */
static u16 msb_get_free_block(struct msb_data *msb, int zone)
{
u16 pos;
int pba = zone * MS_BLOCKS_IN_ZONE;
int i;
get_random_bytes(&pos, sizeof(pos));
if (!msb->free_block_count[zone]) {
pr_err("NO free blocks in the zone %d, to use for a write, (media is WORN out) switching to RO mode", zone);
msb->read_only = true;
return MS_BLOCK_INVALID;
}
pos %= msb->free_block_count[zone];
dbg_verbose("have %d choices for a free block, selected randomally: %d",
msb->free_block_count[zone], pos);
pba = find_next_zero_bit(msb->used_blocks_bitmap,
msb->block_count, pba);
for (i = 0; i < pos; ++i)
pba = find_next_zero_bit(msb->used_blocks_bitmap,
msb->block_count, pba + 1);
dbg_verbose("result of the free blocks scan: pba %d", pba);
if (pba == msb->block_count || (msb_get_zone_from_pba(pba)) != zone) {
pr_err("BUG: cant get a free block");
msb->read_only = true;
return MS_BLOCK_INVALID;
}
msb_mark_block_used(msb, pba);
return pba;
}
static int msb_update_block(struct msb_data *msb, u16 lba,
struct scatterlist *sg, int offset)
{
u16 pba, new_pba;
int error, try;
pba = msb->lba_to_pba_table[lba];
dbg_verbose("start of a block update at lba %d, pba %d", lba, pba);
if (pba != MS_BLOCK_INVALID) {
dbg_verbose("setting the update flag on the block");
msb_set_overwrite_flag(msb, pba, 0,
0xFF & ~MEMSTICK_OVERWRITE_UDST);
}
for (try = 0; try < 3; try++) {
new_pba = msb_get_free_block(msb,
msb_get_zone_from_lba(lba));
if (new_pba == MS_BLOCK_INVALID) {
error = -EIO;
goto out;
}
dbg_verbose("block update: writing updated block to the pba %d",
new_pba);
error = msb_write_block(msb, new_pba, lba, sg, offset);
if (error == -EBADMSG) {
msb_mark_bad(msb, new_pba);
continue;
}
if (error)
goto out;
dbg_verbose("block update: erasing the old block");
msb_erase_block(msb, pba);
msb->lba_to_pba_table[lba] = new_pba;
return 0;
}
out:
if (error) {
pr_err("block update error after %d tries, switching to r/o mode", try);
msb->read_only = true;
}
return error;
}
/* Converts endiannes in the boot block for easy use */
static void msb_fix_boot_page_endianness(struct ms_boot_page *p)
{
p->header.block_id = be16_to_cpu(p->header.block_id);
p->header.format_reserved = be16_to_cpu(p->header.format_reserved);
p->entry.disabled_block.start_addr
= be32_to_cpu(p->entry.disabled_block.start_addr);
p->entry.disabled_block.data_size
= be32_to_cpu(p->entry.disabled_block.data_size);
p->entry.cis_idi.start_addr
= be32_to_cpu(p->entry.cis_idi.start_addr);
p->entry.cis_idi.data_size
= be32_to_cpu(p->entry.cis_idi.data_size);
p->attr.block_size = be16_to_cpu(p->attr.block_size);
p->attr.number_of_blocks = be16_to_cpu(p->attr.number_of_blocks);
p->attr.number_of_effective_blocks
= be16_to_cpu(p->attr.number_of_effective_blocks);
p->attr.page_size = be16_to_cpu(p->attr.page_size);
p->attr.memory_manufacturer_code
= be16_to_cpu(p->attr.memory_manufacturer_code);
p->attr.memory_device_code = be16_to_cpu(p->attr.memory_device_code);
p->attr.implemented_capacity
= be16_to_cpu(p->attr.implemented_capacity);
p->attr.controller_number = be16_to_cpu(p->attr.controller_number);
p->attr.controller_function = be16_to_cpu(p->attr.controller_function);
}
static int msb_read_boot_blocks(struct msb_data *msb)
{
int pba = 0;
struct scatterlist sg;
struct ms_extra_data_register extra;
struct ms_boot_page *page;
msb->boot_block_locations[0] = MS_BLOCK_INVALID;
msb->boot_block_locations[1] = MS_BLOCK_INVALID;
msb->boot_block_count = 0;
dbg_verbose("Start of a scan for the boot blocks");
if (!msb->boot_page) {
page = kmalloc_array(2, sizeof(struct ms_boot_page),
GFP_KERNEL);
if (!page)
return -ENOMEM;
msb->boot_page = page;
} else
page = msb->boot_page;
msb->block_count = MS_BLOCK_MAX_BOOT_ADDR;
for (pba = 0; pba < MS_BLOCK_MAX_BOOT_ADDR; pba++) {
sg_init_one(&sg, page, sizeof(*page));
if (msb_read_page(msb, pba, 0, &extra, &sg, 0)) {
dbg("boot scan: can't read pba %d", pba);
continue;
}
if (extra.management_flag & MEMSTICK_MANAGEMENT_SYSFLG) {
dbg("management flag doesn't indicate boot block %d",
pba);
continue;
}
if (be16_to_cpu(page->header.block_id) != MS_BLOCK_BOOT_ID) {
dbg("the pba at %d doesn' contain boot block ID", pba);
continue;
}
msb_fix_boot_page_endianness(page);
msb->boot_block_locations[msb->boot_block_count] = pba;
page++;
msb->boot_block_count++;
if (msb->boot_block_count == 2)
break;
}
if (!msb->boot_block_count) {
pr_err("media doesn't contain master page, aborting");
return -EIO;
}
dbg_verbose("End of scan for boot blocks");
return 0;
}
static int msb_read_bad_block_table(struct msb_data *msb, int block_nr)
{
struct ms_boot_page *boot_block;
struct scatterlist sg;
u16 *buffer = NULL;
int offset = 0;
int i, error = 0;
int data_size, data_offset, page, page_offset, size_to_read;
u16 pba;
BUG_ON(block_nr > 1);
boot_block = &msb->boot_page[block_nr];
pba = msb->boot_block_locations[block_nr];
if (msb->boot_block_locations[block_nr] == MS_BLOCK_INVALID)
return -EINVAL;
data_size = boot_block->entry.disabled_block.data_size;
data_offset = sizeof(struct ms_boot_page) +
boot_block->entry.disabled_block.start_addr;
if (!data_size)
return 0;
page = data_offset / msb->page_size;
page_offset = data_offset % msb->page_size;
size_to_read =
DIV_ROUND_UP(data_size + page_offset, msb->page_size) *
msb->page_size;
dbg("reading bad block of boot block at pba %d, offset %d len %d",
pba, data_offset, data_size);
buffer = kzalloc(size_to_read, GFP_KERNEL);
if (!buffer)
return -ENOMEM;
/* Read the buffer */
sg_init_one(&sg, buffer, size_to_read);
while (offset < size_to_read) {
error = msb_read_page(msb, pba, page, NULL, &sg, offset);
if (error)
goto out;
page++;
offset += msb->page_size;
if (page == msb->pages_in_block) {
pr_err(
"bad block table extends beyond the boot block");
break;
}
}
/* Process the bad block table */
for (i = page_offset; i < data_size / sizeof(u16); i++) {
u16 bad_block = be16_to_cpu(buffer[i]);
if (bad_block >= msb->block_count) {
dbg("bad block table contains invalid block %d",
bad_block);
continue;
}
if (test_bit(bad_block, msb->used_blocks_bitmap)) {
dbg("duplicate bad block %d in the table",
bad_block);
continue;
}
dbg("block %d is marked as factory bad", bad_block);
msb_mark_block_used(msb, bad_block);
}
out:
kfree(buffer);
return error;
}
static int msb_ftl_initialize(struct msb_data *msb)
{
int i;
if (msb->ftl_initialized)
return 0;
msb->zone_count = msb->block_count / MS_BLOCKS_IN_ZONE;
msb->logical_block_count = msb->zone_count * 496 - 2;
msb->used_blocks_bitmap = kzalloc(msb->block_count / 8, GFP_KERNEL);
msb->erased_blocks_bitmap = kzalloc(msb->block_count / 8, GFP_KERNEL);
msb->lba_to_pba_table =
kmalloc_array(msb->logical_block_count, sizeof(u16),
GFP_KERNEL);
if (!msb->used_blocks_bitmap || !msb->lba_to_pba_table ||
!msb->erased_blocks_bitmap) {
kfree(msb->used_blocks_bitmap);
kfree(msb->lba_to_pba_table);
kfree(msb->erased_blocks_bitmap);
return -ENOMEM;
}
for (i = 0; i < msb->zone_count; i++)
msb->free_block_count[i] = MS_BLOCKS_IN_ZONE;
memset(msb->lba_to_pba_table, MS_BLOCK_INVALID,
msb->logical_block_count * sizeof(u16));
dbg("initial FTL tables created. Zone count = %d, Logical block count = %d",
msb->zone_count, msb->logical_block_count);
msb->ftl_initialized = true;
return 0;
}
static int msb_ftl_scan(struct msb_data *msb)
{
u16 pba, lba, other_block;
u8 overwrite_flag, management_flag, other_overwrite_flag;
int error;
struct ms_extra_data_register extra;
u8 *overwrite_flags = kzalloc(msb->block_count, GFP_KERNEL);
if (!overwrite_flags)
return -ENOMEM;
dbg("Start of media scanning");
for (pba = 0; pba < msb->block_count; pba++) {
if (pba == msb->boot_block_locations[0] ||
pba == msb->boot_block_locations[1]) {
dbg_verbose("pba %05d -> [boot block]", pba);
msb_mark_block_used(msb, pba);
continue;
}
if (test_bit(pba, msb->used_blocks_bitmap)) {
dbg_verbose("pba %05d -> [factory bad]", pba);
continue;
}
memset(&extra, 0, sizeof(extra));
error = msb_read_oob(msb, pba, 0, &extra);
/* can't trust the page if we can't read the oob */
if (error == -EBADMSG) {
pr_notice(
"oob of pba %d damaged, will try to erase it", pba);
msb_mark_block_used(msb, pba);
msb_erase_block(msb, pba);
continue;
} else if (error) {
pr_err("unknown error %d on read of oob of pba %d - aborting",
error, pba);
kfree(overwrite_flags);
return error;
}
lba = be16_to_cpu(extra.logical_address);
management_flag = extra.management_flag;
overwrite_flag = extra.overwrite_flag;
overwrite_flags[pba] = overwrite_flag;
/* Skip bad blocks */
if (!(overwrite_flag & MEMSTICK_OVERWRITE_BKST)) {
dbg("pba %05d -> [BAD]", pba);
msb_mark_block_used(msb, pba);
continue;
}
/* Skip system/drm blocks */
if ((management_flag & MEMSTICK_MANAGEMENT_FLAG_NORMAL) !=
MEMSTICK_MANAGEMENT_FLAG_NORMAL) {
dbg("pba %05d -> [reserved management flag %02x]",
pba, management_flag);
msb_mark_block_used(msb, pba);
continue;
}
/* Erase temporary tables */
if (!(management_flag & MEMSTICK_MANAGEMENT_ATFLG)) {
dbg("pba %05d -> [temp table] - will erase", pba);
msb_mark_block_used(msb, pba);
msb_erase_block(msb, pba);
continue;
}
if (lba == MS_BLOCK_INVALID) {
dbg_verbose("pba %05d -> [free]", pba);
continue;
}
msb_mark_block_used(msb, pba);
/* Block has LBA not according to zoning*/
if (msb_get_zone_from_lba(lba) != msb_get_zone_from_pba(pba)) {
pr_notice("pba %05d -> [bad lba %05d] - will erase",
pba, lba);
msb_erase_block(msb, pba);
continue;
}
/* No collisions - great */
if (msb->lba_to_pba_table[lba] == MS_BLOCK_INVALID) {
dbg_verbose("pba %05d -> [lba %05d]", pba, lba);
msb->lba_to_pba_table[lba] = pba;
continue;
}
other_block = msb->lba_to_pba_table[lba];
other_overwrite_flag = overwrite_flags[other_block];
pr_notice("Collision between pba %d and pba %d",
pba, other_block);
if (!(overwrite_flag & MEMSTICK_OVERWRITE_UDST)) {
pr_notice("pba %d is marked as stable, use it", pba);
msb_erase_block(msb, other_block);
msb->lba_to_pba_table[lba] = pba;
continue;
}
if (!(other_overwrite_flag & MEMSTICK_OVERWRITE_UDST)) {
pr_notice("pba %d is marked as stable, use it",
other_block);
msb_erase_block(msb, pba);
continue;
}
pr_notice("collision between blocks %d and %d, without stable flag set on both, erasing pba %d",
pba, other_block, other_block);
msb_erase_block(msb, other_block);
msb->lba_to_pba_table[lba] = pba;
}
dbg("End of media scanning");
kfree(overwrite_flags);
return 0;
}
static void msb_cache_flush_timer(struct timer_list *t)
{
struct msb_data *msb = from_timer(msb, t, cache_flush_timer);
msb->need_flush_cache = true;
queue_work(msb->io_queue, &msb->io_work);
}
static void msb_cache_discard(struct msb_data *msb)
{
if (msb->cache_block_lba == MS_BLOCK_INVALID)
return;
del_timer_sync(&msb->cache_flush_timer);
dbg_verbose("Discarding the write cache");
msb->cache_block_lba = MS_BLOCK_INVALID;
bitmap_zero(&msb->valid_cache_bitmap, msb->pages_in_block);
}
static int msb_cache_init(struct msb_data *msb)
{
timer_setup(&msb->cache_flush_timer, msb_cache_flush_timer, 0);
if (!msb->cache)
msb->cache = kzalloc(msb->block_size, GFP_KERNEL);
if (!msb->cache)
return -ENOMEM;
msb_cache_discard(msb);
return 0;
}
static int msb_cache_flush(struct msb_data *msb)
{
struct scatterlist sg;
struct ms_extra_data_register extra;
int page, offset, error;
u16 pba, lba;
if (msb->read_only)
return -EROFS;
if (msb->cache_block_lba == MS_BLOCK_INVALID)
return 0;
lba = msb->cache_block_lba;
pba = msb->lba_to_pba_table[lba];
dbg_verbose("Flushing the write cache of pba %d (LBA %d)",
pba, msb->cache_block_lba);
sg_init_one(&sg, msb->cache , msb->block_size);
/* Read all missing pages in cache */
for (page = 0; page < msb->pages_in_block; page++) {
if (test_bit(page, &msb->valid_cache_bitmap))
continue;
offset = page * msb->page_size;
dbg_verbose("reading non-present sector %d of cache block %d",
page, lba);
error = msb_read_page(msb, pba, page, &extra, &sg, offset);
/* Bad pages are copied with 00 page status */
if (error == -EBADMSG) {
pr_err("read error on sector %d, contents probably damaged", page);
continue;
}
if (error)
return error;
if ((extra.overwrite_flag & MEMSTICK_OV_PG_NORMAL) !=
MEMSTICK_OV_PG_NORMAL) {
dbg("page %d is marked as bad", page);
continue;
}
set_bit(page, &msb->valid_cache_bitmap);
}
/* Write the cache now */
error = msb_update_block(msb, msb->cache_block_lba, &sg, 0);
pba = msb->lba_to_pba_table[msb->cache_block_lba];
/* Mark invalid pages */
if (!error) {
for (page = 0; page < msb->pages_in_block; page++) {
if (test_bit(page, &msb->valid_cache_bitmap))
continue;
dbg("marking page %d as containing damaged data",
page);
msb_set_overwrite_flag(msb,
pba , page, 0xFF & ~MEMSTICK_OV_PG_NORMAL);
}
}
msb_cache_discard(msb);
return error;
}
static int msb_cache_write(struct msb_data *msb, int lba,
int page, bool add_to_cache_only, struct scatterlist *sg, int offset)
{
int error;
struct scatterlist sg_tmp[10];
if (msb->read_only)
return -EROFS;
if (msb->cache_block_lba == MS_BLOCK_INVALID ||
lba != msb->cache_block_lba)
if (add_to_cache_only)
return 0;
/* If we need to write different block */
if (msb->cache_block_lba != MS_BLOCK_INVALID &&
lba != msb->cache_block_lba) {
dbg_verbose("first flush the cache");
error = msb_cache_flush(msb);
if (error)
return error;
}
if (msb->cache_block_lba == MS_BLOCK_INVALID) {
msb->cache_block_lba = lba;
mod_timer(&msb->cache_flush_timer,
jiffies + msecs_to_jiffies(cache_flush_timeout));
}
dbg_verbose("Write of LBA %d page %d to cache ", lba, page);
sg_init_table(sg_tmp, ARRAY_SIZE(sg_tmp));
msb_sg_copy(sg, sg_tmp, ARRAY_SIZE(sg_tmp), offset, msb->page_size);
sg_copy_to_buffer(sg_tmp, sg_nents(sg_tmp),
msb->cache + page * msb->page_size, msb->page_size);
set_bit(page, &msb->valid_cache_bitmap);
return 0;
}
static int msb_cache_read(struct msb_data *msb, int lba,
int page, struct scatterlist *sg, int offset)
{
int pba = msb->lba_to_pba_table[lba];
struct scatterlist sg_tmp[10];
int error = 0;
if (lba == msb->cache_block_lba &&
test_bit(page, &msb->valid_cache_bitmap)) {
dbg_verbose("Read of LBA %d (pba %d) sector %d from cache",
lba, pba, page);
sg_init_table(sg_tmp, ARRAY_SIZE(sg_tmp));
msb_sg_copy(sg, sg_tmp, ARRAY_SIZE(sg_tmp),
offset, msb->page_size);
sg_copy_from_buffer(sg_tmp, sg_nents(sg_tmp),
msb->cache + msb->page_size * page,
msb->page_size);
} else {
dbg_verbose("Read of LBA %d (pba %d) sector %d from device",
lba, pba, page);
error = msb_read_page(msb, pba, page, NULL, sg, offset);
if (error)
return error;
msb_cache_write(msb, lba, page, true, sg, offset);
}
return error;
}
/* Emulated geometry table
* This table content isn't that importaint,
* One could put here different values, providing that they still
* cover whole disk.
* 64 MB entry is what windows reports for my 64M memstick */
static const struct chs_entry chs_table[] = {
/* size sectors cylynders heads */
{ 4, 16, 247, 2 },
{ 8, 16, 495, 2 },
{ 16, 16, 495, 4 },
{ 32, 16, 991, 4 },
{ 64, 16, 991, 8 },
{128, 16, 991, 16 },
{ 0 }
};
/* Load information about the card */
static int msb_init_card(struct memstick_dev *card)
{
struct msb_data *msb = memstick_get_drvdata(card);
struct memstick_host *host = card->host;
struct ms_boot_page *boot_block;
int error = 0, i, raw_size_in_megs;
msb->caps = 0;
if (card->id.class >= MEMSTICK_CLASS_ROM &&
card->id.class <= MEMSTICK_CLASS_ROM)
msb->read_only = true;
msb->state = -1;
error = msb_reset(msb, false);
if (error)
return error;
/* Due to a bug in Jmicron driver written by Alex Dubov,
its serial mode barely works,
so we switch to parallel mode right away */
if (host->caps & MEMSTICK_CAP_PAR4)
msb_switch_to_parallel(msb);
msb->page_size = sizeof(struct ms_boot_page);
/* Read the boot page */
error = msb_read_boot_blocks(msb);
if (error)
return -EIO;
boot_block = &msb->boot_page[0];
/* Save intersting attributes from boot page */
msb->block_count = boot_block->attr.number_of_blocks;
msb->page_size = boot_block->attr.page_size;
msb->pages_in_block = boot_block->attr.block_size * 2;
msb->block_size = msb->page_size * msb->pages_in_block;
if (msb->page_size > PAGE_SIZE) {
/* this isn't supported by linux at all, anyway*/
dbg("device page %d size isn't supported", msb->page_size);
return -EINVAL;
}
msb->block_buffer = kzalloc(msb->block_size, GFP_KERNEL);
if (!msb->block_buffer)
return -ENOMEM;
raw_size_in_megs = (msb->block_size * msb->block_count) >> 20;
for (i = 0; chs_table[i].size; i++) {
if (chs_table[i].size != raw_size_in_megs)
continue;
msb->geometry.cylinders = chs_table[i].cyl;
msb->geometry.heads = chs_table[i].head;
msb->geometry.sectors = chs_table[i].sec;
break;
}
if (boot_block->attr.transfer_supporting == 1)
msb->caps |= MEMSTICK_CAP_PAR4;
if (boot_block->attr.device_type & 0x03)
msb->read_only = true;
dbg("Total block count = %d", msb->block_count);
dbg("Each block consists of %d pages", msb->pages_in_block);
dbg("Page size = %d bytes", msb->page_size);
dbg("Parallel mode supported: %d", !!(msb->caps & MEMSTICK_CAP_PAR4));
dbg("Read only: %d", msb->read_only);
#if 0
/* Now we can switch the interface */
if (host->caps & msb->caps & MEMSTICK_CAP_PAR4)
msb_switch_to_parallel(msb);
#endif
error = msb_cache_init(msb);
if (error)
return error;
error = msb_ftl_initialize(msb);
if (error)
return error;
/* Read the bad block table */
error = msb_read_bad_block_table(msb, 0);
if (error && error != -ENOMEM) {
dbg("failed to read bad block table from primary boot block, trying from backup");
error = msb_read_bad_block_table(msb, 1);
}
if (error)
return error;
/* *drum roll* Scan the media */
error = msb_ftl_scan(msb);
if (error) {
pr_err("Scan of media failed");
return error;
}
return 0;
}
static int msb_do_write_request(struct msb_data *msb, int lba,
int page, struct scatterlist *sg, size_t len, int *sucessfuly_written)
{
int error = 0;
off_t offset = 0;
*sucessfuly_written = 0;
while (offset < len) {
if (page == 0 && len - offset >= msb->block_size) {
if (msb->cache_block_lba == lba)
msb_cache_discard(msb);
dbg_verbose("Writing whole lba %d", lba);
error = msb_update_block(msb, lba, sg, offset);
if (error)
return error;
offset += msb->block_size;
*sucessfuly_written += msb->block_size;
lba++;
continue;
}
error = msb_cache_write(msb, lba, page, false, sg, offset);
if (error)
return error;
offset += msb->page_size;
*sucessfuly_written += msb->page_size;
page++;
if (page == msb->pages_in_block) {
page = 0;
lba++;
}
}
return 0;
}
static int msb_do_read_request(struct msb_data *msb, int lba,
int page, struct scatterlist *sg, int len, int *sucessfuly_read)
{
int error = 0;
int offset = 0;
*sucessfuly_read = 0;
while (offset < len) {
error = msb_cache_read(msb, lba, page, sg, offset);
if (error)
return error;
offset += msb->page_size;
*sucessfuly_read += msb->page_size;
page++;
if (page == msb->pages_in_block) {
page = 0;
lba++;
}
}
return 0;
}
static void msb_io_work(struct work_struct *work)
{
struct msb_data *msb = container_of(work, struct msb_data, io_work);
int page, error, len;
sector_t lba;
struct scatterlist *sg = msb->prealloc_sg;
struct request *req;
dbg_verbose("IO: work started");
while (1) {
spin_lock_irq(&msb->q_lock);
if (msb->need_flush_cache) {
msb->need_flush_cache = false;
spin_unlock_irq(&msb->q_lock);
msb_cache_flush(msb);
continue;
}
req = msb->req;
if (!req) {
dbg_verbose("IO: no more requests exiting");
spin_unlock_irq(&msb->q_lock);
return;
}
spin_unlock_irq(&msb->q_lock);
/* process the request */
dbg_verbose("IO: processing new request");
blk_rq_map_sg(msb->queue, req, sg);
lba = blk_rq_pos(req);
sector_div(lba, msb->page_size / 512);
page = sector_div(lba, msb->pages_in_block);
if (rq_data_dir(msb->req) == READ)
error = msb_do_read_request(msb, lba, page, sg,
blk_rq_bytes(req), &len);
else
error = msb_do_write_request(msb, lba, page, sg,
blk_rq_bytes(req), &len);
if (len && !blk_update_request(req, BLK_STS_OK, len)) {
__blk_mq_end_request(req, BLK_STS_OK);
spin_lock_irq(&msb->q_lock);
msb->req = NULL;
spin_unlock_irq(&msb->q_lock);
}
if (error && msb->req) {
blk_status_t ret = errno_to_blk_status(error);
dbg_verbose("IO: ending one sector of the request with error");
blk_mq_end_request(req, ret);
spin_lock_irq(&msb->q_lock);
msb->req = NULL;
spin_unlock_irq(&msb->q_lock);
}
if (msb->req)
dbg_verbose("IO: request still pending");
}
}
static DEFINE_IDR(msb_disk_idr); /*set of used disk numbers */
static DEFINE_MUTEX(msb_disk_lock); /* protects against races in open/release */
static int msb_bd_open(struct block_device *bdev, fmode_t mode)
{
struct gendisk *disk = bdev->bd_disk;
struct msb_data *msb = disk->private_data;
dbg_verbose("block device open");
mutex_lock(&msb_disk_lock);
if (msb && msb->card)
msb->usage_count++;
mutex_unlock(&msb_disk_lock);
return 0;
}
static void msb_data_clear(struct msb_data *msb)
{
kfree(msb->boot_page);
kfree(msb->used_blocks_bitmap);
kfree(msb->lba_to_pba_table);
kfree(msb->cache);
msb->card = NULL;
}
static int msb_disk_release(struct gendisk *disk)
{
struct msb_data *msb = disk->private_data;
dbg_verbose("block device release");
mutex_lock(&msb_disk_lock);
if (msb) {
if (msb->usage_count)
msb->usage_count--;
if (!msb->usage_count) {
disk->private_data = NULL;
idr_remove(&msb_disk_idr, msb->disk_id);
put_disk(disk);
kfree(msb);
}
}
mutex_unlock(&msb_disk_lock);
return 0;
}
static void msb_bd_release(struct gendisk *disk, fmode_t mode)
{
msb_disk_release(disk);
}
static int msb_bd_getgeo(struct block_device *bdev,
struct hd_geometry *geo)
{
struct msb_data *msb = bdev->bd_disk->private_data;
*geo = msb->geometry;
return 0;
}
static blk_status_t msb_queue_rq(struct blk_mq_hw_ctx *hctx,
const struct blk_mq_queue_data *bd)
{
struct memstick_dev *card = hctx->queue->queuedata;
struct msb_data *msb = memstick_get_drvdata(card);
struct request *req = bd->rq;
dbg_verbose("Submit request");
spin_lock_irq(&msb->q_lock);
if (msb->card_dead) {
dbg("Refusing requests on removed card");
WARN_ON(!msb->io_queue_stopped);
spin_unlock_irq(&msb->q_lock);
blk_mq_start_request(req);
return BLK_STS_IOERR;
}
if (msb->req) {
spin_unlock_irq(&msb->q_lock);
return BLK_STS_DEV_RESOURCE;
}
blk_mq_start_request(req);
msb->req = req;
if (!msb->io_queue_stopped)
queue_work(msb->io_queue, &msb->io_work);
spin_unlock_irq(&msb->q_lock);
return BLK_STS_OK;
}
static int msb_check_card(struct memstick_dev *card)
{
struct msb_data *msb = memstick_get_drvdata(card);
return (msb->card_dead == 0);
}
static void msb_stop(struct memstick_dev *card)
{
struct msb_data *msb = memstick_get_drvdata(card);
unsigned long flags;
dbg("Stopping all msblock IO");
blk_mq_stop_hw_queues(msb->queue);
spin_lock_irqsave(&msb->q_lock, flags);
msb->io_queue_stopped = true;
spin_unlock_irqrestore(&msb->q_lock, flags);
del_timer_sync(&msb->cache_flush_timer);
flush_workqueue(msb->io_queue);
spin_lock_irqsave(&msb->q_lock, flags);
if (msb->req) {
blk_mq_requeue_request(msb->req, false);
msb->req = NULL;
}
spin_unlock_irqrestore(&msb->q_lock, flags);
}
static void msb_start(struct memstick_dev *card)
{
struct msb_data *msb = memstick_get_drvdata(card);
unsigned long flags;
dbg("Resuming IO from msblock");
msb_invalidate_reg_window(msb);
spin_lock_irqsave(&msb->q_lock, flags);
if (!msb->io_queue_stopped || msb->card_dead) {
spin_unlock_irqrestore(&msb->q_lock, flags);
return;
}
spin_unlock_irqrestore(&msb->q_lock, flags);
/* Kick cache flush anyway, its harmless */
msb->need_flush_cache = true;
msb->io_queue_stopped = false;
blk_mq_start_hw_queues(msb->queue);
queue_work(msb->io_queue, &msb->io_work);
}
static const struct block_device_operations msb_bdops = {
.open = msb_bd_open,
.release = msb_bd_release,
.getgeo = msb_bd_getgeo,
.owner = THIS_MODULE
};
static const struct blk_mq_ops msb_mq_ops = {
.queue_rq = msb_queue_rq,
};
/* Registers the block device */
static int msb_init_disk(struct memstick_dev *card)
{
struct msb_data *msb = memstick_get_drvdata(card);
int rc;
unsigned long capacity;
mutex_lock(&msb_disk_lock);
msb->disk_id = idr_alloc(&msb_disk_idr, card, 0, 256, GFP_KERNEL);
mutex_unlock(&msb_disk_lock);
if (msb->disk_id < 0)
return msb->disk_id;
msb->disk = alloc_disk(0);
if (!msb->disk) {
rc = -ENOMEM;
goto out_release_id;
}
msb->queue = blk_mq_init_sq_queue(&msb->tag_set, &msb_mq_ops, 2,
BLK_MQ_F_SHOULD_MERGE);
if (IS_ERR(msb->queue)) {
rc = PTR_ERR(msb->queue);
msb->queue = NULL;
goto out_put_disk;
}
msb->queue->queuedata = card;
blk_queue_max_hw_sectors(msb->queue, MS_BLOCK_MAX_PAGES);
blk_queue_max_segments(msb->queue, MS_BLOCK_MAX_SEGS);
blk_queue_max_segment_size(msb->queue,
MS_BLOCK_MAX_PAGES * msb->page_size);
blk_queue_logical_block_size(msb->queue, msb->page_size);
sprintf(msb->disk->disk_name, "msblk%d", msb->disk_id);
msb->disk->fops = &msb_bdops;
msb->disk->private_data = msb;
msb->disk->queue = msb->queue;
msb->disk->flags |= GENHD_FL_EXT_DEVT;
capacity = msb->pages_in_block * msb->logical_block_count;
capacity *= (msb->page_size / 512);
set_capacity(msb->disk, capacity);
dbg("Set total disk size to %lu sectors", capacity);
msb->usage_count = 1;
msb->io_queue = alloc_ordered_workqueue("ms_block", WQ_MEM_RECLAIM);
INIT_WORK(&msb->io_work, msb_io_work);
sg_init_table(msb->prealloc_sg, MS_BLOCK_MAX_SEGS+1);
if (msb->read_only)
set_disk_ro(msb->disk, 1);
msb_start(card);
device_add_disk(&card->dev, msb->disk, NULL);
dbg("Disk added");
return 0;
out_put_disk:
put_disk(msb->disk);
out_release_id:
mutex_lock(&msb_disk_lock);
idr_remove(&msb_disk_idr, msb->disk_id);
mutex_unlock(&msb_disk_lock);
return rc;
}
static int msb_probe(struct memstick_dev *card)
{
struct msb_data *msb;
int rc = 0;
msb = kzalloc(sizeof(struct msb_data), GFP_KERNEL);
if (!msb)
return -ENOMEM;
memstick_set_drvdata(card, msb);
msb->card = card;
spin_lock_init(&msb->q_lock);
rc = msb_init_card(card);
if (rc)
goto out_free;
rc = msb_init_disk(card);
if (!rc) {
card->check = msb_check_card;
card->stop = msb_stop;
card->start = msb_start;
return 0;
}
out_free:
memstick_set_drvdata(card, NULL);
msb_data_clear(msb);
kfree(msb);
return rc;
}
static void msb_remove(struct memstick_dev *card)
{
struct msb_data *msb = memstick_get_drvdata(card);
unsigned long flags;
if (!msb->io_queue_stopped)
msb_stop(card);
dbg("Removing the disk device");
/* Take care of unhandled + new requests from now on */
spin_lock_irqsave(&msb->q_lock, flags);
msb->card_dead = true;
spin_unlock_irqrestore(&msb->q_lock, flags);
blk_mq_start_hw_queues(msb->queue);
/* Remove the disk */
del_gendisk(msb->disk);
blk_cleanup_queue(msb->queue);
blk_mq_free_tag_set(&msb->tag_set);
msb->queue = NULL;
mutex_lock(&msb_disk_lock);
msb_data_clear(msb);
mutex_unlock(&msb_disk_lock);
msb_disk_release(msb->disk);
memstick_set_drvdata(card, NULL);
}
#ifdef CONFIG_PM
static int msb_suspend(struct memstick_dev *card, pm_message_t state)
{
msb_stop(card);
return 0;
}
static int msb_resume(struct memstick_dev *card)
{
struct msb_data *msb = memstick_get_drvdata(card);
struct msb_data *new_msb = NULL;
bool card_dead = true;
#ifndef CONFIG_MEMSTICK_UNSAFE_RESUME
msb->card_dead = true;
return 0;
#endif
mutex_lock(&card->host->lock);
new_msb = kzalloc(sizeof(struct msb_data), GFP_KERNEL);
if (!new_msb)
goto out;
new_msb->card = card;
memstick_set_drvdata(card, new_msb);
spin_lock_init(&new_msb->q_lock);
sg_init_table(msb->prealloc_sg, MS_BLOCK_MAX_SEGS+1);
if (msb_init_card(card))
goto out;
if (msb->block_size != new_msb->block_size)
goto out;
if (memcmp(msb->boot_page, new_msb->boot_page,
sizeof(struct ms_boot_page)))
goto out;
if (msb->logical_block_count != new_msb->logical_block_count ||
memcmp(msb->lba_to_pba_table, new_msb->lba_to_pba_table,
msb->logical_block_count))
goto out;
if (msb->block_count != new_msb->block_count ||
memcmp(msb->used_blocks_bitmap, new_msb->used_blocks_bitmap,
msb->block_count / 8))
goto out;
card_dead = false;
out:
if (card_dead)
dbg("Card was removed/replaced during suspend");
msb->card_dead = card_dead;
memstick_set_drvdata(card, msb);
if (new_msb) {
msb_data_clear(new_msb);
kfree(new_msb);
}
msb_start(card);
mutex_unlock(&card->host->lock);
return 0;
}
#else
#define msb_suspend NULL
#define msb_resume NULL
#endif /* CONFIG_PM */
static struct memstick_device_id msb_id_tbl[] = {
{MEMSTICK_MATCH_ALL, MEMSTICK_TYPE_LEGACY, MEMSTICK_CATEGORY_STORAGE,
MEMSTICK_CLASS_FLASH},
{MEMSTICK_MATCH_ALL, MEMSTICK_TYPE_LEGACY, MEMSTICK_CATEGORY_STORAGE,
MEMSTICK_CLASS_ROM},
{MEMSTICK_MATCH_ALL, MEMSTICK_TYPE_LEGACY, MEMSTICK_CATEGORY_STORAGE,
MEMSTICK_CLASS_RO},
{MEMSTICK_MATCH_ALL, MEMSTICK_TYPE_LEGACY, MEMSTICK_CATEGORY_STORAGE,
MEMSTICK_CLASS_WP},
{MEMSTICK_MATCH_ALL, MEMSTICK_TYPE_DUO, MEMSTICK_CATEGORY_STORAGE_DUO,
MEMSTICK_CLASS_DUO},
{}
};
MODULE_DEVICE_TABLE(memstick, msb_id_tbl);
static struct memstick_driver msb_driver = {
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE
},
.id_table = msb_id_tbl,
.probe = msb_probe,
.remove = msb_remove,
.suspend = msb_suspend,
.resume = msb_resume
};
static int __init msb_init(void)
{
int rc = memstick_register_driver(&msb_driver);
if (rc)
pr_err("failed to register memstick driver (error %d)\n", rc);
return rc;
}
static void __exit msb_exit(void)
{
memstick_unregister_driver(&msb_driver);
idr_destroy(&msb_disk_idr);
}
module_init(msb_init);
module_exit(msb_exit);
module_param(cache_flush_timeout, int, S_IRUGO);
MODULE_PARM_DESC(cache_flush_timeout,
"Cache flush timeout in msec (1000 default)");
module_param(debug, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug, "Debug level (0-2)");
module_param(verify_writes, bool, S_IRUGO);
MODULE_PARM_DESC(verify_writes, "Read back and check all data that is written");
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Maxim Levitsky");
MODULE_DESCRIPTION("Sony MemoryStick block device driver");
| 24.539924 | 110 | 0.702493 | [
"geometry"
] |
82eaba5c103a9cb6c64f200832503487cec54c68 | 2,835 | h | C | NGS/IO/Parser/uParser.h | NGS-lib/NGSplusplus | 7fa9fff2453917f24e9e35dab1f04a9be67f7f13 | [
"BSL-1.0"
] | 3 | 2015-11-23T14:24:06.000Z | 2017-11-21T21:04:06.000Z | NGS/IO/Parser/uParser.h | NGS-lib/NGSplusplus | 7fa9fff2453917f24e9e35dab1f04a9be67f7f13 | [
"BSL-1.0"
] | null | null | null | NGS/IO/Parser/uParser.h | NGS-lib/NGSplusplus | 7fa9fff2453917f24e9e35dab1f04a9be67f7f13 | [
"BSL-1.0"
] | null | null | null | // ***************************************************************************
// uParser.h (c) 2013
// Alexei Nordell-Markovits : Sherbrooke University
// Charles Joly Beauparlant : Laval University
//
// This file is part of the NGS++ library.
//
// The NGS++ library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 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 (lgpl-3.0.txt). If not, see <http://www.gnu.org/licenses/>.
// ***************************************************************************
#ifndef IPARSER_H_INCLUDED
#define IPARSER_H_INCLUDED
#include <map>
#include <string>
#include <functional>
#include <memory>
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <fstream>
#include "../uToken.h"
#include "../../uGeneException.h"
#include "uParserBase.h"
#include "../uHeader.h"
namespace NGS {
class uHeader;
class uParser{
public :
uParser(const std::string& filename, const std::string & type, bool header = false);
uParser(std::istream* stream, const std::string & type, bool header = false);
uParser(const std::string& filename, const std::vector<std::string>& fieldsNames, char delimiter = '\t');
uParser(std::istream* stream, const std::vector<std::string>& fieldsNames, char delimiter = '\t');
~uParser();
bool eof() const ;
uToken getNextEntry();
std::string getPreviousRaw(){return m_pParserBase->getPreviousRaw();};
/** \brief Get an unformated version of header (i.e.: a single string containing the whole header)
*/
std::string getUnformatedHeader() const { return m_pParserBase->getUnformatedHeader(); }
/** \brief Get a specific data from header.
*/
std::string getHeaderParam(header_param name) const { return m_pParserBase->getHeaderParam(name); }
std::vector<std::string> getHeaderParamVector(header_param name) const { return m_pParserBase->getHeaderParamVector(name); }
/** \brief Check if there is a value associated with a given param.
* \param header_param& name: name of the param to check.
*/
bool isHeaderParamSet(const header_param& name) const { return m_pParserBase->isHeaderParamSet(name); }
private:
std::shared_ptr<uParserBase> m_pParserBase=nullptr;
// static uParserBaseFactory myFact;
};
}
#endif
| 38.310811 | 128 | 0.670547 | [
"vector"
] |
82eec89cd18d2ef18f1b03fb94b48809c8a385e6 | 814 | h | C | lldb/tools/lldb-vscode/FunctionBreakpoint.h | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 2,338 | 2018-06-19T17:34:51.000Z | 2022-03-31T11:00:37.000Z | lldb/tools/lldb-vscode/FunctionBreakpoint.h | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 3,740 | 2019-01-23T15:36:48.000Z | 2022-03-31T22:01:13.000Z | lldb/tools/lldb-vscode/FunctionBreakpoint.h | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 500 | 2019-01-23T07:49:22.000Z | 2022-03-30T02:59:37.000Z | //===-- FunctionBreakpoint.h ------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef LLDB_TOOLS_LLDB_VSCODE_FUNCTIONBREAKPOINT_H
#define LLDB_TOOLS_LLDB_VSCODE_FUNCTIONBREAKPOINT_H
#include "BreakpointBase.h"
namespace lldb_vscode {
struct FunctionBreakpoint : public BreakpointBase {
std::string functionName;
FunctionBreakpoint() = default;
FunctionBreakpoint(const llvm::json::Object &obj);
// Set this breakpoint in LLDB as a new breakpoint
void SetBreakpoint();
};
} // namespace lldb_vscode
#endif
| 28.068966 | 80 | 0.644963 | [
"object"
] |
82f8f21493b9736d03cbad62725fe75b0432c5e5 | 1,452 | h | C | SuperDBCore/SuperDBCore/FSExecutor.h | SinnerSchraderMobileMirrors/superdb | b43fed90c33c34635366828e1d2f250ffd774b5f | [
"Unlicense"
] | 215 | 2015-01-07T11:10:30.000Z | 2021-03-09T01:21:24.000Z | SuperDBCore/SuperDBCore/FSExecutor.h | atelierdumobile/superdb | 603bf3b292cbf0b7f25ad1e459f162f851383604 | [
"Unlicense"
] | 3 | 2015-02-10T10:18:05.000Z | 2018-08-14T05:25:20.000Z | SuperDBCore/SuperDBCore/FSExecutor.h | atelierdumobile/superdb | 603bf3b292cbf0b7f25ad1e459f162f851383604 | [
"Unlicense"
] | 30 | 2015-01-06T15:14:04.000Z | 2019-09-26T18:43:55.000Z | /* Executor.h Copyright (c) 1998-2009 Philippe Mougin. */
/* This software is open source. See the license. */
#import <objc/objc.h>
#import "FSArray.h"
@class Space;
@class FSCompiler;
@class FSSymbolTable;
@class FSInterpreter;
@class FSInterpreterResult;
@interface FSExecutor:NSObject <NSCoding>
{
FSInterpreter *interpreter;
// WARNING: No retain done on this pointer, in order to avoid a cycle.
// I add this ivar in order for a FSSystem object to be able to implement the object browser opening.
BOOL should_journal;
NSInteger verboseLevel;
NSFileHandle *journal;
NSString *journalName;
FSSymbolTable *localSymbolTable;
FSCompiler *compiler;
}
- (FSArray *) allDefinedSymbols;
- (void)breakCycles;
- (FSInterpreterResult *)execute:(NSString *)command;
- initWithInterpreter:(FSInterpreter *)theInterpreter;
- (void)installFlightTutorial;
- (FSInterpreter *)interpreter; // Will return nil if the associated interpreter no longer exists
- (void)interpreterIsDeallocating;
- (id)objectForSymbol:(NSString *)symbol found:(BOOL *)found; // found may be passed as NULL
- (BOOL)setJournalName:(NSString *)filename;
- (void)setShouldJournal:(BOOL)shouldJournal;
- (void)setObject:(id)object forSymbol:(NSString *)symbol;
- (void)setVerboseLevel:(NSInteger)theVerboseLevel;
- (BOOL)shouldJournal;
// ULSYSTEM PROTOCOL (informal)
- (void)setSpace:(Space*)space;
- (Space*)space;
- (FSSymbolTable *)symbolTable;
@end
| 30.25 | 103 | 0.749311 | [
"object"
] |
82f971402d85dd62d5bc29e0dd3e4e766380ee5e | 28,671 | c | C | kernel/kernel-4.9/drivers/acpi/acpica/utcopy.c | rubedos/l4t_R32.5.1_viper | 6aed0062084d9031546f946e63fc74303555e0a6 | [
"MIT"
] | 55 | 2019-12-20T03:25:14.000Z | 2022-01-16T07:19:47.000Z | kernel/kernel-4.9/drivers/acpi/acpica/utcopy.c | rubedos/l4t_R32.5.1_viper | 6aed0062084d9031546f946e63fc74303555e0a6 | [
"MIT"
] | 2 | 2020-11-02T08:01:00.000Z | 2022-03-27T02:59:18.000Z | kernel/kernel-4.9/drivers/acpi/acpica/utcopy.c | rubedos/l4t_R32.5.1_viper | 6aed0062084d9031546f946e63fc74303555e0a6 | [
"MIT"
] | 11 | 2020-08-06T03:59:45.000Z | 2022-02-25T02:31:59.000Z | /******************************************************************************
*
* Module Name: utcopy - Internal to external object translation utilities
*
*****************************************************************************/
/*
* Copyright (C) 2000 - 2016, Intel Corp.
* 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,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* NO WARRANTY
* 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 MERCHANTIBILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR 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 DAMAGES.
*/
#include <acpi/acpi.h>
#include "accommon.h"
#include "acnamesp.h"
#define _COMPONENT ACPI_UTILITIES
ACPI_MODULE_NAME("utcopy")
/* Local prototypes */
static acpi_status
acpi_ut_copy_isimple_to_esimple(union acpi_operand_object *internal_object,
union acpi_object *external_object,
u8 *data_space, acpi_size *buffer_space_used);
static acpi_status
acpi_ut_copy_ielement_to_ielement(u8 object_type,
union acpi_operand_object *source_object,
union acpi_generic_state *state,
void *context);
static acpi_status
acpi_ut_copy_ipackage_to_epackage(union acpi_operand_object *internal_object,
u8 *buffer, acpi_size *space_used);
static acpi_status
acpi_ut_copy_esimple_to_isimple(union acpi_object *user_obj,
union acpi_operand_object **return_obj);
static acpi_status
acpi_ut_copy_epackage_to_ipackage(union acpi_object *external_object,
union acpi_operand_object **internal_object);
static acpi_status
acpi_ut_copy_simple_object(union acpi_operand_object *source_desc,
union acpi_operand_object *dest_desc);
static acpi_status
acpi_ut_copy_ielement_to_eelement(u8 object_type,
union acpi_operand_object *source_object,
union acpi_generic_state *state,
void *context);
static acpi_status
acpi_ut_copy_ipackage_to_ipackage(union acpi_operand_object *source_obj,
union acpi_operand_object *dest_obj,
struct acpi_walk_state *walk_state);
/*******************************************************************************
*
* FUNCTION: acpi_ut_copy_isimple_to_esimple
*
* PARAMETERS: internal_object - Source object to be copied
* external_object - Where to return the copied object
* data_space - Where object data is returned (such as
* buffer and string data)
* buffer_space_used - Length of data_space that was used
*
* RETURN: Status
*
* DESCRIPTION: This function is called to copy a simple internal object to
* an external object.
*
* The data_space buffer is assumed to have sufficient space for
* the object.
*
******************************************************************************/
static acpi_status
acpi_ut_copy_isimple_to_esimple(union acpi_operand_object *internal_object,
union acpi_object *external_object,
u8 *data_space, acpi_size *buffer_space_used)
{
acpi_status status = AE_OK;
ACPI_FUNCTION_TRACE(ut_copy_isimple_to_esimple);
*buffer_space_used = 0;
/*
* Check for NULL object case (could be an uninitialized
* package element)
*/
if (!internal_object) {
return_ACPI_STATUS(AE_OK);
}
/* Always clear the external object */
memset(external_object, 0, sizeof(union acpi_object));
/*
* In general, the external object will be the same type as
* the internal object
*/
external_object->type = internal_object->common.type;
/* However, only a limited number of external types are supported */
switch (internal_object->common.type) {
case ACPI_TYPE_STRING:
external_object->string.pointer = (char *)data_space;
external_object->string.length = internal_object->string.length;
*buffer_space_used = ACPI_ROUND_UP_TO_NATIVE_WORD((acpi_size)
internal_object->
string.
length + 1);
memcpy((void *)data_space,
(void *)internal_object->string.pointer,
(acpi_size)internal_object->string.length + 1);
break;
case ACPI_TYPE_BUFFER:
external_object->buffer.pointer = data_space;
external_object->buffer.length = internal_object->buffer.length;
*buffer_space_used =
ACPI_ROUND_UP_TO_NATIVE_WORD(internal_object->string.
length);
memcpy((void *)data_space,
(void *)internal_object->buffer.pointer,
internal_object->buffer.length);
break;
case ACPI_TYPE_INTEGER:
external_object->integer.value = internal_object->integer.value;
break;
case ACPI_TYPE_LOCAL_REFERENCE:
/* This is an object reference. */
switch (internal_object->reference.class) {
case ACPI_REFCLASS_NAME:
/*
* For namepath, return the object handle ("reference")
* We are referring to the namespace node
*/
external_object->reference.handle =
internal_object->reference.node;
external_object->reference.actual_type =
acpi_ns_get_type(internal_object->reference.node);
break;
default:
/* All other reference types are unsupported */
return_ACPI_STATUS(AE_TYPE);
}
break;
case ACPI_TYPE_PROCESSOR:
external_object->processor.proc_id =
internal_object->processor.proc_id;
external_object->processor.pblk_address =
internal_object->processor.address;
external_object->processor.pblk_length =
internal_object->processor.length;
break;
case ACPI_TYPE_POWER:
external_object->power_resource.system_level =
internal_object->power_resource.system_level;
external_object->power_resource.resource_order =
internal_object->power_resource.resource_order;
break;
default:
/*
* There is no corresponding external object type
*/
ACPI_ERROR((AE_INFO,
"Unsupported object type, cannot convert to external object: %s",
acpi_ut_get_type_name(internal_object->common.
type)));
return_ACPI_STATUS(AE_SUPPORT);
}
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_copy_ielement_to_eelement
*
* PARAMETERS: acpi_pkg_callback
*
* RETURN: Status
*
* DESCRIPTION: Copy one package element to another package element
*
******************************************************************************/
static acpi_status
acpi_ut_copy_ielement_to_eelement(u8 object_type,
union acpi_operand_object *source_object,
union acpi_generic_state *state,
void *context)
{
acpi_status status = AE_OK;
struct acpi_pkg_info *info = (struct acpi_pkg_info *)context;
acpi_size object_space;
u32 this_index;
union acpi_object *target_object;
ACPI_FUNCTION_ENTRY();
this_index = state->pkg.index;
target_object = (union acpi_object *)&((union acpi_object *)
(state->pkg.dest_object))->
package.elements[this_index];
switch (object_type) {
case ACPI_COPY_TYPE_SIMPLE:
/*
* This is a simple or null object
*/
status = acpi_ut_copy_isimple_to_esimple(source_object,
target_object,
info->free_space,
&object_space);
if (ACPI_FAILURE(status)) {
return (status);
}
break;
case ACPI_COPY_TYPE_PACKAGE:
/*
* Build the package object
*/
target_object->type = ACPI_TYPE_PACKAGE;
target_object->package.count = source_object->package.count;
target_object->package.elements =
ACPI_CAST_PTR(union acpi_object, info->free_space);
/*
* Pass the new package object back to the package walk routine
*/
state->pkg.this_target_obj = target_object;
/*
* Save space for the array of objects (Package elements)
* update the buffer length counter
*/
object_space = ACPI_ROUND_UP_TO_NATIVE_WORD((acpi_size)
target_object->
package.count *
sizeof(union
acpi_object));
break;
default:
return (AE_BAD_PARAMETER);
}
info->free_space += object_space;
info->length += object_space;
return (status);
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_copy_ipackage_to_epackage
*
* PARAMETERS: internal_object - Pointer to the object we are returning
* buffer - Where the object is returned
* space_used - Where the object length is returned
*
* RETURN: Status
*
* DESCRIPTION: This function is called to place a package object in a user
* buffer. A package object by definition contains other objects.
*
* The buffer is assumed to have sufficient space for the object.
* The caller must have verified the buffer length needed using
* the acpi_ut_get_object_size function before calling this function.
*
******************************************************************************/
static acpi_status
acpi_ut_copy_ipackage_to_epackage(union acpi_operand_object *internal_object,
u8 *buffer, acpi_size *space_used)
{
union acpi_object *external_object;
acpi_status status;
struct acpi_pkg_info info;
ACPI_FUNCTION_TRACE(ut_copy_ipackage_to_epackage);
/*
* First package at head of the buffer
*/
external_object = ACPI_CAST_PTR(union acpi_object, buffer);
/*
* Free space begins right after the first package
*/
info.length = ACPI_ROUND_UP_TO_NATIVE_WORD(sizeof(union acpi_object));
info.free_space = buffer +
ACPI_ROUND_UP_TO_NATIVE_WORD(sizeof(union acpi_object));
info.object_space = 0;
info.num_packages = 1;
external_object->type = internal_object->common.type;
external_object->package.count = internal_object->package.count;
external_object->package.elements =
ACPI_CAST_PTR(union acpi_object, info.free_space);
/*
* Leave room for an array of ACPI_OBJECTS in the buffer
* and move the free space past it
*/
info.length += (acpi_size)external_object->package.count *
ACPI_ROUND_UP_TO_NATIVE_WORD(sizeof(union acpi_object));
info.free_space += external_object->package.count *
ACPI_ROUND_UP_TO_NATIVE_WORD(sizeof(union acpi_object));
status = acpi_ut_walk_package_tree(internal_object, external_object,
acpi_ut_copy_ielement_to_eelement,
&info);
*space_used = info.length;
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_copy_iobject_to_eobject
*
* PARAMETERS: internal_object - The internal object to be converted
* ret_buffer - Where the object is returned
*
* RETURN: Status
*
* DESCRIPTION: This function is called to build an API object to be returned
* to the caller.
*
******************************************************************************/
acpi_status
acpi_ut_copy_iobject_to_eobject(union acpi_operand_object *internal_object,
struct acpi_buffer *ret_buffer)
{
acpi_status status;
ACPI_FUNCTION_TRACE(ut_copy_iobject_to_eobject);
if (internal_object->common.type == ACPI_TYPE_PACKAGE) {
/*
* Package object: Copy all subobjects (including
* nested packages)
*/
status = acpi_ut_copy_ipackage_to_epackage(internal_object,
ret_buffer->pointer,
&ret_buffer->length);
} else {
/*
* Build a simple object (no nested objects)
*/
status = acpi_ut_copy_isimple_to_esimple(internal_object,
ACPI_CAST_PTR(union
acpi_object,
ret_buffer->
pointer),
ACPI_ADD_PTR(u8,
ret_buffer->
pointer,
ACPI_ROUND_UP_TO_NATIVE_WORD
(sizeof
(union
acpi_object))),
&ret_buffer->length);
/*
* build simple does not include the object size in the length
* so we add it in here
*/
ret_buffer->length += sizeof(union acpi_object);
}
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_copy_esimple_to_isimple
*
* PARAMETERS: external_object - The external object to be converted
* ret_internal_object - Where the internal object is returned
*
* RETURN: Status
*
* DESCRIPTION: This function copies an external object to an internal one.
* NOTE: Pointers can be copied, we don't need to copy data.
* (The pointers have to be valid in our address space no matter
* what we do with them!)
*
******************************************************************************/
static acpi_status
acpi_ut_copy_esimple_to_isimple(union acpi_object *external_object,
union acpi_operand_object **ret_internal_object)
{
union acpi_operand_object *internal_object;
ACPI_FUNCTION_TRACE(ut_copy_esimple_to_isimple);
/*
* Simple types supported are: String, Buffer, Integer
*/
switch (external_object->type) {
case ACPI_TYPE_STRING:
case ACPI_TYPE_BUFFER:
case ACPI_TYPE_INTEGER:
case ACPI_TYPE_LOCAL_REFERENCE:
internal_object = acpi_ut_create_internal_object((u8)
external_object->
type);
if (!internal_object) {
return_ACPI_STATUS(AE_NO_MEMORY);
}
break;
case ACPI_TYPE_ANY: /* This is the case for a NULL object */
*ret_internal_object = NULL;
return_ACPI_STATUS(AE_OK);
default:
/* All other types are not supported */
ACPI_ERROR((AE_INFO,
"Unsupported object type, cannot convert to internal object: %s",
acpi_ut_get_type_name(external_object->type)));
return_ACPI_STATUS(AE_SUPPORT);
}
/* Must COPY string and buffer contents */
switch (external_object->type) {
case ACPI_TYPE_STRING:
internal_object->string.pointer =
ACPI_ALLOCATE_ZEROED((acpi_size)
external_object->string.length + 1);
if (!internal_object->string.pointer) {
goto error_exit;
}
memcpy(internal_object->string.pointer,
external_object->string.pointer,
external_object->string.length);
internal_object->string.length = external_object->string.length;
break;
case ACPI_TYPE_BUFFER:
internal_object->buffer.pointer =
ACPI_ALLOCATE_ZEROED(external_object->buffer.length);
if (!internal_object->buffer.pointer) {
goto error_exit;
}
memcpy(internal_object->buffer.pointer,
external_object->buffer.pointer,
external_object->buffer.length);
internal_object->buffer.length = external_object->buffer.length;
/* Mark buffer data valid */
internal_object->buffer.flags |= AOPOBJ_DATA_VALID;
break;
case ACPI_TYPE_INTEGER:
internal_object->integer.value = external_object->integer.value;
break;
case ACPI_TYPE_LOCAL_REFERENCE:
/* An incoming reference is defined to be a namespace node */
internal_object->reference.class = ACPI_REFCLASS_REFOF;
internal_object->reference.object =
external_object->reference.handle;
break;
default:
/* Other types can't get here */
break;
}
*ret_internal_object = internal_object;
return_ACPI_STATUS(AE_OK);
error_exit:
acpi_ut_remove_reference(internal_object);
return_ACPI_STATUS(AE_NO_MEMORY);
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_copy_epackage_to_ipackage
*
* PARAMETERS: external_object - The external object to be converted
* internal_object - Where the internal object is returned
*
* RETURN: Status
*
* DESCRIPTION: Copy an external package object to an internal package.
* Handles nested packages.
*
******************************************************************************/
static acpi_status
acpi_ut_copy_epackage_to_ipackage(union acpi_object *external_object,
union acpi_operand_object **internal_object)
{
acpi_status status = AE_OK;
union acpi_operand_object *package_object;
union acpi_operand_object **package_elements;
u32 i;
ACPI_FUNCTION_TRACE(ut_copy_epackage_to_ipackage);
/* Create the package object */
package_object =
acpi_ut_create_package_object(external_object->package.count);
if (!package_object) {
return_ACPI_STATUS(AE_NO_MEMORY);
}
package_elements = package_object->package.elements;
/*
* Recursive implementation. Probably ok, since nested external
* packages as parameters should be very rare.
*/
for (i = 0; i < external_object->package.count; i++) {
status =
acpi_ut_copy_eobject_to_iobject(&external_object->package.
elements[i],
&package_elements[i]);
if (ACPI_FAILURE(status)) {
/* Truncate package and delete it */
package_object->package.count = i;
package_elements[i] = NULL;
acpi_ut_remove_reference(package_object);
return_ACPI_STATUS(status);
}
}
/* Mark package data valid */
package_object->package.flags |= AOPOBJ_DATA_VALID;
*internal_object = package_object;
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_copy_eobject_to_iobject
*
* PARAMETERS: external_object - The external object to be converted
* internal_object - Where the internal object is returned
*
* RETURN: Status
*
* DESCRIPTION: Converts an external object to an internal object.
*
******************************************************************************/
acpi_status
acpi_ut_copy_eobject_to_iobject(union acpi_object *external_object,
union acpi_operand_object **internal_object)
{
acpi_status status;
ACPI_FUNCTION_TRACE(ut_copy_eobject_to_iobject);
if (external_object->type == ACPI_TYPE_PACKAGE) {
status =
acpi_ut_copy_epackage_to_ipackage(external_object,
internal_object);
} else {
/*
* Build a simple object (no nested objects)
*/
status = acpi_ut_copy_esimple_to_isimple(external_object,
internal_object);
}
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_copy_simple_object
*
* PARAMETERS: source_desc - The internal object to be copied
* dest_desc - New target object
*
* RETURN: Status
*
* DESCRIPTION: Simple copy of one internal object to another. Reference count
* of the destination object is preserved.
*
******************************************************************************/
static acpi_status
acpi_ut_copy_simple_object(union acpi_operand_object *source_desc,
union acpi_operand_object *dest_desc)
{
u16 reference_count;
union acpi_operand_object *next_object;
acpi_status status;
acpi_size copy_size;
/* Save fields from destination that we don't want to overwrite */
reference_count = dest_desc->common.reference_count;
next_object = dest_desc->common.next_object;
/*
* Copy the entire source object over the destination object.
* Note: Source can be either an operand object or namespace node.
*/
copy_size = sizeof(union acpi_operand_object);
if (ACPI_GET_DESCRIPTOR_TYPE(source_desc) == ACPI_DESC_TYPE_NAMED) {
copy_size = sizeof(struct acpi_namespace_node);
}
memcpy(ACPI_CAST_PTR(char, dest_desc),
ACPI_CAST_PTR(char, source_desc), copy_size);
/* Restore the saved fields */
dest_desc->common.reference_count = reference_count;
dest_desc->common.next_object = next_object;
/* New object is not static, regardless of source */
dest_desc->common.flags &= ~AOPOBJ_STATIC_POINTER;
/* Handle the objects with extra data */
switch (dest_desc->common.type) {
case ACPI_TYPE_BUFFER:
/*
* Allocate and copy the actual buffer if and only if:
* 1) There is a valid buffer pointer
* 2) The buffer has a length > 0
*/
if ((source_desc->buffer.pointer) &&
(source_desc->buffer.length)) {
dest_desc->buffer.pointer =
ACPI_ALLOCATE(source_desc->buffer.length);
if (!dest_desc->buffer.pointer) {
return (AE_NO_MEMORY);
}
/* Copy the actual buffer data */
memcpy(dest_desc->buffer.pointer,
source_desc->buffer.pointer,
source_desc->buffer.length);
}
break;
case ACPI_TYPE_STRING:
/*
* Allocate and copy the actual string if and only if:
* 1) There is a valid string pointer
* (Pointer to a NULL string is allowed)
*/
if (source_desc->string.pointer) {
dest_desc->string.pointer =
ACPI_ALLOCATE((acpi_size)source_desc->string.
length + 1);
if (!dest_desc->string.pointer) {
return (AE_NO_MEMORY);
}
/* Copy the actual string data */
memcpy(dest_desc->string.pointer,
source_desc->string.pointer,
(acpi_size)source_desc->string.length + 1);
}
break;
case ACPI_TYPE_LOCAL_REFERENCE:
/*
* We copied the reference object, so we now must add a reference
* to the object pointed to by the reference
*
* DDBHandle reference (from Load/load_table) is a special reference,
* it does not have a Reference.Object, so does not need to
* increase the reference count
*/
if (source_desc->reference.class == ACPI_REFCLASS_TABLE) {
break;
}
acpi_ut_add_reference(source_desc->reference.object);
break;
case ACPI_TYPE_REGION:
/*
* We copied the Region Handler, so we now must add a reference
*/
if (dest_desc->region.handler) {
acpi_ut_add_reference(dest_desc->region.handler);
}
break;
/*
* For Mutex and Event objects, we cannot simply copy the underlying
* OS object. We must create a new one.
*/
case ACPI_TYPE_MUTEX:
status = acpi_os_create_mutex(&dest_desc->mutex.os_mutex);
if (ACPI_FAILURE(status)) {
return (status);
}
break;
case ACPI_TYPE_EVENT:
status = acpi_os_create_semaphore(ACPI_NO_UNIT_LIMIT, 0,
&dest_desc->event.
os_semaphore);
if (ACPI_FAILURE(status)) {
return (status);
}
break;
default:
/* Nothing to do for other simple objects */
break;
}
return (AE_OK);
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_copy_ielement_to_ielement
*
* PARAMETERS: acpi_pkg_callback
*
* RETURN: Status
*
* DESCRIPTION: Copy one package element to another package element
*
******************************************************************************/
static acpi_status
acpi_ut_copy_ielement_to_ielement(u8 object_type,
union acpi_operand_object *source_object,
union acpi_generic_state *state,
void *context)
{
acpi_status status = AE_OK;
u32 this_index;
union acpi_operand_object **this_target_ptr;
union acpi_operand_object *target_object;
ACPI_FUNCTION_ENTRY();
this_index = state->pkg.index;
this_target_ptr = (union acpi_operand_object **)
&state->pkg.dest_object->package.elements[this_index];
switch (object_type) {
case ACPI_COPY_TYPE_SIMPLE:
/* A null source object indicates a (legal) null package element */
if (source_object) {
/*
* This is a simple object, just copy it
*/
target_object =
acpi_ut_create_internal_object(source_object->
common.type);
if (!target_object) {
return (AE_NO_MEMORY);
}
status =
acpi_ut_copy_simple_object(source_object,
target_object);
if (ACPI_FAILURE(status)) {
goto error_exit;
}
*this_target_ptr = target_object;
} else {
/* Pass through a null element */
*this_target_ptr = NULL;
}
break;
case ACPI_COPY_TYPE_PACKAGE:
/*
* This object is a package - go down another nesting level
* Create and build the package object
*/
target_object =
acpi_ut_create_package_object(source_object->package.count);
if (!target_object) {
return (AE_NO_MEMORY);
}
target_object->common.flags = source_object->common.flags;
/* Pass the new package object back to the package walk routine */
state->pkg.this_target_obj = target_object;
/* Store the object pointer in the parent package object */
*this_target_ptr = target_object;
break;
default:
return (AE_BAD_PARAMETER);
}
return (status);
error_exit:
acpi_ut_remove_reference(target_object);
return (status);
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_copy_ipackage_to_ipackage
*
* PARAMETERS: source_obj - Pointer to the source package object
* dest_obj - Where the internal object is returned
* walk_state - Current Walk state descriptor
*
* RETURN: Status
*
* DESCRIPTION: This function is called to copy an internal package object
* into another internal package object.
*
******************************************************************************/
static acpi_status
acpi_ut_copy_ipackage_to_ipackage(union acpi_operand_object *source_obj,
union acpi_operand_object *dest_obj,
struct acpi_walk_state *walk_state)
{
acpi_status status = AE_OK;
ACPI_FUNCTION_TRACE(ut_copy_ipackage_to_ipackage);
dest_obj->common.type = source_obj->common.type;
dest_obj->common.flags = source_obj->common.flags;
dest_obj->package.count = source_obj->package.count;
/*
* Create the object array and walk the source package tree
*/
dest_obj->package.elements = ACPI_ALLOCATE_ZEROED(((acpi_size)
source_obj->package.
count +
1) * sizeof(void *));
if (!dest_obj->package.elements) {
ACPI_ERROR((AE_INFO, "Package allocation failure"));
return_ACPI_STATUS(AE_NO_MEMORY);
}
/*
* Copy the package element-by-element by walking the package "tree".
* This handles nested packages of arbitrary depth.
*/
status = acpi_ut_walk_package_tree(source_obj, dest_obj,
acpi_ut_copy_ielement_to_ielement,
walk_state);
if (ACPI_FAILURE(status)) {
/* On failure, delete the destination package object */
acpi_ut_remove_reference(dest_obj);
}
return_ACPI_STATUS(status);
}
/*******************************************************************************
*
* FUNCTION: acpi_ut_copy_iobject_to_iobject
*
* PARAMETERS: source_desc - The internal object to be copied
* dest_desc - Where the copied object is returned
* walk_state - Current walk state
*
* RETURN: Status
*
* DESCRIPTION: Copy an internal object to a new internal object
*
******************************************************************************/
acpi_status
acpi_ut_copy_iobject_to_iobject(union acpi_operand_object *source_desc,
union acpi_operand_object **dest_desc,
struct acpi_walk_state *walk_state)
{
acpi_status status = AE_OK;
ACPI_FUNCTION_TRACE(ut_copy_iobject_to_iobject);
/* Create the top level object */
*dest_desc = acpi_ut_create_internal_object(source_desc->common.type);
if (!*dest_desc) {
return_ACPI_STATUS(AE_NO_MEMORY);
}
/* Copy the object and possible subobjects */
if (source_desc->common.type == ACPI_TYPE_PACKAGE) {
status =
acpi_ut_copy_ipackage_to_ipackage(source_desc, *dest_desc,
walk_state);
} else {
status = acpi_ut_copy_simple_object(source_desc, *dest_desc);
}
/* Delete the allocated object if copy failed */
if (ACPI_FAILURE(status)) {
acpi_ut_remove_reference(*dest_desc);
}
return_ACPI_STATUS(status);
}
| 28.35905 | 82 | 0.666597 | [
"object"
] |
82fd8dc1cf73df4e27590da3e91f612f8cec7cb1 | 7,183 | h | C | src/DgString.h | bsthorn/dggridR | 11451bbec18ec111027a3f67268e9d9a5485a634 | [
"MIT"
] | null | null | null | src/DgString.h | bsthorn/dggridR | 11451bbec18ec111027a3f67268e9d9a5485a634 | [
"MIT"
] | null | null | null | src/DgString.h | bsthorn/dggridR | 11451bbec18ec111027a3f67268e9d9a5485a634 | [
"MIT"
] | null | null | null | /*******************************************************************************
Copyright (C) 2021 Kevin Sahr
This file is part of DGGRID.
DGGRID is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
DGGRID is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*******************************************************************************/
////////////////////////////////////////////////////////////////////////////////
//
// DgString.h: DgString class definitions
//
////////////////////////////////////////////////////////////////////////////////
#ifndef DGSTRING_H
#define DGSTRING_H
#include "DgUtil.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <sstream>
#include <string>
using namespace std;
////////////////////////////////////////////////////////////////////////////////
// string comparison operators
inline bool operator== (const string& s1, const string& s2)
{ return (s1.compare(s2) == 0); }
inline bool operator!= (const string& s1, const string& s2)
{ return (s1.compare(s2) != 0); }
inline bool operator< (const string& s1, const string& s2)
{ return (s1.compare(s2) < 0); }
inline bool operator<= (const string& s1, const string& s2)
{ return (s1.compare(s2) <= 0); }
inline bool operator> (const string& s1, const string& s2)
{ return (s1.compare(s2) > 0); }
inline bool operator>= (const string& s1, const string& s2)
{ return (s1.compare(s2) >= 0); }
inline bool operator== (const string& s1, const char* s2)
{ return (s1 == string(s2)); }
inline bool operator!= (const string& s1, const char* s2)
{ return (s1 != string(s2)); }
inline bool operator< (const string& s1, const char* s2)
{ return (s1 < string(s2)); }
inline bool operator<= (const string& s1, const char* s2)
{ return (s1 <= string(s2)); }
inline bool operator> (const string& s1, const char* s2)
{ return (s1 > string(s2)); }
inline bool operator>= (const string& s1, const char* s2)
{ return (s1 >= string(s2)); }
inline bool operator== (const char* s1, const string& s2)
{ return (string(s1) == s2); }
inline bool operator!= (const char* s1, const string& s2)
{ return (string(s1) != s2); }
inline bool operator< (const char* s1, const string& s2)
{ return (string(s1) < s2); }
inline bool operator<= (const char* s1, const string& s2)
{ return (string(s1) <= s2); }
inline bool operator> (const char* s1, const string& s2)
{ return (string(s1) > s2); }
inline bool operator>= (const char* s1, const string& s2)
{ return (string(s1) >= s2); }
////////////////////////////////////////////////////////////////////////////////
inline string toLower (const string& strIn)
{
std::string ret(strIn);
std::transform(ret.begin(), ret.end(), ret.begin(), ::tolower);
return ret;
}
////////////////////////////////////////////////////////////////////////////////
namespace dgg { namespace util {
////////////////////////////////////////////////////////////////////////////////
inline string addCommas (unsigned long long int num)
{
std::stringstream ss;
ss << num;
string s = ss.str();
string newS = "";
if (s.length() <= 3)
newS = s;
else
{
int offset = s.length() % 3; // adjust for different # of digits
for (unsigned int i = 0; i < s.length(); i++)
{
if (i && !(i % 3 - offset))
newS += ",";
newS += s[i];
}
}
return newS;
}
////////////////////////////////////////////////////////////////////////////////
inline string addCommas (long double num, unsigned int precision)
{
unsigned long long int intPart = num;
string newS = addCommas(intPart);
std::stringstream ss;
ss << std::fixed << setprecision(precision) << num;
string s = ss.str();
size_t ptNdx = s.find_first_of('.');
if (ptNdx != string::npos)
newS += s.substr(ptNdx, s.length() - ptNdx);
return newS;
}
/* Strip away trailing and leading \r\n (no perfect forwarding in C++03!): */
inline void trim(std::string& line, const std::string& candidates = "\n\r")
{
// Tail:
size_t pos;
while(std::string::npos != (pos = candidates.find(line[line.size() - 1])))
line.erase(line.size() - 1);
size_t i = 0;
// Shift ahead to the first non-match:
for(; std::string::npos != (pos = candidates.find(line[i])); ++i)
;
line.erase(0, i); // ...and, erase to there.
}
inline void trim(char *line, const std::string& candidates = "\n\r")
{
// Again, this could be made more efficient, when there's a need:
size_t len = std::strlen(line),
pos = 0,
i = 0;
while(std::string::npos != (pos = candidates.find(line[len - 1])))
{
line[len - 1] = 0;
--len;
}
/* Here, we find the first non-candidate character in the string, starting at the head. Then,
we shift the remainder of the string left: */
while(std::string::npos != candidates.find(line[i]))
++i;
// Shift left:
memcpy(static_cast<void *>(line), static_cast<void *>(&line[i]), len - i);
line[len - i] = 0; // add NULL
}
template <class TargetT>
inline static TargetT from_string(const std::string& source)
{
TargetT result;
std::istringstream os(source);
os >> result;
return result;
}
#define GCC_VERSION (__GNUC__ * 10000 \
+ __GNUC_MINOR__ * 100 \
+ __GNUC_PATCHLEVEL__)
// JFW: clean up (gcc specific)
template <>
inline
/* Test for GCC < 4.3.0 */
#if !defined __APPLE__ && !defined __clang__ && GCC_VERSION < 40300
/* Template specializations are not allowed to have their own storage
classes, but older g++ didn't know that. Without this, you'll get
linker errors. */
static
#endif
long long int from_string(const std::string& source)
{
long long int n;
sscanf(source.c_str(), "%lld", &n);
return n;
}
// JFW: clean up (gcc specific)
template <>
inline
#if !defined __APPLE__ && !defined __clang__ && GCC_VERSION < 40300
static
#endif
unsigned long long int from_string(const std::string& source)
{
unsigned long long int n;
sscanf(source.c_str(), "%llu", &n);
return n;
}
template <class SourceT>
static std::string to_string(const SourceT& source)
{
std::ostringstream os;
os << source;
return os.str();
}
// JFW: We should tidy all of this up later:
inline std::string to_string(long double val, const char *formatStr)
{
char buffer[50];
sprintf(buffer, formatStr, val);
return string(buffer);
}
inline std::string to_string(int val, int padWidth)
{
std::ostringstream os;
os << std::setw(padWidth) << std::setfill('0') << val;
return os.str();
}
}} // namespace dgg::util
////////////////////////////////////////////////////////////////////////////////
#endif
| 26.802239 | 94 | 0.575526 | [
"transform"
] |
82fdbfddfa52fb1dcdcd769686a1dfd11e1804ea | 3,531 | h | C | external/webkit/Source/WebKit/chromium/src/WebScrollbarImpl.h | ghsecuritylab/android_platform_sony_nicki | 526381be7808e5202d7865aa10303cb5d249388a | [
"Apache-2.0"
] | 2 | 2017-05-19T08:53:12.000Z | 2017-08-28T11:59:26.000Z | external/webkit/Source/WebKit/chromium/src/WebScrollbarImpl.h | ghsecuritylab/android_platform_sony_nicki | 526381be7808e5202d7865aa10303cb5d249388a | [
"Apache-2.0"
] | 2 | 2017-07-25T09:37:22.000Z | 2017-08-04T07:18:56.000Z | external/webkit/Source/WebKit/chromium/src/WebScrollbarImpl.h | ghsecuritylab/android_platform_sony_nicki | 526381be7808e5202d7865aa10303cb5d249388a | [
"Apache-2.0"
] | 2 | 2017-08-09T09:03:23.000Z | 2020-05-26T09:14:49.000Z | /*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef WebScrollbarImpl_h
#define WebScrollbarImpl_h
#include "ScrollableArea.h"
#include "WebScrollbar.h"
#include <wtf/RefPtr.h>
namespace WebCore {
class Scrollbar;
}
namespace WebKit {
class WebScrollbarImpl : public WebScrollbar,
public WebCore::ScrollableArea {
public:
WebScrollbarImpl(WebScrollbarClient*, Orientation orientation);
~WebScrollbarImpl();
// WebKit::WebScrollbar methods
virtual void setLocation(const WebRect&);
virtual int value() const;
virtual void setValue(int position);
virtual void setDocumentSize(int size);
virtual void scroll(ScrollDirection, ScrollGranularity, float multiplier);
virtual void paint(WebCanvas*, const WebRect&);
virtual bool handleInputEvent(const WebInputEvent&);
// WebCore::ScrollableArea methods
virtual int scrollSize(WebCore::ScrollbarOrientation) const;
virtual int scrollPosition(WebCore::Scrollbar*) const;
virtual void setScrollOffset(const WebCore::IntPoint&);
virtual void invalidateScrollbarRect(WebCore::Scrollbar*, const WebCore::IntRect&);
virtual void invalidateScrollCornerRect(const WebCore::IntRect&);
virtual bool isActive() const;
virtual WebCore::IntRect scrollCornerRect() const { return WebCore::IntRect(); }
virtual bool isScrollCornerVisible() const;
virtual void getTickmarks(Vector<WebCore::IntRect>&) const;
virtual WebCore::Scrollbar* horizontalScrollbar() const;
virtual WebCore::Scrollbar* verticalScrollbar() const;
private:
bool onMouseDown(const WebInputEvent& event);
bool onMouseUp(const WebInputEvent& event);
bool onMouseMove(const WebInputEvent& event);
bool onMouseLeave(const WebInputEvent& event);
bool onMouseWheel(const WebInputEvent& event);
bool onKeyDown(const WebInputEvent& event);
WebScrollbarClient* m_client;
int m_scrollOffset;
RefPtr<WebCore::Scrollbar> m_scrollbar;
};
} // namespace WebKit
#endif
| 39.233333 | 87 | 0.755877 | [
"vector"
] |
82fec65ada3644a6e8ddec9330cb67221c085356 | 3,871 | h | C | Userland/Libraries/LibGUI/TabWidget.h | TheCrott/serenity | 925f21353efaa5304c5d486e6802c4e75e0c4d15 | [
"BSD-2-Clause"
] | 2 | 2022-01-15T00:53:43.000Z | 2022-01-16T22:56:38.000Z | Userland/Libraries/LibGUI/TabWidget.h | TheCrott/serenity | 925f21353efaa5304c5d486e6802c4e75e0c4d15 | [
"BSD-2-Clause"
] | 1 | 2021-08-29T03:48:57.000Z | 2021-09-26T05:14:57.000Z | Userland/Libraries/LibGUI/TabWidget.h | TheCrott/serenity | 925f21353efaa5304c5d486e6802c4e75e0c4d15 | [
"BSD-2-Clause"
] | 1 | 2022-02-09T08:28:12.000Z | 2022-02-09T08:28:12.000Z | /*
* Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <LibGUI/Margins.h>
#include <LibGUI/Widget.h>
namespace GUI {
class TabWidget : public Widget {
C_OBJECT(TabWidget)
public:
enum TabPosition {
Top,
Bottom,
};
virtual ~TabWidget() override;
TabPosition tab_position() const { return m_tab_position; }
void set_tab_position(TabPosition);
Optional<size_t> active_tab_index() const;
Widget* active_widget() { return m_active_widget.ptr(); }
const Widget* active_widget() const { return m_active_widget.ptr(); }
void set_active_widget(Widget*);
void set_tab_index(int);
int bar_height() const { return m_bar_visible ? 21 : 0; }
GUI::Margins const& container_margins() const { return m_container_margins; }
void set_container_margins(GUI::Margins const&);
void add_widget(const StringView&, Widget&);
void remove_widget(Widget&);
template<class T, class... Args>
T& add_tab(const StringView& title, Args&&... args)
{
auto t = T::construct(forward<Args>(args)...);
add_widget(title, *t);
return *t;
}
void remove_tab(Widget& tab) { remove_widget(tab); }
void remove_all_tabs_except(Widget& tab);
void set_tab_title(Widget& tab, const StringView& title);
void set_tab_icon(Widget& tab, const Gfx::Bitmap*);
void activate_next_tab();
void activate_previous_tab();
void set_text_alignment(Gfx::TextAlignment alignment) { m_text_alignment = alignment; }
Gfx::TextAlignment text_alignment() const { return m_text_alignment; }
bool uniform_tabs() const { return m_uniform_tabs; }
void set_uniform_tabs(bool uniform_tabs) { m_uniform_tabs = uniform_tabs; }
int uniform_tab_width() const;
void set_bar_visible(bool bar_visible);
bool is_bar_visible() const { return m_bar_visible; };
void set_close_button_enabled(bool close_button_enabled) { m_close_button_enabled = close_button_enabled; };
Function<void(size_t)> on_tab_count_change;
Function<void(Widget&)> on_change;
Function<void(Widget&)> on_middle_click;
Function<void(Widget&)> on_tab_close_click;
Function<void(Widget&, const ContextMenuEvent&)> on_context_menu_request;
protected:
TabWidget();
virtual void paint_event(PaintEvent&) override;
virtual void child_event(Core::ChildEvent&) override;
virtual void resize_event(ResizeEvent&) override;
virtual void mousedown_event(MouseEvent&) override;
virtual void mouseup_event(MouseEvent&) override;
virtual void mousemove_event(MouseEvent&) override;
virtual void leave_event(Core::Event&) override;
virtual void keydown_event(KeyEvent&) override;
virtual void context_menu_event(ContextMenuEvent&) override;
private:
Gfx::IntRect child_rect_for_size(const Gfx::IntSize&) const;
Gfx::IntRect button_rect(size_t index) const;
Gfx::IntRect close_button_rect(size_t index) const;
Gfx::IntRect bar_rect() const;
Gfx::IntRect container_rect() const;
void update_bar();
void update_focus_policy();
int bar_margin() const { return 2; }
RefPtr<Widget> m_active_widget;
struct TabData {
int width(const Gfx::Font&) const;
String title;
RefPtr<Gfx::Bitmap> icon;
Widget* widget { nullptr };
};
Vector<TabData> m_tabs;
TabPosition m_tab_position { TabPosition::Top };
Optional<size_t> m_hovered_tab_index;
Optional<size_t> m_hovered_close_button_index;
Optional<size_t> m_pressed_close_button_index;
GUI::Margins m_container_margins { 2, 2, 2, 2 };
Gfx::TextAlignment m_text_alignment { Gfx::TextAlignment::Center };
bool m_uniform_tabs { false };
bool m_bar_visible { true };
bool m_close_button_enabled { false };
};
}
| 31.991736 | 112 | 0.708344 | [
"vector"
] |
d201e9d86a7332f2b8863edb0939d372a3eb9a59 | 3,337 | h | C | poincare/include/poincare/fraction_layout.h | VersiraSec/epsilon-cfw | d12b44c6c6668ecc14b60d8dd098ba5c230b1291 | [
"FSFAP"
] | 1,442 | 2017-08-28T19:39:45.000Z | 2022-03-30T00:56:14.000Z | poincare/include/poincare/fraction_layout.h | VersiraSec/epsilon-cfw | d12b44c6c6668ecc14b60d8dd098ba5c230b1291 | [
"FSFAP"
] | 1,321 | 2017-08-28T23:03:10.000Z | 2022-03-31T19:32:17.000Z | poincare/include/poincare/fraction_layout.h | VersiraSec/epsilon-cfw | d12b44c6c6668ecc14b60d8dd098ba5c230b1291 | [
"FSFAP"
] | 421 | 2017-08-28T22:02:39.000Z | 2022-03-28T20:52:21.000Z | #ifndef POINCARE_FRACTION_LAYOUT_NODE_H
#define POINCARE_FRACTION_LAYOUT_NODE_H
#include <poincare/layout_cursor.h>
#include <poincare/layout.h>
namespace Poincare {
class FractionLayoutNode /*final*/ : public LayoutNode {
friend class DerivativeLayoutNode;
public:
using LayoutNode::LayoutNode;
// Layout
Type type() const override { return Type::FractionLayout; }
// LayoutNode
void moveCursorLeft(LayoutCursor * cursor, bool * shouldRecomputeLayout, bool forSelection) override;
void moveCursorRight(LayoutCursor * cursor, bool * shouldRecomputeLayout, bool forSelection) override;
void moveCursorUp(LayoutCursor * cursor, bool * shouldRecomputeLayout, bool equivalentPositionVisited = false, bool forSelection = false) override;
void moveCursorDown(LayoutCursor * cursor, bool * shouldRecomputeLayout, bool equivalentPositionVisited = false, bool forSelection = false) override;
void deleteBeforeCursor(LayoutCursor * cursor) override;
int serialize(char * buffer, int bufferSize, Preferences::PrintFloatMode floatDisplayMode, int numberOfSignificantDigits) const override;
bool isCollapsable(int * numberOfOpenParenthesis, bool goingLeft) const override;
bool shouldCollapseSiblingsOnLeft() const override { return true; }
bool shouldCollapseSiblingsOnRight() const override { return true; }
int leftCollapsingAbsorbingChildIndex() const override { return 0; }
int rightCollapsingAbsorbingChildIndex() const override { return 1; }
void didCollapseSiblings(LayoutCursor * cursor) override;
LayoutNode * layoutToPointWhenInserting(Expression * correspondingExpression) override;
bool canBeOmittedMultiplicationRightFactor() const override { return false; }
/* WARNING: We need to override this function, else 1/2 3/4 would be
* serialized as 1/2**3/4, as the two Fraction layouts think their sibling is
* an omitted multiplication layout factor. We have the same problem with
* 2^3 1/2 being serialized as 2^3**1/2, so must override the Right version
* and not canBeOmittedMultiplicationLeftFactor. */
// TreeNode
size_t size() const override { return sizeof(FractionLayoutNode); }
int numberOfChildren() const override { return 2; }
#if POINCARE_TREE_LOG
void logNodeName(std::ostream & stream) const override {
stream << "FractionLayout";
}
#endif
protected:
// SerializationInterface
bool childNeedsSystemParenthesesAtSerialization(const TreeNode * child) const override { return true; }
// LayoutNode
KDSize computeSize() override;
KDCoordinate computeBaseline() override;
KDPoint positionOfChild(LayoutNode * child) override;
private:
constexpr static KDCoordinate k_fractionLineMargin = 2;
constexpr static KDCoordinate k_fractionLineHeight = 1;
void render(KDContext * ctx, KDPoint p, KDColor expressionColor, KDColor backgroundColor, Layout * selectionStart = nullptr, Layout * selectionEnd = nullptr, KDColor selectionColor = KDColorRed) override;
LayoutNode * numeratorLayout() { return childAtIndex(0); }
LayoutNode * denominatorLayout() { return childAtIndex(1); }
};
class FractionLayout final : public Layout {
public:
static FractionLayout Builder(Layout child0, Layout child1) { return TreeHandle::FixedArityBuilder<FractionLayout, FractionLayoutNode>({child0, child1}); }
FractionLayout() = delete;
};
}
#endif
| 45.094595 | 206 | 0.782739 | [
"render"
] |
d2026756db698081e25db37a8e5820f7e9f7db4a | 1,224 | h | C | blaze/blaze/graph/pattern/in_parallel/parallel_split_unary_fusion_pattern_impl.h | Ru-Xiang/x-deeplearning | 04cc0497150920c64b06bb8c314ef89977a3427a | [
"Apache-2.0"
] | 4,071 | 2018-12-13T04:17:38.000Z | 2022-03-30T03:29:35.000Z | blaze/blaze/graph/pattern/in_parallel/parallel_split_unary_fusion_pattern_impl.h | laozhuang727/x-deeplearning | 781545783a4e2bbbda48fc64318fb2c6d8bbb3cc | [
"Apache-2.0"
] | 359 | 2018-12-21T01:14:57.000Z | 2022-02-15T07:18:02.000Z | blaze/blaze/graph/pattern/in_parallel/parallel_split_unary_fusion_pattern_impl.h | laozhuang727/x-deeplearning | 781545783a4e2bbbda48fc64318fb2c6d8bbb3cc | [
"Apache-2.0"
] | 1,054 | 2018-12-20T09:57:42.000Z | 2022-03-29T07:16:53.000Z | /*
* \file parallel_split_unary_fusion_pattern_impl.h
* \brief The parallel split unary fusion pattern
* Such as: Split->Softmax/Softmax/Softmax/... -> Softmax/Split
*/
#pragma once
#include "blaze/graph/fusion_pattern.h"
namespace blaze {
class ParallelSplitUnaryFusionPatternImpl : public FusionPatternImpl {
public:
virtual void Init() override;
// The pattern is matched.
virtual bool Match(const std::vector<ArgumentHelper*>& args,
const std::vector<Node*>& nodes,
Graph* graph) override;
// Do graph rewrite
virtual void GraphRewrite(const std::vector<ArgumentHelper*>& args,
std::vector<Node*>& nodes,
Graph* graph) override;
protected:
// The unary operator can be fused?
virtual bool UnaryNodeMatch(const ArgumentHelper* arg) = 0;
// The two unary operations can fusion?
virtual bool UnaryNodeMatch(const ArgumentHelper* arg_node0, const ArgumentHelper* arg_node1) = 0;
// Update the fused unary op arg
virtual void UpdateFusedUnaryArg(const ArgumentHelper* arg_node1, OperatorDef* fused_op) = 0;
std::vector<int> candidate_idx_;
int split_node_idx_;
};
} // namespace blaze
| 31.384615 | 100 | 0.689542 | [
"vector"
] |
d203f98ead3c328a56266396df0b3d8fdc8d4dc1 | 759 | h | C | dependencies/panda/Panda3D-1.10.0-x64/include/mayaEggLoader.h | CrankySupertoon01/Toontown-2 | 60893d104528a8e7eb4aced5d0015f22e203466d | [
"MIT"
] | 3 | 2018-03-09T12:07:29.000Z | 2021-02-25T06:50:25.000Z | pandatool/src/mayaegg/mayaEggLoader.h | Sinkay/panda3d | 16bfd3750f726a8831771b81649d18d087917fd5 | [
"PHP-3.01",
"PHP-3.0"
] | 1 | 2018-07-28T20:07:04.000Z | 2018-07-30T18:28:34.000Z | pandatool/src/mayaegg/mayaEggLoader.h | Sinkay/panda3d | 16bfd3750f726a8831771b81649d18d087917fd5 | [
"PHP-3.01",
"PHP-3.0"
] | 2 | 2019-12-02T01:39:10.000Z | 2021-02-13T22:41:00.000Z | // Filename: mayaEggLoader.h
// Created by: jyelon (20jul05)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University. All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license. You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////
#ifndef MAYAEGGLOADER_H
#define MAYAEGGLOADER_H
class EggData;
bool MayaLoadEggData(EggData *data, bool merge, bool model, bool anim, bool respect_normals);
bool MayaLoadEggFile(const char *name, bool merge, bool model, bool anim, bool respect_normals);
#endif
| 30.36 | 96 | 0.610013 | [
"model",
"3d"
] |
d211b5439530e37d1a609950091a2bf856ece96c | 3,437 | c | C | cmds/spells/c/_cloak_of_winds.c | guille-valencia/shadowgate | a5c63b535e50020b58435d6fbb5b4f60d8f25639 | [
"MIT"
] | null | null | null | cmds/spells/c/_cloak_of_winds.c | guille-valencia/shadowgate | a5c63b535e50020b58435d6fbb5b4f60d8f25639 | [
"MIT"
] | null | null | null | cmds/spells/c/_cloak_of_winds.c | guille-valencia/shadowgate | a5c63b535e50020b58435d6fbb5b4f60d8f25639 | [
"MIT"
] | null | null | null | #include <std.h>
#include <priest.h>
inherit SPELL;
int timer, flag, stage, toggle, counter;
void create()
{
::create();
set_spell_name("cloak of winds");
set_spell_level(([ "druid" : 3, "mage" : 3, "ranger" : 3, "oracle" : 3 ]));
set_mystery("wind");
set_domains("air");
set_spell_sphere("abjuration");
set_syntax("cast CLASS cloak of winds");
set_damage_desc("3 / 4 bludgeoning, 2 AC");
set_description("You raise a strong wind and wrap yourself into it. It will push away your enemies and incoming attacks, and will do it with forceful strength.");
set_helpful_spell(1);
traveling_aoe_spell(1);
}
int preSpell()
{
if (caster->query_property("cloak of winds")) {
tell_object(caster, "You are already protected by this spell.");
return 0;
}
return 1;
}
void spell_effect(int prof)
{
int duration;
duration = (ROUND_LENGTH * 6) * clevel;
tell_room(place, "%^WHITE%^%^BOLD%^A cloak of winds surrounds and embraces " + caster->QCN + ".", caster);
tell_object(caster, "%^WHITE%^%^BOLD%^A cloak of winds surrounds and embraces you.");
caster->set_property("cloak of winds", 1);
caster->set_property("spelled", ({ TO }));
caster->set_property("added short", ({ "%^WHITE%^ (%^BOLD%^%^CYAN%^beyond a veil of winds%^RESET%^%^WHITE%^)%^RESET%^" }));
caster->add_ac_bonus(2);
addSpellToCaster();
spell_successful();
execute_attack();
counter = 6 * clevel;
call_out("room_check", ROUND_LENGTH);
}
void room_check()
{
if (!objectp(caster) || !objectp(ENV(caster))) {
dest_effect();
return;
}
prepend_to_combat_cycle(ENV(caster));
call_out("room_check", ROUND_LENGTH * 2);
return;
}
void execute_attack()
{
object* attackers, room;
int i;
if (!flag) {
flag = 1;
::execute_attack();
return;
}
if (!objectp(caster)) {
dest_effect();
return;
}
if (!objectp(ENV(caster))) {
dest_effect();
return;
}
place = ENV(caster);
if (!objectp(place) || counter < 0) {
dest_effect();
return;
}
attackers = caster->query_attackers();
if (sizeof(attackers)) {
define_base_damage(0);
tell_room(place, "%^BOLD%^%^WHITE%^Winds around " + caster->QCN + " forcefully push " + caster->QP + " enemies!", ({ caster, target }));
tell_object(caster, "%^GREEN%^%^The winds around you forcefully push your enemies!");
for (i = 0; i < sizeof(attackers); i++) {
if (!objectp(attackers[i])) {
continue;
}
tell_object(attackers[i], "%^WHITE%^%^BOLD%^You are pushed by the wind around " + caster->QCN + "'s body!");
damage_targ(attackers[i], attackers[i]->return_target_limb(), sdamage * 3 / 4, "bludgeoning");
}
}
prepend_to_combat_cycle(place);
counter--;
}
void dest_effect()
{
remove_call_out("room_check");
if (objectp(caster)) {
tell_room(environment(caster), "%^BOLD%^%^WHITE%^The cloak of winds around " + caster->QCN + " retreats.");
caster->remove_property("cloak of winds");
caster->remove_property_value("added short", ({ "%^WHITE%^ (%^BOLD%^%^CYAN%^beyond a veil of winds%^RESET%^%^WHITE%^)%^RESET%^" }));
caster->add_ac_bonus(-2);
}
::dest_effect();
if (objectp(TO)) {
TO->remove();
}
}
| 27.717742 | 166 | 0.590922 | [
"object"
] |
d212890014ff16481fe3097c71a970d8ef14a013 | 4,724 | h | C | src/scripting/operators/import.h | kliment-olechnovic/voronota | 4e3063aa86b44f1f2e7b088ec9976f3e12047549 | [
"MIT"
] | 9 | 2019-08-23T10:46:18.000Z | 2022-03-11T12:20:27.000Z | src/scripting/operators/import.h | kliment-olechnovic/voronota | 4e3063aa86b44f1f2e7b088ec9976f3e12047549 | [
"MIT"
] | null | null | null | src/scripting/operators/import.h | kliment-olechnovic/voronota | 4e3063aa86b44f1f2e7b088ec9976f3e12047549 | [
"MIT"
] | 3 | 2020-09-17T19:07:47.000Z | 2021-04-29T01:19:38.000Z | #ifndef SCRIPTING_OPERATORS_IMPORT_H_
#define SCRIPTING_OPERATORS_IMPORT_H_
#include "../operators_common.h"
#include "../loading_of_data.h"
namespace voronota
{
namespace scripting
{
namespace operators
{
class Import : public OperatorBase<Import>
{
public:
struct Result : public OperatorResultBase<Result>
{
SummaryOfAtoms atoms_summary;
SummaryOfContacts contacts_summary;
std::string object_name;
void store(HeterogeneousStorage& heterostorage) const
{
VariantSerialization::write(atoms_summary, heterostorage.variant_object.object("atoms_summary"));
heterostorage.summaries_of_atoms["loaded"]=atoms_summary;
if(contacts_summary.number_total>0)
{
VariantSerialization::write(contacts_summary, heterostorage.variant_object.object("contacts_summary"));
heterostorage.summaries_of_contacts["loaded"]=contacts_summary;
}
heterostorage.variant_object.value("object_name")=object_name;
}
};
LoadingOfData::Parameters loading_parameters;
std::string title;
Import()
{
}
void initialize(CommandInput& input, const bool managed)
{
loading_parameters=LoadingOfData::Parameters();
if(!managed)
{
loading_parameters.file=input.get_value_or_first_unused_unnamed_value("file");
}
loading_parameters.format=input.get_value_or_default<std::string>("format", "");
loading_parameters.format_fallback=input.get_value_or_default<std::string>("format-fallback", "pdb");
loading_parameters.forced_include_heteroatoms=input.is_option("include-heteroatoms");
loading_parameters.forced_include_hydrogens=input.is_option("include-hydrogens");
loading_parameters.forced_multimodel_chains=input.is_option("as-assembly");
loading_parameters.include_heteroatoms=input.get_flag("include-heteroatoms");
loading_parameters.include_hydrogens=input.get_flag("include-hydrogens");
loading_parameters.multimodel_chains=input.get_flag("as-assembly");
title=(input.is_option("title") ? input.get_value<std::string>("title") : OperatorsUtilities::get_basename_from_path(loading_parameters.file));
}
void initialize(CommandInput& input)
{
initialize(input, false);
}
void document(CommandDocumentation& doc, const bool managed) const
{
if(!managed)
{
doc.set_option_decription(CDOD("file", CDOD::DATATYPE_STRING, "path to file"));
}
doc.set_option_decription(CDOD("format", CDOD::DATATYPE_STRING, "input file format", ""));
doc.set_option_decription(CDOD("format-fallback", CDOD::DATATYPE_STRING, "input file format fallback", ""));
doc.set_option_decription(CDOD("include-heteroatoms", CDOD::DATATYPE_BOOL, "flag to include heteroatoms"));
doc.set_option_decription(CDOD("include-hydrogens", CDOD::DATATYPE_BOOL, "flag to include hydrogens"));
doc.set_option_decription(CDOD("as-assembly", CDOD::DATATYPE_BOOL, "flag import as a biological assembly"));
doc.set_option_decription(CDOD("title", CDOD::DATATYPE_STRING, "new object title", ""));
}
void document(CommandDocumentation& doc) const
{
document(doc, false);
}
Result run(CongregationOfDataManagers& congregation_of_data_managers) const
{
LoadingOfData::Result loading_result;
LoadingOfData::construct_result(loading_parameters, loading_result);
if(loading_result.atoms.size()<4)
{
throw std::runtime_error(std::string("Less than 4 atoms read."));
}
DataManager* object_new=congregation_of_data_managers.add_object(DataManager(), title);
DataManager& data_manager=*object_new;
data_manager.reset_atoms_by_swapping(loading_result.atoms);
if(!loading_result.contacts.empty())
{
data_manager.reset_contacts_by_swapping(loading_result.contacts);
}
congregation_of_data_managers.set_all_objects_picked(false);
congregation_of_data_managers.set_object_picked(object_new, true);
Result result;
result.atoms_summary=SummaryOfAtoms(data_manager.atoms());
result.contacts_summary=SummaryOfContacts(data_manager.contacts());
result.object_name=congregation_of_data_managers.get_object_attributes(object_new).name;
return result;
}
Result run(DataManager& data_manager) const
{
LoadingOfData::Result loading_result;
LoadingOfData::construct_result(loading_parameters, loading_result);
if(loading_result.atoms.size()<4)
{
throw std::runtime_error(std::string("Less than 4 atoms read."));
}
data_manager.reset_atoms_by_swapping(loading_result.atoms);
if(!loading_result.contacts.empty())
{
data_manager.reset_contacts_by_swapping(loading_result.contacts);
}
Result result;
result.atoms_summary=SummaryOfAtoms(data_manager.atoms());
result.contacts_summary=SummaryOfContacts(data_manager.contacts());
result.object_name=title;
return result;
}
};
}
}
}
#endif /* SCRIPTING_OPERATORS_IMPORT_H_ */
| 31.704698 | 145 | 0.783658 | [
"object"
] |
d214fb8a851f5dc0190a80d6879e6f3d395d118f | 3,680 | h | C | util/ThreadPool.h | prishitakadam/TimberSaw2021 | dbc8e49a62557f2975f49f4e5eaa5757311dd22d | [
"BSD-3-Clause"
] | 1 | 2021-08-21T21:26:00.000Z | 2021-08-21T21:26:00.000Z | util/ThreadPool.h | prishitakadam/TimberSaw2021 | dbc8e49a62557f2975f49f4e5eaa5757311dd22d | [
"BSD-3-Clause"
] | null | null | null | util/ThreadPool.h | prishitakadam/TimberSaw2021 | dbc8e49a62557f2975f49f4e5eaa5757311dd22d | [
"BSD-3-Clause"
] | null | null | null | //
// Created by ruihong on 7/29/21.
//
#ifndef TimberSaw_THREADPOOL_H
#define TimberSaw_THREADPOOL_H
#include <condition_variable>
#include <deque>
#include <mutex>
#include <functional>
#include <vector>
#include <atomic>
#include <port/port_posix.h>
#include <assert.h>
namespace TimberSaw {
class DBImpl;
enum ThreadPoolType{FlushThreadPool, CompactionThreadPool, SubcompactionThreadPool};
struct BGItem {
// void* tag = nullptr;
std::function<void(void* args)> function;
void* args;
// std::function<void()> unschedFunction;
};
struct BGThreadMetadata {
void* db;
void* func_args;
};
class ThreadPool{
public:
std::vector<port::Thread> bgthreads_;
std::deque<BGItem> queue_;
ThreadPoolType Type_;
std::mutex mu_;
std::condition_variable bgsignal_;
int total_threads_limit_;
std::atomic_uint queue_len_ = 0;
bool exit_all_threads_ = false;
bool wait_for_jobs_to_complete_;
void WakeUpAllThreads() { bgsignal_.notify_all();
}
void BGThread() {
bool low_io_priority = false;
while (true) {
// Wait until there is an item that is ready to run
std::unique_lock<std::mutex> lock(mu_);
// Stop waiting if the thread needs to do work or needs to terminate.
while (!exit_all_threads_ && queue_.empty() ) {
bgsignal_.wait(lock);
}
if (exit_all_threads_) { // mechanism to let BG threads exit safely
if (!wait_for_jobs_to_complete_ ||
queue_.empty()) {
break;
}
}
auto func = std::move(queue_.front().function);
void* args = std::move(queue_.front().args);
queue_.pop_front();
queue_len_.store(static_cast<unsigned int>(queue_.size()),
std::memory_order_relaxed);
lock.unlock();
func(args);
}
}
void StartBGThreads() {
// Start background thread if necessary
while ((int)bgthreads_.size() < total_threads_limit_) {
port::Thread p_t(&ThreadPool::BGThread, this);
bgthreads_.push_back(std::move(p_t));
}
}
void Schedule(std::function<void(void* args)>&& func, void* args){
std::lock_guard<std::mutex> lock(mu_);
if (exit_all_threads_) {
return;
}
// printf("schedule a work request!\n");
StartBGThreads();
// Add to priority queue
queue_.push_back(BGItem());
auto& item = queue_.back();
// item.tag = tag;
item.function = std::move(func);
item.args = std::move(args);
queue_len_.store(static_cast<unsigned int>(queue_.size()),
std::memory_order_relaxed);
// if (!HasExcessiveThread()) {
// // Wake up at least one waiting thread.
// bgsignal_.notify_one();
// } else {
// // Need to wake up all threads to make sure the one woken
// // up is not the one to terminate.
// WakeUpAllThreads();
// }
WakeUpAllThreads();
}
void JoinThreads(bool wait_for_jobs_to_complete) {
std::unique_lock<std::mutex> lock(mu_);
assert(!exit_all_threads_);
wait_for_jobs_to_complete_ = wait_for_jobs_to_complete;
exit_all_threads_ = true;
// prevent threads from being recreated right after they're joined, in case
// the user is concurrently submitting jobs.
total_threads_limit_ = 0;
lock.unlock();
bgsignal_.notify_all();
for (auto& th : bgthreads_) {
th.join();
}
bgthreads_.clear();
exit_all_threads_ = false;
wait_for_jobs_to_complete_ = false;
}
void SetBackgroundThreads(int num){
total_threads_limit_ = num;
}
// void Schedule(std::function<void(void* args)>&& schedule, void* args);
};}
#endif // TimberSaw_THREADPOOL_H
| 25.734266 | 84 | 0.647554 | [
"vector"
] |
89c0917f261af26f2e352c5cc73c9ca6d32415d4 | 7,784 | c | C | subsys/net/lib/lwm2m/lwm2m_obj_server.c | maxvankessel/zephyr | 769d91b922b736860244b22e25328d91d9a17657 | [
"Apache-2.0"
] | 3 | 2021-02-20T08:02:28.000Z | 2021-03-19T12:22:44.000Z | subsys/net/lib/lwm2m/lwm2m_obj_server.c | maxvankessel/zephyr | 769d91b922b736860244b22e25328d91d9a17657 | [
"Apache-2.0"
] | 8 | 2020-12-02T14:14:31.000Z | 2021-01-20T13:50:58.000Z | subsys/net/lib/lwm2m/lwm2m_obj_server.c | maxvankessel/zephyr | 769d91b922b736860244b22e25328d91d9a17657 | [
"Apache-2.0"
] | 11 | 2020-12-14T22:12:05.000Z | 2022-03-23T08:43:10.000Z | /*
* Copyright (c) 2017 Linaro Limited
* Copyright (c) 2018-2019 Foundries.io
*
* SPDX-License-Identifier: Apache-2.0
*/
#define LOG_MODULE_NAME net_lwm2m_obj_server
#define LOG_LEVEL CONFIG_LWM2M_LOG_LEVEL
#include <logging/log.h>
LOG_MODULE_REGISTER(LOG_MODULE_NAME);
#include <stdint.h>
#include <init.h>
#include "lwm2m_object.h"
#include "lwm2m_engine.h"
#ifdef CONFIG_LWM2M_RD_CLIENT_SUPPORT
#include "lwm2m_rd_client.h"
#endif
/* Server resource IDs */
#define SERVER_SHORT_SERVER_ID 0
#define SERVER_LIFETIME_ID 1
#define SERVER_DEFAULT_MIN_PERIOD_ID 2
#define SERVER_DEFAULT_MAX_PERIOD_ID 3
#define SERVER_DISABLE_ID 4
#define SERVER_DISABLE_TIMEOUT_ID 5
#define SERVER_STORE_NOTIFY_ID 6
#define SERVER_TRANSPORT_BINDING_ID 7
#define SERVER_REG_UPDATE_TRIGGER_ID 8
#define SERVER_MAX_ID 9
/* Server flags */
#define SERVER_FLAG_DISABLED 1
#define SERVER_FLAG_STORE_NOTIFY 2
#define MAX_INSTANCE_COUNT CONFIG_LWM2M_SERVER_INSTANCE_COUNT
#define TRANSPORT_BINDING_LEN 4
/*
* Calculate resource instances as follows:
* start with SERVER_MAX_ID
* subtract EXEC resources (2)
*/
#define RESOURCE_INSTANCE_COUNT (SERVER_MAX_ID - 2)
/* resource state variables */
static uint16_t server_id[MAX_INSTANCE_COUNT];
static uint32_t lifetime[MAX_INSTANCE_COUNT];
static uint32_t default_min_period[MAX_INSTANCE_COUNT];
static uint32_t default_max_period[MAX_INSTANCE_COUNT];
static uint8_t server_flag_disabled[MAX_INSTANCE_COUNT];
static uint32_t disabled_timeout[MAX_INSTANCE_COUNT];
static uint8_t server_flag_store_notify[MAX_INSTANCE_COUNT];
static char transport_binding[MAX_INSTANCE_COUNT][TRANSPORT_BINDING_LEN];
static struct lwm2m_engine_obj server;
static struct lwm2m_engine_obj_field fields[] = {
/*
* LwM2M TS "E.2 LwM2M Object: LwM2M Server" page 107, describes
* Short Server ID as READ-ONLY, but BOOTSTRAP server will attempt
* to write it, so it needs to be RW
*/
OBJ_FIELD_DATA(SERVER_SHORT_SERVER_ID, RW, U16),
OBJ_FIELD_DATA(SERVER_LIFETIME_ID, RW, U32),
OBJ_FIELD_DATA(SERVER_DEFAULT_MIN_PERIOD_ID, RW_OPT, U32),
OBJ_FIELD_DATA(SERVER_DEFAULT_MAX_PERIOD_ID, RW_OPT, U32),
OBJ_FIELD_EXECUTE_OPT(SERVER_DISABLE_ID),
OBJ_FIELD_DATA(SERVER_DISABLE_TIMEOUT_ID, RW_OPT, U32),
OBJ_FIELD_DATA(SERVER_STORE_NOTIFY_ID, RW, BOOL),
/* Mark Transport Binding is RO but BOOTSTRAP needs to write it */
OBJ_FIELD_DATA(SERVER_TRANSPORT_BINDING_ID, RW, STRING),
OBJ_FIELD_EXECUTE(SERVER_REG_UPDATE_TRIGGER_ID),
};
static struct lwm2m_engine_obj_inst inst[MAX_INSTANCE_COUNT];
static struct lwm2m_engine_res res[MAX_INSTANCE_COUNT][SERVER_MAX_ID];
static struct lwm2m_engine_res_inst
res_inst[MAX_INSTANCE_COUNT][RESOURCE_INSTANCE_COUNT];
static int disable_cb(uint16_t obj_inst_id, uint8_t *args, uint16_t args_len)
{
int i;
LOG_DBG("DISABLE %d", obj_inst_id);
for (i = 0; i < MAX_INSTANCE_COUNT; i++) {
if (inst[i].obj && inst[i].obj_inst_id == obj_inst_id) {
server_flag_disabled[i] = 1U;
return 0;
}
}
return -ENOENT;
}
static int update_trigger_cb(uint16_t obj_inst_id,
uint8_t *args, uint16_t args_len)
{
#ifdef CONFIG_LWM2M_RD_CLIENT_SUPPORT
engine_trigger_update(false);
return 0;
#else
return -EPERM;
#endif
}
static int lifetime_write_cb(uint16_t obj_inst_id, uint16_t res_id,
uint16_t res_inst_id, uint8_t *data,
uint16_t data_len, bool last_block,
size_t total_size)
{
ARG_UNUSED(obj_inst_id);
ARG_UNUSED(res_id);
ARG_UNUSED(res_inst_id);
ARG_UNUSED(data);
ARG_UNUSED(data_len);
ARG_UNUSED(last_block);
ARG_UNUSED(total_size);
#ifdef CONFIG_LWM2M_RD_CLIENT_SUPPORT
engine_trigger_update(false);
return 0;
#else
return -EPERM;
#endif
}
static int32_t server_get_instance_s32(uint16_t obj_inst_id, int32_t *data,
int32_t default_value)
{
int i;
for (i = 0; i < ARRAY_SIZE(inst); i++) {
if (inst[i].obj && inst[i].obj_inst_id == obj_inst_id) {
return data[i];
}
}
return default_value;
}
int32_t lwm2m_server_get_pmin(uint16_t obj_inst_id)
{
return server_get_instance_s32(obj_inst_id, default_min_period,
CONFIG_LWM2M_SERVER_DEFAULT_PMIN);
}
int32_t lwm2m_server_get_pmax(uint16_t obj_inst_id)
{
return server_get_instance_s32(obj_inst_id, default_max_period,
CONFIG_LWM2M_SERVER_DEFAULT_PMAX);
}
int lwm2m_server_short_id_to_inst(uint16_t short_id)
{
int i;
for (i = 0; i < ARRAY_SIZE(inst); i++) {
if (inst[i].obj && server_id[i] == short_id) {
return inst[i].obj_inst_id;
}
}
return -ENOENT;
}
static struct lwm2m_engine_obj_inst *server_create(uint16_t obj_inst_id)
{
int index, i = 0, j = 0;
/* Check that there is no other instance with this ID */
for (index = 0; index < MAX_INSTANCE_COUNT; index++) {
if (inst[index].obj && inst[index].obj_inst_id == obj_inst_id) {
LOG_ERR("Can not create instance - "
"already existing: %u", obj_inst_id);
return NULL;
}
}
for (index = 0; index < MAX_INSTANCE_COUNT; index++) {
if (!inst[index].obj) {
break;
}
}
if (index >= MAX_INSTANCE_COUNT) {
LOG_ERR("Can not create instance - "
"no more room: %u", obj_inst_id);
return NULL;
}
/* Set default values */
server_flag_disabled[index] = 0U;
server_flag_store_notify[index] = 0U;
server_id[index] = index + 1;
lifetime[index] = CONFIG_LWM2M_ENGINE_DEFAULT_LIFETIME;
default_min_period[index] = CONFIG_LWM2M_SERVER_DEFAULT_PMIN;
default_max_period[index] = CONFIG_LWM2M_SERVER_DEFAULT_PMAX;
disabled_timeout[index] = 86400U;
lwm2m_engine_get_binding(transport_binding[index]);
(void)memset(res[index], 0,
sizeof(res[index][0]) * ARRAY_SIZE(res[index]));
init_res_instance(res_inst[index], ARRAY_SIZE(res_inst[index]));
/* initialize instance resource data */
INIT_OBJ_RES_DATA(SERVER_SHORT_SERVER_ID, res[index], i,
res_inst[index], j,
&server_id[index], sizeof(*server_id));
INIT_OBJ_RES(SERVER_LIFETIME_ID, res[index], i, res_inst[index], j,
1U, false, true, &lifetime[index], sizeof(*lifetime),
NULL, NULL, lifetime_write_cb, NULL);
INIT_OBJ_RES_DATA(SERVER_DEFAULT_MIN_PERIOD_ID, res[index], i,
res_inst[index], j,
&default_min_period[index],
sizeof(*default_min_period));
INIT_OBJ_RES_DATA(SERVER_DEFAULT_MAX_PERIOD_ID, res[index], i,
res_inst[index], j,
&default_max_period[index],
sizeof(*default_max_period));
INIT_OBJ_RES_EXECUTE(SERVER_DISABLE_ID, res[index], i, disable_cb);
INIT_OBJ_RES_DATA(SERVER_DISABLE_TIMEOUT_ID, res[index], i,
res_inst[index], j,
&disabled_timeout[index],
sizeof(*disabled_timeout));
INIT_OBJ_RES_DATA(SERVER_STORE_NOTIFY_ID, res[index], i,
res_inst[index], j,
&server_flag_store_notify[index],
sizeof(*server_flag_store_notify));
/* Mark Transport Binding RO as we only support UDP atm */
INIT_OBJ_RES_DATA(SERVER_TRANSPORT_BINDING_ID, res[index], i,
res_inst[index], j,
transport_binding[index], TRANSPORT_BINDING_LEN);
INIT_OBJ_RES_EXECUTE(SERVER_REG_UPDATE_TRIGGER_ID, res[index], i,
update_trigger_cb);
inst[index].resources = res[index];
inst[index].resource_count = i;
LOG_DBG("Create LWM2M server instance: %d", obj_inst_id);
return &inst[index];
}
static int lwm2m_server_init(const struct device *dev)
{
struct lwm2m_engine_obj_inst *obj_inst = NULL;
int ret = 0;
server.obj_id = LWM2M_OBJECT_SERVER_ID;
server.fields = fields;
server.field_count = ARRAY_SIZE(fields);
server.max_instance_count = MAX_INSTANCE_COUNT;
server.create_cb = server_create;
lwm2m_register_obj(&server);
/* auto create the first instance */
ret = lwm2m_create_obj_inst(LWM2M_OBJECT_SERVER_ID, 0, &obj_inst);
if (ret < 0) {
LOG_ERR("Create LWM2M server instance 0 error: %d", ret);
}
return ret;
}
SYS_INIT(lwm2m_server_init, APPLICATION, CONFIG_KERNEL_INIT_PRIORITY_DEFAULT);
| 28.936803 | 78 | 0.759635 | [
"object"
] |
89c14f6eda2c72c9da50ddfa0e91caa7d48d8dba | 4,590 | h | C | ResplendentRestkit/Classes/Category/RKObjectManager+RRKCreateRequestsFromRoutes.h | Resplendent/ResplendentRestkit | 21d8743215722e1e942b2bad7c009014deb72870 | [
"MIT"
] | null | null | null | ResplendentRestkit/Classes/Category/RKObjectManager+RRKCreateRequestsFromRoutes.h | Resplendent/ResplendentRestkit | 21d8743215722e1e942b2bad7c009014deb72870 | [
"MIT"
] | null | null | null | ResplendentRestkit/Classes/Category/RKObjectManager+RRKCreateRequestsFromRoutes.h | Resplendent/ResplendentRestkit | 21d8743215722e1e942b2bad7c009014deb72870 | [
"MIT"
] | 3 | 2015-01-02T22:33:51.000Z | 2018-03-01T22:25:20.000Z | //
// RKObjectManager+RRKCreateRequestsFromRoutes.h
// ResplendentRestkit
//
// Created by Benjamin Maer on 10/3/14.
// Copyright (c) 2014 Resplendent. All rights reserved.
//
#import "RRKBlocks.h"
@import RestKit;
@import CoreData;
@class NSObjectManager;
typedef NS_ENUM(NSInteger, RRKCreateRequestsFromRoutes_RKObjectManager_ImageType) {
RRKCreateRequestsFromRoutes_RKObjectManager_ImageType_JPEG,
RRKCreateRequestsFromRoutes_RKObjectManager_ImageType_PNG
};
/*
These methods unfortunately won't get restkit's routing metadata
*/
@interface RKObjectManager (RRKCreateRequestsFromRoutes)
#pragma mark - Restkit requests
-(nullable RKObjectRequestOperation*)rrk_enqueueRestkitRequestOperationForRoute:(nonnull RKRoute*)route
object:(nullable id)object
parameters:(nullable NSDictionary*)parameters
cancelOldRequests:(BOOL)cancelOldRequests
success:(nullable rrk_rkOperationAndMappingResultBlock)success
failure:(nullable rrk_rkOperationAndErrorBlock)failure;
-(nullable RKObjectRequestOperation*)rrk_enqueueRestkitManagedObjectRequestOperationForRoute:(nonnull RKRoute*)route
object:(nullable NSManagedObject*)object
parameters:(nullable NSDictionary*)parameters
cancelOldRequests:(BOOL)cancelOldRequests
managedObjectContext:(nullable NSManagedObjectContext*)managedObjectContext
success:(nullable rrk_rkOperationAndMappingResultBlock)success
failure:(nullable rrk_rkOperationAndErrorBlock)failure;
//Multipart Form
-(nullable RKObjectRequestOperation*)rrk_enqueueRestkitManagedObjectMultiPartRequestOperationForMethod:(RKRequestMethod)method
path:(nonnull NSString*)path
parameters:(nullable NSDictionary*)parameters
object:(nullable NSManagedObject*)object
formBlock:(nullable rrk_AFRKMultipartFormData_block)formBlock
cancelOldRequests:(BOOL)cancelOldRequests
managedObjectContext:(nullable NSManagedObjectContext*)managedObjectContext
uploadProgressBlock:(nullable rrk_uploadProgressBlock)uploadProgressBlock
success:(nullable rrk_rkOperationAndMappingResultBlock)success
failure:(nullable rrk_rkOperationAndErrorBlock)failure;
-(nullable RKObjectRequestOperation*)rrk_enqueueRestkitManagedObjectMultiPartRequestOperationForMethod:(RKRequestMethod)method
path:(nonnull NSString*)path
parameters:(nullable NSDictionary*)parameters
object:(nullable NSManagedObject*)object
uploadData:(nonnull NSData*)uploadData
name:(nonnull NSString*)name
fileName:(nonnull NSString*)fileName
mimeType:(nonnull NSString*)mimeType
cancelOldRequests:(BOOL)cancelOldRequests
managedObjectContext:(nullable NSManagedObjectContext*)managedObjectContext
uploadProgressBlock:(nullable rrk_uploadProgressBlock)uploadProgressBlock
success:(nullable rrk_rkOperationAndMappingResultBlock)success
failure:(nullable rrk_rkOperationAndErrorBlock)failure;
-(nullable RKObjectRequestOperation*)rrk_enqueueRestkitManagedObjectPNGImageUploadRequestOperationForMethod:(RKRequestMethod)method
path:(nonnull NSString*)path
parameters:(nullable NSDictionary*)parameters
pngImage:(nonnull UIImage*)pngImage
object:(nullable NSManagedObject*)object
cancelOldRequests:(BOOL)cancelOldRequests
managedObjectContext:(nullable NSManagedObjectContext*)managedObjectContext
uploadProgressBlock:(nullable rrk_uploadProgressBlock)uploadProgressBlock
success:(nullable rrk_rkOperationAndMappingResultBlock)success
failure:(nullable rrk_rkOperationAndErrorBlock)failure;
#pragma mark - Image Type
+(nullable NSString*)mimeTypeForImageType:(RRKCreateRequestsFromRoutes_RKObjectManager_ImageType)imageType;
#pragma mark - Add Route and cancel
-(void)rrk_addRouteIfNotAlreadyAdded:(nonnull RKRoute*)route cancelOldRequests:(BOOL)cancelOldRequests;
@end
| 45.9 | 131 | 0.692157 | [
"object"
] |
89c25ba3ff7e0a0560734b01a6bf13020c127c46 | 13,742 | c | C | dds/apps/imu_publisher_vector3int/imu_publisher.c | ros2/tinq-core | e9cca1b1e433495616568ae6ae903322832f7b3b | [
"curl"
] | 2 | 2015-03-31T11:52:22.000Z | 2022-03-14T03:24:11.000Z | dds/apps/imu_publisher_vector3int/imu_publisher.c | ros2/tinq-core | e9cca1b1e433495616568ae6ae903322832f7b3b | [
"curl"
] | null | null | null | dds/apps/imu_publisher_vector3int/imu_publisher.c | ros2/tinq-core | e9cca1b1e433495616568ae6ae903322832f7b3b | [
"curl"
] | null | null | null | /*
* Copyright (c) 2014 - Qeo LLC
*
* The source code form of this Qeo Open Source Project component is subject
* to the terms of the Clear BSD license.
*
* You can redistribute it and/or modify it under the terms of the Clear BSD
* License (http://directory.fsf.org/wiki/License:ClearBSD). See LICENSE file
* for more details.
*
* The Qeo Open Source Project also includes third party Open Source Software.
* See LICENSE file for more details.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <poll.h>
#include "thread.h"
#include "libx.h"
#include "tty.h"
#ifdef DDS_SECURITY
#include "dds/dds_security.h"
#ifdef DDS_NATIVE_SECURITY
#include "nsecplug/nsecplug.h"
#else
#include "msecplug/msecplug.h"
#include "assert.h"
#include "../../plugins/secplug/xmlparse.h"
#endif
#include "../../plugins/security/engine_fs.h"
#endif
#include "dds/dds_aux.h"
#include "dds/dds_debug.h"
#include "dds/dds_dcps.h"
#include "dds/dds_xtypes.h"
#include "dds/dds_dwriter.h"
#include "dds/dds_dreader.h"
#include "vector3_msg.h"
#define WAITSETS /* Set this to use the WaitSet mechanism. */
/*#define TRANSIENT_LOCAL ** Set to use Transient-local Durability. */
/*#define RELIABLE ** Set this for Reliable transfers. */
/*#define KEEP_ALL ** Set this for infinite history. */
#define HISTORY 1 /* # of samples buffered. */
#define DISPLAY_SELF /* Define this to display own messages. */
const char *progname;
char chatroom [64] = "DDS"; /* Chatroom name. */
char user_name [64]; /* User name. */
unsigned domain_id; /* Domain identifier. */
int verbose, aborting;
thread_t rt;
thread_t rt2;
#ifdef DDS_SECURITY
char *engine_id; /* Engine id. */
char *cert_path; /* Certificates path. */
char *key_path; /* Private key path. */
char *realm_name; /* Realm name. */
#endif
DDS_DomainParticipant part;
DDS_DynamicTypeSupport ts;
DDS_Publisher pub;
DDS_Subscriber sub;
DDS_Topic topic;
DDS_TopicDescription td;
DDS_DynamicDataWriter dw;
DDS_DynamicDataReader dr;
void do_dds_shell (DDS_DataWriter dw)
{
Vector3_t m;
DDS_InstanceHandle_t h;
char buf [256];
tty_init ();
DDS_Handle_attach (tty_stdin,
POLLIN | POLLPRI | POLLERR | POLLHUP | POLLNVAL,
tty_input,
NULL);
#if 0
printf ("Welcome to the Technicolor chatroom.\r\n");
printf ("Anything you type will be sent to all chatroom attendees.\r\n");
printf ("Type '!help' for chatroom options.\r\n");
m.chatroom = chatroom;
m.from = user_name;
#endif
h = 0;
while (!aborting) {
tty_gets (sizeof (buf), buf, 0, 1);
if (buf [0] == '!') {
if (!strcmp (buf + 1, "quit") ||
(buf [1] == 'q' && buf [2] == '\0')) {
aborting = 1;
break;
}
else if (!strcmp (buf + 1, "list"))
printf ("Attendees:\r\n\t%s\r\n", user_name);
else if (!memcmp (buf + 1, "user", 4)) {
if (h) {
Vector3_signal (dw, h, 1);
h = 0;
}
strcpy (user_name, buf + 6);
printf ("You are now: %s\r\n", user_name);
}
else if (!strcmp (buf + 1, "busy"))
Vector3_signal (dw, h, 0);
else if (!strcmp (buf + 1, "away")) {
if (h) {
Vector3_signal (dw, h, 1);
h = 0;
}
}
else if (!strcmp (buf + 1, "help") ||
(buf [1] == 'h' && buf [2] == '\0') ||
(buf [1] == '?' && buf [2] == '\0')) {
printf ("Commands:\r\n");
printf (" !list -> list the attendees.\r\n");
printf (" !busy -> momentarily not involved.\r\n");
printf (" !away -> gone away.\r\n");
printf (" !help or !h or !? -> Show this info.\r\n");
printf (" !quit or !q -> Quit the chatroom.\r\n");
printf (" !!<command> -> DDS debug command.\r\n");
/* printf (" !$<command> -> Shell command.\r\n"); */
}
else if (buf [1] == '!')
DDS_Debug_command (buf + 2);
/* else if (buf [1] == '$')
system (buf + 2); */
else
printf ("?%s\r\n", buf + 1);
continue;
} else {
#if 0
if (!h)
h = Vector3_register (dw, &m);
m.message = buf;
Vector3_write (dw, &m, h);
#endif
printf ("Commands:\r\n");
printf (" !list -> list the attendees.\r\n");
printf (" !busy -> momentarily not involved.\r\n");
printf (" !away -> gone away.\r\n");
printf (" !help or !h or !? -> Show this info.\r\n");
printf (" !quit or !q -> Quit the chatroom.\r\n");
printf (" !!<command> -> DDS debug command.\r\n");
}
}
}
static void *dds_send_imu (void *args)
{
Vector3_t m;
DDS_InstanceHandle_t h;
int i = 0;
h = 0;
for (;;){
sleep (1); // sleep 0.5 seconds
//sprintf(buf_t, "Embedded says %s\n", buf);
m.x_ = 1 + i;
m.y_ = 2 + i;
m.z_ = 3 + i;
i++;
#if 0
/* According to https://github.com/brunodebus/tinq-core/issues/7#issuecomment-63740498:
the Vector3 shouldn't be registered if it doesn't contain a @key attribute
*/
if (!h)
h = Vector3_register (dw, &m);
#endif
Vector3_write (dw, &m, h);
}
}
void read_msg (DDS_DataReaderListener *l, DDS_DataReader dr)
{
Vector3_t msg;
DDS_InstanceStateKind kind;
int valid;
DDS_ReturnCode_t ret;
ARG_NOT_USED (l)
memset (&msg, 0, sizeof (msg));
ret = Vector3_read_or_take (dr, &msg, DDS_NOT_READ_SAMPLE_STATE,
DDS_ANY_VIEW_STATE,
DDS_ANY_INSTANCE_STATE, 1,
&valid, &kind);
if (ret == DDS_RETCODE_OK)
do {
#if 0
/*
Use a from field within the message to avoid to read the messages that this
node sent.
*/
#ifndef DISPLAY_SELF
if (!strcmp (msg.from, user_name) &&
!strcmp (msg.chatroom, chatroom))
break;
#endif
#endif
if (valid)
printf ("IMU accel message: x=%d, y=%d and z=%d\r\n", msg.x_, msg.y_, msg.z_);
else if (kind == DDS_NOT_ALIVE_DISPOSED_INSTANCE_STATE)
printf ("DDS_NOT_ALIVE_DISPOSED_INSTANCE_STATE!\r\n");
else if (kind == DDS_NOT_ALIVE_NO_WRITERS_INSTANCE_STATE)
printf ("DDS_NOT_ALIVE_NO_WRITERS_INSTANCE_STATE!\r\n");
}
while (0);
Vector3_cleanup (&msg);
}
#ifdef WAITSETS
static void *imu_reader (void *args)
{
DDS_DynamicDataReader dr;
DDS_WaitSet ws;
DDS_SampleStateMask ss = DDS_NOT_READ_SAMPLE_STATE;
DDS_ViewStateMask vs = DDS_ANY_VIEW_STATE;
DDS_InstanceStateMask is = DDS_ANY_INSTANCE_STATE;
DDS_ReadCondition rc;
DDS_ConditionSeq conds = DDS_SEQ_INITIALIZER (DDS_Condition);
DDS_Duration_t to;
DDS_ReturnCode_t ret;
dr = args;
ws = DDS_WaitSet__alloc ();
if (!ws)
fatal ("Unable to allocate a WaitSet!");
if (verbose)
printf ("DDS Waitset allocated.\r\n");
rc = DDS_DataReader_create_readcondition (dr, ss, vs, is);
if (!rc)
fatal ("DDS_DataReader_create_readcondition () returned an error!");
if (verbose)
printf ("DDS Readcondition created.\r\n");
ret = DDS_WaitSet_attach_condition (ws, rc);
if (ret)
fatal ("Unable to attach condition to a WaitSet!");
while (!aborting) {
to.sec = 0;
to.nanosec = 200000000; /* Timeout after 200ms. */
ret = DDS_WaitSet_wait (ws, &conds, &to);
if (ret == DDS_RETCODE_TIMEOUT)
continue;
read_msg (NULL, dr);
}
ret = DDS_WaitSet_detach_condition (ws, rc);
if (ret)
fatal ("Unable to detach condition from WaitSet (%s)!", DDS_error (ret));
DDS_WaitSet__free (ws);
return (NULL);
}
static void start_imu_reader (DDS_DynamicDataReader dr)
{
thread_create (rt, imu_reader, dr);
}
static void stop_imu_reader (DDS_DynamicDataReader dr)
{
ARG_NOT_USED (dr)
thread_wait (rt, NULL);
}
#else
static DDS_DataReaderListener msg_listener = {
NULL, /* Sample rejected. */
NULL, /* Liveliness changed. */
NULL, /* Requested Deadline missed. */
NULL, /* Requested incompatible QoS. */
read_msg, /* Data available. */
NULL, /* Subscription matched. */
NULL, /* Sample lost. */
NULL /* Cookie */
};
#endif
#ifdef DDS_SECURITY
#define fail_unless assert
static void enable_security (void)
{
DDS_Credentials credentials;
DDS_ReturnCode_t error;
#ifdef MSECPLUG_WITH_SECXML
/*int dhandle, thandle;*/
#endif
error = DDS_SP_set_policy ();
if (error)
fatal ("DDS_SP_set_policy() returned error (%s)!", DDS_error (error));
#ifdef MSECPLUG_WITH_SECXML
if (DDS_SP_parse_xml ("security.xml"))
fatal ("SP: no DDS security rules in 'security.xml'!\r\n");
#else
DDS_SP_add_domain();
if (!realm_name)
DDS_SP_add_participant ();
else
DDS_SP_set_participant_access (DDS_SP_add_participant (), strcat(realm_name, "*"), 2, 0);
#endif
if (!cert_path || !key_path)
fatal ("Error: you must provide a valid certificate path and a valid private key path\r\n");
if (engine_id) {
DDS_SP_init_engine (engine_id, init_engine_fs);
credentials.credentialKind = DDS_ENGINE_BASED;
credentials.info.engine.engine_id = engine_id;
credentials.info.engine.cert_id = cert_path;
credentials.info.engine.priv_key_id = key_path;
}
else {
credentials.credentialKind = DDS_FILE_BASED;
credentials.info.filenames.private_key_file = key_path;
credentials.info.filenames.certificate_chain_file = cert_path;
}
error = DDS_Security_set_credentials ("Technicolor Chatroom", &credentials);
}
static void cleanup_security (void)
{
/* Cleanup security submodule. */
DDS_SP_access_db_cleanup ();
DDS_SP_engine_cleanup ();
/* Cleanup malloc-ed memory. */
if (engine_id)
free (engine_id);
if (cert_path)
free (cert_path);
if (key_path)
free (key_path);
if (realm_name)
free (realm_name);
}
#endif
int main (int argc, const char **argv)
{
DDS_DataWriterQos wr_qos;
DDS_DataReaderQos rd_qos;
DDS_ReturnCode_t error;
sprintf (user_name, ".pid.%u", getpid ());
DDS_entity_name ("Technicolor Chatroom");
#ifdef DDS_SECURITY
if (cert_path || key_path || engine_id)
enable_security ();
#endif
part = DDS_DomainParticipantFactory_create_participant (domain_id, NULL, NULL, 0);
if (!part) {
printf ("Can't create participant!\r\n");
exit (1);
}
if (verbose)
printf ("DDS Domain Participant created.\r\n");
ts = Vector3_type_new ();
if (!ts) {
printf ("Can't create vector3 message type!\r\n");
exit (1);
}
error = DDS_DynamicTypeSupport_register_type (ts, part, "simple_msgs::dds_::Vector3Int_");
if (error) {
printf ("Can't register vector3 message type.\r\n");
exit (1);
}
if (verbose)
printf ("DDS Topic type ('%s') registered.\r\n", "simple_msgs::dds_::Vector3Int_");
topic = DDS_DomainParticipant_create_topic (part, "imu", "simple_msgs::dds_::Vector3Int_", NULL, NULL, 0);
if (!topic) {
printf ("Can't register vector3 message type.\r\n");
exit (1);
}
if (verbose)
printf ("DDS Vector3 Topic created.\r\n");
td = DDS_DomainParticipant_lookup_topicdescription (part, "imu");
if (!td) {
printf ("Can't get topicdescription.\r\n");
exit (1);
}
pub = DDS_DomainParticipant_create_publisher (part, NULL, NULL, 0);
if (!pub) {
printf ("DDS_DomainParticipant_create_publisher () failed!\r\n");
exit (1);
}
DDS_Publisher_get_default_datawriter_qos (pub, &wr_qos);
#ifdef TRANSIENT_LOCAL
wr_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS;
#endif
#ifdef RELIABLE
wr_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS;
#endif
#ifdef KEEP_ALL
wr_qos.history.kind = DDS_KEEP_ALL_HISTORY_QOS;
wr_qos.history.depth = DDS_LENGTH_UNLIMITED;
wr_qos.resource_limits.max_samples_per_instance = HISTORY;
wr_qos.resource_limits.max_instances = HISTORY * 10;
wr_qos.resource_limits.max_samples = HISTORY * 4;
#else
wr_qos.history.kind = DDS_KEEP_LAST_HISTORY_QOS;
wr_qos.history.depth = HISTORY;
#endif
/* Create a Data Writer. */
dw = DDS_Publisher_create_datawriter (pub, topic, &wr_qos, NULL, 0);
if (!dw) {
printf ("Unable to create vector3 message writer.\r\n");
exit (1);
}
if (verbose)
printf ("DDS Vector3 message writer created.\r\n");
sub = DDS_DomainParticipant_create_subscriber (part, NULL, NULL, 0);
if (!sub) {
printf ("DDS_DomainParticipant_create_subscriber () returned an error!\r\n");
exit (1);
}
if (verbose)
printf ("DDS Subscriber created.\r\n");
DDS_Subscriber_get_default_datareader_qos (sub, &rd_qos);
#ifdef TRANSIENT_LOCAL
rd_qos.durability.kind = DDS_TRANSIENT_LOCAL_DURABILITY_QOS;
#endif
#ifdef RELIABLE
rd_qos.reliability.kind = DDS_RELIABLE_RELIABILITY_QOS;
#endif
#ifdef KEEP_ALL
rd_qos.history.kind = DDS_KEEP_ALL_HISTORY_QOS;
rd_qos.history.depth = DDS_LENGTH_UNLIMITED;
rd_qos.resource_limits.max_samples_per_instance = HISTORY;
rd_qos.resource_limits.max_instances = HISTORY * 10;
rd_qos.resource_limits.max_samples = HISTORY * 4;
#else
rd_qos.history.kind = DDS_KEEP_LAST_HISTORY_QOS;
rd_qos.history.depth = HISTORY;
#endif
dr = DDS_Subscriber_create_datareader (sub, td, &rd_qos,
#ifndef WAITSETS
&msg_listener, DDS_DATA_AVAILABLE_STATUS);
#else
NULL, 0);
#endif
if (!dr) {
printf ("DDS_DomainParticipant_create_datareader () returned an error!\r\n");
exit (1);
}
if (verbose)
printf ("DDS Vector message reader created.\r\n");
#ifdef WAITSETS
start_imu_reader (dr);
#endif
// publisher thread
thread_create (rt2, dds_send_imu, dr);
// DDS Debug shell thread
do_dds_shell (dw);
#ifdef WAITSETS
stop_imu_reader (dr);
#endif
DDS_Publisher_delete_datawriter (pub, dw);
usleep (200000);
error = DDS_DomainParticipant_delete_contained_entities (part);
if (verbose)
printf ("DDS Entities deleted (error = %u).\r\n", error);
Vector3_type_free (ts);
if (verbose)
printf ("Vector3 Type deleted.\r\n");
error = DDS_DomainParticipantFactory_delete_participant (part);
if (verbose)
printf ("DDS Participant deleted (error = %u).\r\n", error);
#ifdef DDS_SECURITY
if (cert_path || key_path || engine_id)
cleanup_security ();
#endif
return (0);
}
| 26.735409 | 107 | 0.67079 | [
"vector"
] |
89c4a56a433f56f4a4ac7d780d1647ff20f9a49a | 9,217 | h | C | gtk_win.h | aokellermann/tick | 65ce376640ab357dcadb5a2eb7c86ad67906b0e1 | [
"MIT"
] | 6 | 2018-04-28T07:41:49.000Z | 2021-12-16T03:56:47.000Z | gtk_win.h | aokellermann/tick | 65ce376640ab357dcadb5a2eb7c86ad67906b0e1 | [
"MIT"
] | 3 | 2018-02-08T17:03:19.000Z | 2018-08-04T06:25:01.000Z | gtk_win.h | aokellermann/tick | 65ce376640ab357dcadb5a2eb7c86ad67906b0e1 | [
"MIT"
] | 1 | 2020-09-10T17:36:51.000Z | 2020-09-10T17:36:51.000Z | #ifndef TICK_GTK_WIN_H
#define TICK_GTK_WIN_H
#include <gtk/gtk.h>
#include "portfolio.h"
#define GET_OBJECT(obj) gtk_builder_get_object(app.builder, obj)
#define PEER_COLUMN_SYMBOL 0
#define PEER_COLUMN_PROFIT_24H_PERCENT 1
#define PEER_COLUMN_PROFIT_7D_PERCENT 2
#define PEER_COLUMN_PROFIT_30D_PERCENT 3
#define INFO_ARRAY_CACHE_MAX 128
typedef enum column_index {
AMOUNT, LABEL, VALUE, SPENT, PROFIT, PROFIT_PERCENT, PROFIT_24H, PROFIT_24H_PERCENT, PROFIT_7D,
PROFIT_7D_PERCENT, PROFIT_30D, PROFIT_30D_PERCENT, NUM_COLS
} Col_Index;
typedef enum zoom_level_total_months {
FIVE_Y, FOUR_Y, THREE_Y, TWO_Y, ONE_Y, SIX_M, THREE_M, ONE_M, FOURTEEN_D, SEVEN_D
} Zoom_Months;
typedef struct app_data {
Info_Array* portfolio_data;
String* portfolio_string;
GtkBuilder* builder;
Info_Array* info_cache;
char password[PASS_MAX];
time_t last_reload;
Info* focused;
} App_Data;
/**
* Initializes gtk, loads glade file, connects signals, shows the check window, and enters the
* main gtk loop.
*/
void window_main(void);
/**
* Precondition: app.portfolio_string is a String containing a JSON array of portfolio data
*
* If the JSON array is length 0, the function will do nothing.
*
* Otherwise, app.portfolio_data will be created from app.portfolio_string and the check list store
* will be cleared and appended with this data.
*/
void check_list_create_from_string(void);
/**
* Precondition: check_list_create_from_string has already been called and api data has been
* stored in app.portfolio_data
*
* Api data from app.portfolio_data will be stored in the check list store
*/
void check_list_add_api_data(void);
/**
* SIGNAL FOR LOAD BUTTON CLICK
*
* Loads the portfolio file, decrypts if necessary, collects api data, and adds all the data to
* the check list store.
* @param button UNUSED -- MAY BE NULL
*/
void on_load_button_clicked(GtkButton* button);
/**
* SIGNAL FOR LOAD BUTTON CLICK
*
* Shows either the encrypt or decrypt dialog depending on the button's label.
* @param button a GtkButton with either label "Encrypt" or "Decrypt"
*/
void on_lock_button_clicked(GtkButton* button);
/**
* SIGNAL FOR SET PASSWORD DIALOG RESPONSE
*
* If response is GTK_RESPONSE_CANCEL (if click cancel or press escape), hide the dialog.
* Otherwise, calls on_set_password_entry_activate.
* @param dialog
* @param response_id response of button activated -- either GTK_RESPONSE_CANCEL or GTK_RESPONSE_OK
*/
void on_set_password_dialog_response(GtkDialog* dialog, gint response_id);
/**
* SIGNAL FOR SET PASSWORD ENTRY ACTIVATE
*
* Activated by keypress ENTER.
*
* If the length of the entered password is not between 6 and 30 characters or the two entered
* passwords are not the same, the password will not be set.
* @param entry UNUSED -- MAY BE NULL
*/
void on_set_password_entry_activate(GtkEntry* entry);
/**
* SIGNAL FOR DECRYPT DIALOG RESPONSE
*
* If response is GTK_RESPONSE_CANCEL (if click cancel or press escape), hide the dialog.
* Otherwise, calls on_decrypt_password_entry_activate.
* @param dialog
* @param response_id response of button activated -- either GTK_RESPONSE_CANCEL or GTK_RESPONSE_OK
*/
void on_decrypt_dialog_response(GtkDialog* dialog, gint response_id);
/**
* SIGNAL FOR DECRYPT PASSWORD ENTRY ACTIVATE
*
* If the entered password matches app.password, app.password will be cleared.
* @param entry UNUSED -- MAY BE NULL
*/
void on_decrypt_password_entry_activate(GtkEntry* entry);
/**
* SIGNAL FOR ADD, REMOVE, AND SET BUTTON CLICK
*
* Opens portfolio_modify_dialog based on which button was clicked.
* @param button the button clicked
*/
void on_modify_button_clicked(GtkButton* button);
/**
* SIGNAL FOR MODIFY ENTRY ACTIVATE
*
* Modifies app.portfolio_string according to the values entered in portfolio_modify_dialog
* @param entry UNUSED -- MAY BE NULL
*/
void on_modify_entry_activate(GtkEntry* entry);
/**
* SIGNAL FOR PORTFOLIO MODIFY DIALOG RESPONSE
*
* If response is GTK_RESPONSE_CANCEL (if click cancel or press escape), hide the dialog.
* Otherwise, calls on_modify_entry_activate.
* @param dialog
* @param response_id response of button activated -- either GTK_RESPONSE_CANCEL or GTK_RESPONSE_OK
*/
void on_portfolio_modify_dialog_response(GtkDialog* dialog, gint response_id);
/**
* SIGNAL FOR PASSWORD ENTRY ACTIVATE
*
* If the entered password is correct, copy the password to app.password and load the portfolio
* @param entry UNUSED -- MAY BE NULL
*/
void on_password_entry_activate(GtkEntry* entry);
/**
* SIGNAL FOR GET PASSWORD DIALOG RESPONSE
*
* If response is GTK_RESPONSE_CANCEL (if click cancel or press escape), hide the dialog.
* Otherwise, calls on_password_entry_activate.
* @param dialog
* @param response_id response of button activated -- either GTK_RESPONSE_CANCEL or GTK_RESPONSE_OK
*/
void on_get_password_dialog_response(GtkDialog* dialog, gint response_id);
/**
* SIGNAL FOR KEY ENTRY ACTIVATE
*
* If the entered key is not empty, sets the api key with the given provider and key.
* @param entry UNUSED -- MAY BE NULL
*/
void on_key_entry_activate(GtkEntry* entry);
/**
* SIGNAL FOR SET KEY DIALOG RESPONSE
*
* If response is GTK_RESPONSE_CANCEL (if click cancel or press escape), hide the dialog.
* Otherwise, calls on_key_entry_activate.
* @param dialog
* @param response_id response of button activated -- either GTK_RESPONSE_CANCEL or GTK_RESPONSE_OK
*/
void on_set_key_dialog_response(GtkDialog* dialog, gint response_id);
/**
* SIGNAL FOR CHECK WINDOW DESTROY
*
* Encrypts and writes the portfolio to file if necessary. Unrefs gtk builder and exits main gtk
* loop. Destroys all memory in app.
*/
void on_check_window_destroy(void);
/**
* SIGNAL FOR COLUMN CLICKED
*
* Sorts the ListStore struct according to which column was clicked.
* @param column clicked column
* @param list_store portfolio data list
*/
void on_column_clicked(GtkTreeViewColumn* column, GtkListStore* list_store);
/**
* SIGNAL FOR CHECK TREE VIEW ACTIVATE
*
* Shows info for the security in the column activated.
* @param tree_view GtkTreeView*
* @param path GtkTreePath*
* @param column GtkTreeViewColumn*
*/
void on_check_tree_view_row_activated(GtkTreeView* tree_view, GtkTreePath* path,
GtkTreeViewColumn* column);
/**
* SIGNAL FOR BACK BUTTON CLICKED
*
* Returns to the portfolio view.
* @param button
*/
void on_info_back_button_clicked(GtkButton* button);
/**
* SIGNAL FOR SEARCH ENTRY FOCUS
*
* On first time focusing, populates the search completion list store with ref symbols.
* @param search_entry
* @param event
*/
void on_search_entry_focus_in_event(GtkWidget* search_entry, GdkEvent* event);
/**
* SIGNAL FOR SEARCH ENTRY ACTIVATE
*
* Shows info for the entered security if available.
* @param entry
*/
void on_search_entry_activate(GtkEntry* entry);
/**
* SIGNAL FOR PEER COLUMN ACTIVATED
*
* Shows info for the security in the column activated.
* @param tree_view
* @param path
* @param column
*/
void on_info_peers_tree_view_row_activated(GtkTreeView* tree_view, GtkTreePath* path,
GtkTreeViewColumn* column);
/**
* Shows info for the given symbol
* @param slug
*/
void slug_show_info(const char* slug);
/**
* Formats text in an Info_Array for printing to window
* @param portfolio_data Info_Array* with valid Info data in it.
*/
void info_array_format_cells(Info_Array* portfolio_data);
/**
* Formats text in pInfo for printing to window
* @param pInfo
*/
void info_format_cells(Info* pInfo);
/**
* Sorts a ListStore struct according to idx.
* @param list_store ListStore to sort
* @param idx column number
*/
void list_store_sort(GtkListStore* list_store, Col_Index idx);
/**
* Destroys app.portfolio_data and recreates it from app.portfolio_string with api data. Then
* recreates the check list.
*/
void list_store_update(void);
/**
* Fills all components of info window with the given pInfo.
* @param pInfo
*/
void info_pane_populate_all(const Info* pInfo);
/**
* Fills header with info from pInfo
* @param pInfo
*/
void info_pane_populate_header(const Info* pInfo);
/**
* Fills company section with info from pInfo
* @param pInfo
*/
void info_pane_populate_company(const Info* pInfo);
/**
* Fills peers section with info from pInfo
* @param pInfo
*/
void info_pane_populate_peers(const Info* pInfo);
/**
* Fills news section with info from pInfo
* @param pInfo
*/
void info_pane_populate_news(const Info* pInfo);
/**
* SIGNAL FOR GRAPH DRAW
*
* Draws a graph of app.focused
* @param widget GtkDrawingArea
* @param cr cairo object to draw on
* @return FALSE
*/
gboolean on_info_graph_drawing_area_draw(GtkWidget* widget, cairo_t* cr);
/**
* Shows a generic message dialog.
* @param message the message to show
* @param success if true, will show a success dialog. otherwise it will show an error dialog.
*/
void show_generic_message_dialog(const char* message, gboolean success);
/**
* Sets the text property of a GObject to a string
* @param object the GObject to change the text of
* @param text the text to write
*/
void g_object_set_text(GObject* object, const gchar* text);
#endif | 28.447531 | 100 | 0.755343 | [
"object"
] |
89d0db194e87f61c20c0c81fd67aac0076d3934e | 3,649 | h | C | aws-cpp-sdk-ce/include/aws/ce/model/MetricValue.h | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-ce/include/aws/ce/model/MetricValue.h | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-ce/include/aws/ce/model/MetricValue.h | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T12:02:58.000Z | 2021-11-09T12:02:58.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/ce/CostExplorer_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace CostExplorer
{
namespace Model
{
/**
* <p>The aggregated value for a metric.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/ce-2017-10-25/MetricValue">AWS API
* Reference</a></p>
*/
class AWS_COSTEXPLORER_API MetricValue
{
public:
MetricValue();
MetricValue(Aws::Utils::Json::JsonView jsonValue);
MetricValue& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The actual number that represents the metric.</p>
*/
inline const Aws::String& GetAmount() const{ return m_amount; }
/**
* <p>The actual number that represents the metric.</p>
*/
inline bool AmountHasBeenSet() const { return m_amountHasBeenSet; }
/**
* <p>The actual number that represents the metric.</p>
*/
inline void SetAmount(const Aws::String& value) { m_amountHasBeenSet = true; m_amount = value; }
/**
* <p>The actual number that represents the metric.</p>
*/
inline void SetAmount(Aws::String&& value) { m_amountHasBeenSet = true; m_amount = std::move(value); }
/**
* <p>The actual number that represents the metric.</p>
*/
inline void SetAmount(const char* value) { m_amountHasBeenSet = true; m_amount.assign(value); }
/**
* <p>The actual number that represents the metric.</p>
*/
inline MetricValue& WithAmount(const Aws::String& value) { SetAmount(value); return *this;}
/**
* <p>The actual number that represents the metric.</p>
*/
inline MetricValue& WithAmount(Aws::String&& value) { SetAmount(std::move(value)); return *this;}
/**
* <p>The actual number that represents the metric.</p>
*/
inline MetricValue& WithAmount(const char* value) { SetAmount(value); return *this;}
/**
* <p>The unit that the metric is given in.</p>
*/
inline const Aws::String& GetUnit() const{ return m_unit; }
/**
* <p>The unit that the metric is given in.</p>
*/
inline bool UnitHasBeenSet() const { return m_unitHasBeenSet; }
/**
* <p>The unit that the metric is given in.</p>
*/
inline void SetUnit(const Aws::String& value) { m_unitHasBeenSet = true; m_unit = value; }
/**
* <p>The unit that the metric is given in.</p>
*/
inline void SetUnit(Aws::String&& value) { m_unitHasBeenSet = true; m_unit = std::move(value); }
/**
* <p>The unit that the metric is given in.</p>
*/
inline void SetUnit(const char* value) { m_unitHasBeenSet = true; m_unit.assign(value); }
/**
* <p>The unit that the metric is given in.</p>
*/
inline MetricValue& WithUnit(const Aws::String& value) { SetUnit(value); return *this;}
/**
* <p>The unit that the metric is given in.</p>
*/
inline MetricValue& WithUnit(Aws::String&& value) { SetUnit(std::move(value)); return *this;}
/**
* <p>The unit that the metric is given in.</p>
*/
inline MetricValue& WithUnit(const char* value) { SetUnit(value); return *this;}
private:
Aws::String m_amount;
bool m_amountHasBeenSet;
Aws::String m_unit;
bool m_unitHasBeenSet;
};
} // namespace Model
} // namespace CostExplorer
} // namespace Aws
| 27.43609 | 106 | 0.634694 | [
"model"
] |
89d198ca70f02f582fcab28651d397cb58367167 | 4,183 | h | C | ape/include/tencentcloud/ape/v20200513/model/DescribeImagesResponse.h | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | ape/include/tencentcloud/ape/v20200513/model/DescribeImagesResponse.h | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | ape/include/tencentcloud/ape/v20200513/model/DescribeImagesResponse.h | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | /*
* 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_APE_V20200513_MODEL_DESCRIBEIMAGESRESPONSE_H_
#define TENCENTCLOUD_APE_V20200513_MODEL_DESCRIBEIMAGESRESPONSE_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/AbstractModel.h>
#include <tencentcloud/ape/v20200513/model/ImageItem.h>
namespace TencentCloud
{
namespace Ape
{
namespace V20200513
{
namespace Model
{
/**
* DescribeImages返回参数结构体
*/
class DescribeImagesResponse : public AbstractModel
{
public:
DescribeImagesResponse();
~DescribeImagesResponse() = default;
CoreInternalOutcome Deserialize(const std::string &payload);
/**
* 获取页偏移量
* @return Offset 页偏移量
*/
int64_t GetOffset() const;
/**
* 判断参数 Offset 是否已赋值
* @return Offset 是否已赋值
*/
bool OffsetHasBeenSet() const;
/**
* 获取页大小
* @return Limit 页大小
*/
int64_t GetLimit() const;
/**
* 判断参数 Limit 是否已赋值
* @return Limit 是否已赋值
*/
bool LimitHasBeenSet() const;
/**
* 获取总条数
* @return Total 总条数
*/
int64_t GetTotal() const;
/**
* 判断参数 Total 是否已赋值
* @return Total 是否已赋值
*/
bool TotalHasBeenSet() const;
/**
* 获取是否有下一页
* @return HaveMore 是否有下一页
*/
bool GetHaveMore() const;
/**
* 判断参数 HaveMore 是否已赋值
* @return HaveMore 是否已赋值
*/
bool HaveMoreHasBeenSet() const;
/**
* 获取图片信息数组
* @return Items 图片信息数组
*/
std::vector<ImageItem> GetItems() const;
/**
* 判断参数 Items 是否已赋值
* @return Items 是否已赋值
*/
bool ItemsHasBeenSet() const;
private:
/**
* 页偏移量
*/
int64_t m_offset;
bool m_offsetHasBeenSet;
/**
* 页大小
*/
int64_t m_limit;
bool m_limitHasBeenSet;
/**
* 总条数
*/
int64_t m_total;
bool m_totalHasBeenSet;
/**
* 是否有下一页
*/
bool m_haveMore;
bool m_haveMoreHasBeenSet;
/**
* 图片信息数组
*/
std::vector<ImageItem> m_items;
bool m_itemsHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_APE_V20200513_MODEL_DESCRIBEIMAGESRESPONSE_H_
| 28.848276 | 83 | 0.419794 | [
"vector",
"model"
] |
89d240f8bd6a3f9e54756b105f0336d5bbfd070b | 1,976 | h | C | src/fileformat/file_format/pe/authenticode/x509_certificate.h | xbabka01/retdec | b37492014fedceee0b2b16b35962b397cad985a5 | [
"Zlib",
"Apache-2.0",
"MIT"
] | 1 | 2021-12-20T14:48:36.000Z | 2021-12-20T14:48:36.000Z | src/fileformat/file_format/pe/authenticode/x509_certificate.h | CuteCutePanda/retdec | e59b1388c766206e6642b79b2f6b4c761a679a80 | [
"Zlib",
"Apache-2.0",
"MIT"
] | null | null | null | src/fileformat/file_format/pe/authenticode/x509_certificate.h | CuteCutePanda/retdec | e59b1388c766206e6642b79b2f6b4c761a679a80 | [
"Zlib",
"Apache-2.0",
"MIT"
] | null | null | null | /**
* @file src/fileformat/file_format/pe/authenticode/x509_certificate.h
* @brief Class that wraps openssl x509 certificate information.
* @copyright (c) 2020 Avast Software, licensed under the MIT license
*/
#pragma once
#include "retdec/fileformat/types/certificate_table/certificate.h"
#include "retdec/fileformat/types/certificate_table/certificate_table.h"
#include "helper.h"
#include <memory>
#include <openssl/bn.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/ocsp.h>
#include <openssl/pkcs7.h>
#include <openssl/ts.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/x509_vfy.h>
#include <string>
#include <vector>
#include <ctime>
#include <iomanip>
using retdec::fileformat::Certificate;
namespace authenticode {
class X509Certificate
{ /* Can't name it X509 due to the collisions with openssl*/
private:
const X509* cert = nullptr;
public:
X509Certificate(const X509* cert);
X509Certificate() = default;
int getVersion() const;
std::string getValidUntil() const;
std::string getValidSince() const;
std::string getRawSubject() const;
std::string getRawIssuer() const;
std::string getSerialNumber() const;
std::string getSignatureAlgorithm() const;
std::string getPublicKey() const;
std::string getPublicKeyAlgorithm() const;
std::string getPem() const;
std::string getSignature() const;
std::string getSha1() const;
std::string getSha256() const;
Certificate::Attributes getSubject() const;
Certificate::Attributes getIssuer() const;
Certificate createCertificate() const;
};
class CertificateProcessor
{
private:
std::unique_ptr<X509_STORE, decltype(&X509_STORE_free)> trust_store;
std::unique_ptr<X509_STORE_CTX, decltype(&X509_STORE_CTX_free)> ctx;
public:
std::vector<X509Certificate> chain;
CertificateProcessor();
std::vector<X509Certificate> getChain(const X509* cert, const STACK_OF(X509)* all_certs);
const X509_STORE* getStore() const;
};
} // namespace authenticode
| 26 | 90 | 0.762146 | [
"vector"
] |
89d2d3b5cdbf0d06ab506777f338dbb49e6e649a | 41,818 | h | C | vendors/infineon/XMCLib/2.2.0/drivers/inc/xmc_usbd.h | dhwalters423/infineon-freertos | ce23016da800951ab563b7bcd9217f27891a43d3 | [
"MIT"
] | null | null | null | vendors/infineon/XMCLib/2.2.0/drivers/inc/xmc_usbd.h | dhwalters423/infineon-freertos | ce23016da800951ab563b7bcd9217f27891a43d3 | [
"MIT"
] | null | null | null | vendors/infineon/XMCLib/2.2.0/drivers/inc/xmc_usbd.h | dhwalters423/infineon-freertos | ce23016da800951ab563b7bcd9217f27891a43d3 | [
"MIT"
] | null | null | null | /**
* @file xmc_usbd.h
* @date 2015-06-20
*
*****************************************************************************
* XMClib v2.2.0 - XMC Peripheral Driver Library
*
* Copyright (c) 2015-2020, Infineon Technologies AG
* All rights reserved.
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* To improve the quality of the software, users are encouraged to share
* modifications, enhancements or bug fixes with Infineon Technologies AG
* at XMCSupport@infineon.com.
*****************************************************************************
*
* Change History
* --------------
*
* 2015-02-16:
* - Initial Version.<br>
* 2015-03-18:
* - Updated the doxygen comments for documentation. <br>
* - Updated the XMC_USBD_PATCH_VERSION to 4. <br>
*
* 2015-06-20:
* - Removed version macros and declaration of GetDriverVersion API.<br>
* - Updated the doxygen comments for API XMC_USBD_IsEnumDone().<br>
* - Updated the copy right in the file header.<br>
*
* @endcond
*
*/
#ifndef XMC_USBD_H
#define XMC_USBD_H
/**********************************************************************************************************************
* HEADER FILES
*********************************************************************************************************************/
#include "xmc_common.h"
#if defined(USB0)
#include <stdlib.h>
#include <string.h>
#include "xmc_usbd_regs.h"
#include "xmc_scu.h"
/**
* @addtogroup XMClib XMC Peripheral Library
* @{
*/
/**
* @addtogroup USBD
* @brief Universal Serial Bus Device (USBD) driver for the XMC4000 microcontroller family.
*
* The USBD is the device driver for the USB0 hardware module on XMC4000 family of microcontrollers.
* The USB0 module can be used to establish a USB interface between outside world and XMC4000 family of controllers.
* The USB module includes the following features in device mode:
* -# Complies with the USB 2.0 Specification.
* -# Support for the Full-Speed (12-Mbps) mode.
* -# Supports up to 7 bidirectional endpoints, including control endpoint 0.
* -# Supports SOFs in Full-Speed modes.
* -# Supports clock gating for power saving.
* -# Supports USB suspend/resume.
* -# Supports USB soft disconnect.
* -# Supports DMA mode.
* -# Supports FIFO mode.
*
* The below figure shows the overview of USB0 module in XMC4 microntroller.
* @image html USB_module_overview.png
* @image latex ../images/USB_module_overview.png
*
* The below figure shows the USB device connection of USB0 module.
* @image html USB_device_connection.png
* @image latex ../images/USB_device_connection.png
*
* The USBD device driver supports the following features:\n
* -# Initialize/Uninitialize the USB0 module on XMC4000 device.
* -# Connect the USB device to host.
* -# Get USB device state.
* -# Set the USB device address.
* -# Configure/Unconfigure the USB endpoints.
* -# Stall/Abort the USB endpoints.
* -# USB IN transfers on EP0 and non EP0 endpoints.
* -# USB OUT transfers on EP0 and non EP0 endpoints.
*
* The USBD device driver provides the configuration structure ::XMC_USBD_t which user need to configure before initializing the USB.\n
* The following elements of configuration structure need to be initialized before calling the ::XMC_USBD_Init API:
* -# cb_xmc_device_event of type ::XMC_USBD_SignalDeviceEvent_t.
* -# cb_endpoint_event of type ::XMC_USBD_SignalEndpointEvent_t.
* -# usbd_max_num_eps of type ::XMC_USBD_MAX_NUM_EPS_t.
* -# usbd_transfer_mode of type ::XMC_USBD_TRANSFER_MODE_t.
*
* @{
*/
/**********************************************************************************************************************
* MACROS
*********************************************************************************************************************/
#define XMC_USBD_NUM_TX_FIFOS (7U) /**< Number of hardware transmission endpoint fifos */
#define XMC_USBD_MAX_FIFO_SIZE (2048U) /**< Maximum USBD endpoint fifo size */
#define XMC_USBD_NUM_EPS (7U) /**< Number of hardware endpoints */
#define XMC_USBD_MAX_PACKET_SIZE (64U) /**< Maximum packet size for all endpoints
(including ep0) */
/**< Maximum transfer size for endpoints.
*
* It's based on the maximum payload, due to the fact,
* that we only can transfer 2^10 - 1 packets and this is less than the
* transfer size field can hold.
*/
#define XMC_USBD_MAX_TRANSFER_SIZE (((uint32_t)((uint32_t)1U << (uint32_t)10U) - 1U) * (uint32_t)XMC_USBD_MAX_PACKET_SIZE)
#define XMC_USBD_MAX_TRANSFER_SIZE_EP0 (64U) /**< Maximum transfer size for endpoint 0*/
#define XMC_USBD_SETUP_COUNT (3U) /**< The number of USB setup packets */
#define XMC_USBD_SETUP_SIZE (8U) /**< The size of USB setup data */
#define XMC_USBD_EP_NUM_MASK (0x0FU) /**< USB Endpoint number mask. */
#define XMC_USBD_EP_DIR_MASK (0x80U) /**< USB Endpoint direction mask */
#define XMC_USBD_DCFG_DEVSPD_FS (0x3U) /*USB Full Speed device flag in DCFG register */
#define XMC_USBD_TX_FIFO_REG_OFFSET (0x1000U)/* First endpoint fifo register offset from base address */
#define XMC_USBD_TX_FIFO_OFFSET (0x1000U)/* Offset for each fifo register */
#define XMC_USBD_ENDPOINT_NUMBER_MASK (0x0FU) /**< USB Endpoint number mask to get the EP number from address. */
#define XMC_USBD_ENDPOINT_DIRECTION_MASK (0x80U) /**< USB Endpoint direction mask to get the EP direction from address. */
#define XMC_USBD_ENDPOINT_MAX_PACKET_SIZE_MASK (0x07FFU)/**< USB Endpoint Maximum Packet Size mask */
#define XMC_USBD_ENDPOINT_MFRAME_TR_MASK (0x1800U)/* USB Endpoint micro frame TR mask */
#define XMC_USBD_ENDPOINT_MFRAME_TR_1 (0x0000U)/* Selects USB Endpoint micro frame TR1 */
#define XMC_USBD_ENDPOINT_MFRAME_TR_2 (0x0800U)/* Selects USB Endpoint micro frame TR2 */
#define XMC_USBD_ENDPOINT_MFRAME_TR_3 (0x1000U)/* Selects USB Endpoint micro frame TR3 */
#define XMC_USBD_SPEED_FULL (1U) /**< Speed Mode. Full Speed */
#define XMC_USBD_EP0_BUFFER_SIZE (64U) /* Endpoint 0 buffer size */
#define XMC_USBD_EP1_BUFFER_SIZE (64U) /* Endpoint 1 buffer size */
#define XMC_USBD_EP2_BUFFER_SIZE (64U) /* Endpoint 2 buffer size */
#define XMC_USBD_EP3_BUFFER_SIZE (64U) /* Endpoint 3 buffer size */
#define XMC_USBD_EP4_BUFFER_SIZE (64U) /* Endpoint 4 buffer size */
#define XMC_USBD_EP5_BUFFER_SIZE (64U) /* Endpoint 5 buffer size */
#define XMC_USBD_EP6_BUFFER_SIZE (64U) /* Endpoint 6 buffer size */
/**********************************************************************************************************************
* ENUMS
*********************************************************************************************************************/
/**
* Defines the options for the global receive fifo packet status.
* Use type ::XMC_USBD_GRXSTS_PKTSTS_t for this enum.
* */
typedef enum XMC_USBD_GRXSTS_PKTSTS {
XMC_USBD_GRXSTS_PKTSTS_GOUTNAK = 0x1U, /**< Global out nack send ( triggers an interrupt ) */
XMC_USBD_GRXSTS_PKTSTS_OUTDATA = 0x2U, /**< OUT data packet received */
XMC_USBD_GRXSTS_PKTSTS_OUTCMPL = 0x3U, /**< OUT transfer completed (triggers an interrupt) */
XMC_USBD_GRXSTS_PKTSTS_SETUPCMPL = 0x4U, /**< SETUP transaction completed (triggers an interrupt) */
XMC_USBD_GRXSTS_PKTSTS_SETUP = 0x6U /**< SETUP data packet received */
} XMC_USBD_GRXSTS_PKTSTS_t;
/**
* Defines the options for the USB endpoint type. The values are from the USB 2.0 specification.
* Use type ::XMC_USBD_ENDPOINT_TYPE_t for this enum.
*/
typedef enum XMC_USBD_ENDPOINT_TYPE {
XMC_USBD_ENDPOINT_TYPE_CONTROL = 0x0U, /**< Control endpoint */
XMC_USBD_ENDPOINT_TYPE_ISOCHRONOUS = 0x01U, /**< Isochronous endpoint */
XMC_USBD_ENDPOINT_TYPE_BULK = 0x02U, /**< Bulk endpoint */
XMC_USBD_ENDPOINT_TYPE_INTERRUPT = 0x03U /**< Interrupt endpoint */
} XMC_USBD_ENDPOINT_TYPE_t;
/**
* Defines the options for USB device state while setting the address.
* Use type ::XMC_USBD_SET_ADDRESS_STAGE_t for this enum.
*/
typedef enum XMC_USBD_SET_ADDRESS_STAGE {
XMC_USBD_SET_ADDRESS_STAGE_SETUP, /**< Setup address */
XMC_USBD_SET_ADDRESS_STAGE_STATUS /**< Status address */
} XMC_USBD_SET_ADDRESS_STAGE_t;
/**
* Defines the USB Device Status of executed operation.
* Use type ::XMC_USBD_STATUS_t for this enum.
*/
typedef enum XMC_USBD_STATUS {
XMC_USBD_STATUS_OK = 0U, /**< USBD Status: Operation succeeded*/
XMC_USBD_STATUS_BUSY = 2U, /**< Driver is busy and cannot handle request */
XMC_USBD_STATUS_ERROR = 1U /**< USBD Status: Unspecified error*/
} XMC_USBD_STATUS_t;
/**
* Defines the USB Device events.
* Use type ::XMC_USBD_EVENT_t for this enum.
*/
typedef enum XMC_USBD_EVENT {
XMC_USBD_EVENT_POWER_ON, /**< USB Device Power On */
XMC_USBD_EVENT_POWER_OFF, /**< USB Device Power Off */
XMC_USBD_EVENT_CONNECT, /**< USB Device connected */
XMC_USBD_EVENT_DISCONNECT, /**< USB Device disconnected */
XMC_USBD_EVENT_RESET, /**< USB Reset occurred */
XMC_USBD_EVENT_HIGH_SPEED, /**< USB switch to High Speed occurred */
XMC_USBD_EVENT_SUSPEND, /**< USB Suspend occurred */
XMC_USBD_EVENT_RESUME, /**< USB Resume occurred */
XMC_USBD_EVENT_REMOTE_WAKEUP, /**< USB Remote wakeup */
XMC_USBD_EVENT_SOF, /**< USB Start of frame event */
XMC_USBD_EVENT_EARLYSUSPEND, /**< USB Early suspend */
XMC_USBD_EVENT_ENUMDONE, /**< USB enumeration done */
XMC_USBD_EVENT_ENUMNOTDONE, /**< USB enumeration not done */
XMC_USBD_EVENT_OUTEP, /**< USB OUT endpoint */
XMC_USBD_EVENT_INEP /**< USB IN endpoint */
} XMC_USBD_EVENT_t;
/**
* Defines the USB IN endpoint events.
* Use type ::XMC_USBD_EVENT_IN_EP_t for this enum.
*/
typedef enum XMC_USBD_EVENT_IN_EP {
XMC_USBD_EVENT_IN_EP_TX_COMPLET = 1U, /**< USB IN ep transmission complete */
XMC_USBD_EVENT_IN_EP_DISABLED = 2U, /**< USB IN ep disabled */
XMC_USBD_EVENT_IN_EP_AHB_ERROR = 4U, /**< USB IN ep AHB error */
XMC_USBD_EVENT_IN_EP_TIMEOUT = 8U, /**< USB IN ep timeout */
} XMC_USBD_EVENT_IN_EP_t;
/**
* Defines the USB OUT endpoint events.
* Use type ::XMC_USBD_EVENT_OUT_EP_t for this enum.
*/
typedef enum XMC_USBD_EVENT_OUT_EP {
XMC_USBD_EVENT_OUT_EP_TX_COMPLET = 1U, /**< USB OUT ep transmission complete */
XMC_USBD_EVENT_OUT_EP_DISABLED = 2U, /**< USB OUT ep disabled */
XMC_USBD_EVENT_OUT_EP_AHB_ERROR = 4U, /**< USB OUT ep AHB error */
XMC_USBD_EVENT_OUT_EP_SETUP = 8U, /**< USB OUT ep setup */
} XMC_USBD_EVENT_OUT_EP_t;
/**
* Defines the generic USB endpoint events.
* Use type ::XMC_USBD_EP_EVENT_t for this enum.
*/
typedef enum XMC_USBD_EP_EVENT {
XMC_USBD_EP_EVENT_SETUP, /**< SETUP packet*/
XMC_USBD_EP_EVENT_OUT, /**< OUT packet*/
XMC_USBD_EP_EVENT_IN /**< IN packet*/
} XMC_USBD_EP_EVENT_t;
/**
* Defines the options for the USB data transfer modes.
* Use type ::XMC_USBD_TRANSFER_MODE_t for this enum.
*/
typedef enum XMC_USBD_TRANSFER_MODE {
XMC_USBD_USE_DMA, /**< Transfer by DMA*/
XMC_USBD_USE_FIFO /**< Transfer by FIFO*/
} XMC_USBD_TRANSFER_MODE_t;
/**
* Defines the options for the maximum number of endpoints used.
* Use type ::XMC_USBD_MAX_NUM_EPS_t for this enum.
*/
typedef enum XMC_USBD_MAX_NUM_EPS {
XMC_USBD_MAX_NUM_EPS_1 = 1U, /**< Maximum 1 endpoint used*/
XMC_USBD_MAX_NUM_EPS_2 = 2U, /**< Maximum 2 endpoints used*/
XMC_USBD_MAX_NUM_EPS_3 = 3U, /**< Maximum 3 endpoints used*/
XMC_USBD_MAX_NUM_EPS_4 = 4U, /**< Maximum 4 endpoints used*/
XMC_USBD_MAX_NUM_EPS_5 = 5U, /**< Maximum 5 endpoints used*/
XMC_USBD_MAX_NUM_EPS_6 = 6U, /**< Maximum 6 endpoints used*/
XMC_USBD_MAX_NUM_EPS_7 = 7U /**< Maximum 2 endpoints used*/
} XMC_USBD_MAX_NUM_EPS_t;
/**
* USB device/endpoint event function pointers
*/
typedef void (*XMC_USBD_SignalDeviceEvent_t) (XMC_USBD_EVENT_t event);/**< Pointer to USB device event call back.
Uses type ::XMC_USBD_EVENT_t as the argument of callback.*/
typedef void (*XMC_USBD_SignalEndpointEvent_t) (uint8_t ep_addr, XMC_USBD_EP_EVENT_t ep_event);/**< Pointer to USB endpoint event call back.
Uses type ::XMC_USBD_EP_EVENT_t and EP address as the argument of callback.*/
/**********************************************************************************************************************
* DATA STRUCTURES
*********************************************************************************************************************/
/**
* Describes the USB Device Driver Capabilities.
*/
typedef struct XMC_USBD_CAPABILITIES {
uint32_t event_power_on : 1; /**< Signal Power On event*/
uint32_t event_power_off : 1; /**< Signal Power Off event*/
uint32_t event_connect : 1; /**< Signal Connect event*/
uint32_t event_disconnect : 1; /**< Signal Disconnect event*/
uint32_t event_reset : 1; /**< Signal Reset event*/
uint32_t event_high_speed : 1; /**< Signal switch to High-speed event*/
uint32_t event_suspend : 1; /**< Signal Suspend event*/
uint32_t event_resume : 1; /**< Signal Resume event*/
uint32_t event_remote_wakeup : 1; /**< Signal Remote Wake up event*/
uint32_t reserved : 23; /**< Reserved for future use*/
} XMC_USBD_CAPABILITIES_t;
/**
* Describes the current USB Device State.
*/
typedef struct XMC_USBD_STATE {
uint32_t powered : 1; /**< USB Device powered flag*/
uint32_t connected : 1; /**< USB Device connected flag*/
uint32_t active : 1; /**< USB Device active lag*/
uint32_t speed : 2; /**< USB Device speed */
} XMC_USBD_STATE_t;
/**
* Describes a USB endpoint<BR>
*
* All information to control an endpoint is stored in this structure.
* It contains information about the endpoints and the status of the device.
*/
typedef struct {
union {
uint32_t address : 8; /**< The endpoint address including the direction */
struct {
uint32_t number : 4; /**< The endpoint number.It can be from 0 to 6 */
uint32_t pading : 3; /**< Padding between number and direction */
uint32_t direction : 1; /**< The endpoint direction */
} address_st;
} address_u;
uint32_t type : 2; /**< The endpoint type */
uint32_t isConfigured : 1; /**< The flag showing, if the endpoint is configured */
volatile uint32_t inInUse : 1; /**< Sets if the selected USB IN endpoint is currently in use */
volatile uint32_t outInUse : 1; /**< Sets if the selected USB OUT endpoint is currently in use */
uint32_t isStalled : 1; /**< Sets if the selected USB endpoint is stalled. */
uint32_t txFifoNum : 4; /**< Endpoint transmit Fifo Number */
uint32_t sendZeroLengthPacket : 1; /**< If set, a zero length packet will be send at the end of the transfer */
uint32_t maxPacketSize : 7; /**< The maximum size of packet for USB endpoint ( due to FS Speed device only 64 Byte )*/
uint32_t maxTransferSize : 19; /**< The maximum amount of data the core can send at once.*/
uint8_t *outBuffer; /**< The buffer for operation as OUT endpoint */
uint32_t outBytesAvailable; /**< The number of bytes available in the EP OUT buffer */
uint32_t outBufferSize; /**< The size of the EP OUT buffer */
uint32_t outOffset; /**< The read offset of the EP OUT buffer */
uint8_t *inBuffer; /**< The buffer for operation as IN endpoint */
uint32_t inBufferSize; /**< The size of the EP IN buffer */
uint8_t *xferBuffer; /**< The buffer of the current transfer */
uint32_t xferLength; /**< The length of the current transfer */
uint32_t xferCount; /**< Bytes transfered of the current USB data transfer */
uint32_t xferTotal; /**< The length of total data in buffer */
} XMC_USBD_EP_t;
/**
* Describes the XMC USB device<BR>
*
* All information to control an XMC USB device is stored in
* this structure. It contains register, callbacks, information
* about the endpoints and the status of the device.
*/
typedef struct XMC_USBD_DEVICE {
XMC_USBD_EP_t ep[8]; /**< Endpoints of the USB device. It is of type ::XMC_USBD_EP_t */
dwc_otg_core_global_regs_t *global_register; /**< Global register interface */
dwc_otg_device_global_regs_t *device_register; /**< Device register interface */
dwc_otg_dev_in_ep_regs_t *endpoint_in_register[(uint8_t)XMC_USBD_NUM_EPS];/**< IN Endpoint register interface */
dwc_otg_dev_out_ep_regs_t *endpoint_out_register[(uint8_t)XMC_USBD_NUM_EPS];/**< OUT Endpoint register interface */
volatile uint32_t *fifo[(uint8_t)XMC_USBD_NUM_TX_FIFOS]; /**< Transmit fifo interface */
uint16_t txfifomsk; /**< Mask of used TX fifos */
uint32_t IsConnected : 1; /**< Sets if device is connected */
uint32_t IsActive : 1; /**< Sets if device is currently active */
uint32_t IsPowered : 1; /**< Sets if device is powered by Vbus */
XMC_USBD_SignalDeviceEvent_t DeviceEvent_cb; /**< The USB device event callback. */
XMC_USBD_SignalEndpointEvent_t EndpointEvent_cb; /**< The USB endpoint event callback. */
} XMC_USBD_DEVICE_t;
/**
* USB device initialization structure
*/
typedef struct XMC_USBD_OBJ
{
USB0_GLOBAL_TypeDef *const usbd; /**< USB Module Pointer. The USB0 module base address. */
XMC_USBD_SignalDeviceEvent_t cb_xmc_device_event; /**< USB device event callback. Use ::XMC_USBD_SignalDeviceEvent_t type of function pointer. */
XMC_USBD_SignalEndpointEvent_t cb_endpoint_event; /**< USB endpoint event callback. Use ::XMC_USBD_SignalEndpointEvent_t type of function pointer.*/
XMC_USBD_MAX_NUM_EPS_t usbd_max_num_eps; /**< Maximum number of end points used. The maximum range can be 7.*/
XMC_USBD_TRANSFER_MODE_t usbd_transfer_mode; /**< USB data transfer mode.Use ::XMC_USBD_TRANSFER_MODE_t type to specify the transfer mode. */
} XMC_USBD_t;
/**
* Defines the access structure of the USB Device Driver.
*/
typedef struct XMC_USBD_DRIVER {
XMC_USBD_CAPABILITIES_t (*GetCapabilities) (void); /**< Pointer to @ref XMC_USBD_GetCapabilities : Get driver capabilities.*/
XMC_USBD_STATUS_t (*Initialize) (XMC_USBD_t *obj); /**< Pointer to @ref XMC_USBD_Init : Initialize USB Device Interface.*/
XMC_USBD_STATUS_t (*Uninitialize) (void); /**< Pointer to @ref XMC_USBD_Uninitialize : De-initialize USB Device Interface.*/
XMC_USBD_STATUS_t (*DeviceConnect) (void); /**< Pointer to @ref XMC_USBD_DeviceConnect : Connect USB Device.*/
XMC_USBD_STATUS_t (*DeviceDisconnect) (void); /**< Pointer to @ref XMC_USBD_DeviceDisconnect : Disconnect USB Device.*/
XMC_USBD_STATE_t (*DeviceGetState) (const XMC_USBD_t *const obj); /**< Pointer to @ref XMC_USBD_DeviceGetState : Get current USB Device State.*/
XMC_USBD_STATUS_t (*DeviceSetAddress) (uint8_t dev_addr, XMC_USBD_SET_ADDRESS_STAGE_t stage);/**< Pointer to @ref XMC_USBD_DeviceSetAddress : Set USB Device Address.*/
XMC_USBD_STATUS_t (*EndpointConfigure) (uint8_t ep_addr,XMC_USBD_ENDPOINT_TYPE_t ep_type, uint16_t ep_max_packet_size);/**< Pointer to @ref XMC_USBD_EndpointConfigure : Configure USB Endpoint.*/
XMC_USBD_STATUS_t (*EndpointUnconfigure)(uint8_t ep_addr); /**< Pointer to @ref XMC_USBD_EndpointUnconfigure : Unconfigure USB Endpoint.*/
XMC_USBD_STATUS_t (*EndpointStall) (uint8_t ep_addr, bool stall); /**< Pointer to @ref XMC_USBD_EndpointStall : Set/Clear Stall for USB Endpoint.*/
XMC_USBD_STATUS_t (*EndpointReadStart) (uint8_t ep_addr, uint32_t len); /**< Pointer to @ref XMC_USBD_EndpointReadStart : Start USB Endpoint Read operation.*/
int32_t (*EndpointRead) (uint8_t ep_addr, uint8_t *buf, uint32_t len);/**< Pointer to @ref XMC_USBD_EndpointRead : Read data from USB Endpoint.*/
int32_t (*EndpointWrite) (uint8_t ep_addr, const uint8_t *buf, uint32_t len); /**< Pointer to @ref XMC_USBD_EndpointWrite : Write data to USB Endpoint.*/
XMC_USBD_STATUS_t (*EndpointAbort) (uint8_t ep_addr); /**< Pointer to @ref XMC_USBD_EndpointAbort : Abort current USB Endpoint transfer.*/
uint16_t (*GetFrameNumber) (void); /**< Pointer to @ref XMC_USBD_GetFrameNumber : Get current USB Frame Number.*/
uint32_t (*IsEnumDone) (void); /**< Pointer to @ref XMC_USBD_IsEnumDone : Is enumeration done in Host?.*/
} const XMC_USBD_DRIVER_t;
/**
* Defines the driver interface function table.
* To access the XMC device controller driver interface use this table of functions.
**/
extern const XMC_USBD_DRIVER_t Driver_USBD0;
/**
* Defines the XMC USB device data
* The instance of ::XMC_USBD_DEVICE_t structure describing the XMC device.
**/
extern XMC_USBD_DEVICE_t xmc_device;
/**********************************************************************************************************************
* API PROTOTYPES
*********************************************************************************************************************/
#ifdef __cplusplus
extern "C" {
#endif
/**
* @param None.
*
* @return None.
*
* \par<b>Description:</b><BR>
* Enables the USB module in the XMC controller.<BR>
* It de-asserts the peripheral reset on USB0 module and enables the USB power.
*
* \par<b>Note:</b><BR>
* This API is called inside the XMC_USBD_Init().\n
*
* \par<b>Related APIs:</b><BR>
* XMC_USBD_Disable()\n
**/
void XMC_USBD_Enable(void);
/**
* @param None.
*
* @return None.
*
* \par<b>Description:</b><BR>
* Disables the USB module in the XMC controller.<BR>
* It asserts the peripheral reset on USB0 module and disables the USB power.
*
* \par<b>Related APIs:</b><BR>
* XMC_USBD_Enable()\n
**/
void XMC_USBD_Disable(void);
/**
* @param event The single event that needs to be cleared. Use ::XMC_USBD_EVENT_t as argument.\n
*
* @return None.
*
* \par<b>Description:</b><BR>
* Clears the selected USBD \a event.<BR>
* It clears the event by writing to the GINTSTS register.
*
* \par<b>Note:</b><BR>
* This API is called inside the USB interrupt handler to clear the event XMC_USBD_EVENT_t
* and maintain the device state machine.\n
*
* \par<b>Related APIs:</b><BR>
* ::XMC_USBD_ClearEventOUTEP(),::XMC_USBD_ClearEventINEP()\n
**/
void XMC_USBD_ClearEvent(XMC_USBD_EVENT_t event);
/**
* @param event The single event or multiple events that need to be cleared.
*
* @param ep_num The IN endpoint number on which the events to be cleared.
*
* @return None.
*
* \par<b>Description:</b><BR>
* Clears the single event or multiple events of the selected IN endpoint.<BR>
* The multiple events can be selected by the bitwise OR operation of ::XMC_USBD_EVENT_IN_EP_t elements.\n
* It clears the event by programming DIEPINT register.\n
*
* \par<b>Note:</b><BR>
* This API is called inside the USB IN EP interrupt handler to clear the ::XMC_USBD_EVENT_IN_EP_t event
* and maintain the device state machine.\n
*
* \par<b>Related APIs:</b><BR>
* ::XMC_USBD_ClearEventOUTEP()\n
**/
void XMC_USBD_ClearEventINEP(uint32_t event,uint8_t ep_num);
/**
* @param event The single event or multiple events that need to be cleared.
*
* @param ep_num The OUT endpoint number on which the events to be cleared.
*
* @return None.
*
* \par<b>Description:</b><BR>
* Clears the single \a event or multiple events of the selected OUT endpoint.<BR>
* The multiple events can be selected by the bitwise OR operation of ::XMC_USBD_EVENT_OUT_EP_t elements.
* It clears the event by writing to DOEPINT register.
*
* \par<b>Note:</b><BR>
* This API is called inside the USB OUT EP interrupt handler to clear the ::XMC_USBD_EVENT_OUT_EP_t event
* and maintain the device state machine.\n
*
* \par<b>Related APIs:</b><BR>
* ::XMC_USBD_ClearEventINEP()\n
**/
void XMC_USBD_ClearEventOUTEP(uint32_t event,uint8_t ep_num);
/**
* @param event The single event or multiple events that need to be enabled.
*
* @return None.
*
* \par<b>Description:</b><BR>
* Enables the event or multiple events of the OUT endpoints.<BR>
* The multiple events can be selected by the bitwise OR operation of ::XMC_USBD_EVENT_OUT_EP_t elements.
* It enables the event by programming DOEPMSK register.
*
* \par<b>Note:</b><BR>
* This API is called inside the ::XMC_USBD_Init() to enable the OUT EP interrupts.\n
*
* \par<b>Related APIs:</b><BR>
* ::XMC_USBD_EnableEventINEP()\n
**/
void XMC_USBD_EnableEventOUTEP(uint32_t event);
/**
* @param event The single event or multiple events that need to be enabled.
*
* @return None.
*
* \par<b>Description:</b><BR>
* Enables the \a event or multiple events of the USB IN endpoints.<BR>
* The multiple events can be selected by the bitwise OR operation of ::XMC_USBD_EVENT_IN_EP_t elements.
* It enables the event by programming DIEPMSK register.
*
* \par<b>Note:</b><BR>
* This API is called inside the ::XMC_USBD_Init() to enable the IN EP interrupts.\n
*
* \par<b>Related APIs:</b><BR>
* ::XMC_USBD_EnableEventOUTEP()\n
**/
void XMC_USBD_EnableEventINEP(uint32_t event);
/**
* @param None.
*
* @return ::XMC_USBD_CAPABILITIES_t.
*
* \par<b>Description:</b><BR>
* Retrieves the USB device capabilities of type \a XMC_USBD_CAPABILITIES_t<BR>
* The USB device capabilities supported by the USBD driver, like power on/off, connect/disconnect,
* reset,suspend/resume,USB speed etc are retrieved.
*
* It can be called after initializing the USB device to get the information on the USBD capabilities.
*
**/
XMC_USBD_CAPABILITIES_t XMC_USBD_GetCapabilities(void);
/**
* @param obj The pointer to the USB device handle ::XMC_USBD_t.
*
* @return XMC_USBD_STATUS_t The USB device status of type ::XMC_USBD_STATUS_t.
*
* \par<b>Description:</b><BR>
* Initializes the USB device to get ready for connect to USB host.<BR>
* Enables the USB module,sets the EP buffer sizes,registers the device and EP event call backs.
* Initializes the global,device and FIFO register base addresses.
* Configures the global AHB,enables the global interrupt and DMA by programming GAHBCFG register.
* Configures the USB in to device mode and enables the session request protocol by programming GUSBCFG register.
* Configures the USB device speed to full speed by programming DCFG register.
* Disconnects the USB device by programming DCTL register.
* Enables the USB common and device interrupts by programming GINTMSK register.
*
* \par<b>Note:</b><BR>
* This API makes the USB device ready to connect to host.The user has to explicitly call
* the ::XMC_USBD_DeviceConnect() after the USB initialization to connect to USB host.\n
*
* \par<b>Related APIs:</b><BR>
* ::XMC_USBD_DeviceConnect()\n
**/
XMC_USBD_STATUS_t XMC_USBD_Init(XMC_USBD_t *obj);
/**
* @param None.
*
* @return ::XMC_USBD_STATUS_t.
*
* \par<b>Description:</b><BR>
* Uninitialises the USB device.<BR>
* Disconnects the USB device by programming DCTL register and resets the XMC USB device data.
*
* \par<b>Note:</b><BR>
* Once this API is called, USB device will not be accessible from host.\n
*
* \par<b>Related APIs:</b><BR>
* ::XMC_USBD_Init()\n
**/
XMC_USBD_STATUS_t XMC_USBD_Uninitialize(void);
/**
* @param None.
*
* @return ::XMC_USBD_STATUS_t.
*
* \par<b>Description:</b><BR>
* Connects the USB device to host and triggers the USB enumeration.<BR>
* Connects the USB device to host by programming DCTL register.\n
* It resets the soft disconnect bit, which activates the speed pull up at d+ line of USB.
* ::XMC_USBD_Init() should be called before calling this API.
*
* \par<b>Note:</b><BR>
* Once this API is called, USB host starts the enumeration process and the device should
* handle the descriptor requests.\n
*
* \par<b>Related APIs:</b><BR>
* ::XMC_USBD_Init()\n
**/
XMC_USBD_STATUS_t XMC_USBD_DeviceConnect(void);
/**
* @param None.
*
* @return ::XMC_USBD_STATUS_t.
*
* \par<b>Description:</b><BR>
* Disconnects the USB device from host.<BR>
* By programming DCTL register, it sets the soft disconnect bit, which deactivates\n
* the speed pull up at d+ line of USB.
*
* \par<b>Note:</b><BR>
* Once this API is called, USB device will not be accessible from host.\n
*
* \par<b>Related APIs:</b><BR>
* ::XMC_USBD_DeviceConnect()\n
**/
XMC_USBD_STATUS_t XMC_USBD_DeviceDisconnect(void);
/**
* @param obj The pointer to the USB device handle structure \a XMC_USBD_t.
*
* @return ::XMC_USBD_STATE_t.
*
* \par<b>Description:</b><BR>
* Retrieves the current USB device state.<BR>
* Power,active,speed and connection status data are retrieved.\n
*
* \par<b>Note:</b><BR>
* Before calling this API, USB should be initialized with ::XMC_USBD_Init.\n
*
* \par<b>Related APIs:</b><BR>
* ::XMC_USBD_Init()\n
**/
XMC_USBD_STATE_t XMC_USBD_DeviceGetState(const XMC_USBD_t *const obj);
/**
* @param address The address to be set for the USB device .
* @param stage The device request stage-setup or status ::XMC_USBD_SET_ADDRESS_STAGE_t.
*
* @return ::XMC_USBD_STATUS_t.
*
* \par<b>Description:</b><BR>
* Sets the USB device address.<BR>
* The device address is programmed in the DCFG register.<BR>
*
* The address should be more than 0; as 0 is the default USB device address at the starting of enumeration.
* As part of enumeration, host sends the control request to the device to set the USB address; and in turn,\n
* in the USB device event call back handler, user has to set the address using this API for the set address request.<BR>
*
* The stage parameter should be XMC_USBD_SET_ADDRESS_STAGE_SETUP from the enum ::XMC_USBD_SET_ADDRESS_STAGE_t.
*
* \par<b>Note:</b><BR>
* Before calling this API, USB should be initialized with ::XMC_USBD_Init () and connected to
* USB host using ::XMC_USBD_DeviceConnect() \n
*
* \par<b>Related APIs:</b><BR>
* ::XMC_USBD_Init(), ::XMC_USBD_DeviceConnect()\n
**/
XMC_USBD_STATUS_t XMC_USBD_DeviceSetAddress(uint8_t address,XMC_USBD_SET_ADDRESS_STAGE_t stage);
/**
* @param ep_addr The address of the USB endpoint, which needs to be configured.
* @param ep_type The ::XMC_USBD_ENDPOINT_TYPE_t.
* @param ep_max_packet_size The maximum packet size of endpoint in USB full speed.
*
* @return ::XMC_USBD_STATUS_t.
*
* \par<b>Description:</b><BR>
* Configures the USB endpoint.<BR>
* The endpoint is configured by programming the DAINT,DIEPCTL and DOEPCTL registers.<BR>
*
* Configures the EP type, FIFO number,maximum packet size, enables endpoint and sets the DATA0 PID.
* This function also initializes the internal buffer handling for the specified endpoint,
* but does not start any transfers.<BR>
*
* As part of enumeration, host sends the control request to the device to set the configuration; and in turn,\n
* in the USB device event call back handler, user has to set the configuration and configure the endpoints \n
* required for the device.\n
*
* \par<b>Note:</b><BR>
* This API should only be used as part of enumeration.\n
*
* \par<b>Related APIs:</b><BR>
* ::XMC_USBD_Init(),::XMC_USBD_DeviceConnect(),::XMC_USBD_EndpointUnconfigure()\n
**/
XMC_USBD_STATUS_t XMC_USBD_EndpointConfigure(uint8_t ep_addr,
XMC_USBD_ENDPOINT_TYPE_t ep_type,
uint16_t ep_max_packet_size);
/**
* @param ep_addr The address of the USB endpoint, which needs to be unconfigured.
*
* @return ::XMC_USBD_STATUS_t.
*
* \par<b>Description:</b><BR>
* Unconfigures the USB endpoint.<BR>
* The endpoint is unconfigured by programming the DAINT,DIEPCTL and DOEPCTL registers.\n
* Disables the endpoint, unassign the fifo, deactivate it and only send nacks.\n
* Waits until the endpoint has finished operation and disables it. All (eventuallly) allocated buffers gets freed.
* Forces the endpoint to stop immediately, any pending transfers are killed(Can cause device reset).
*
* \par<b>Related APIs:</b><BR>
* ::XMC_USBD_EndpointConfigure()\n
**/
XMC_USBD_STATUS_t XMC_USBD_EndpointUnconfigure(uint8_t ep_addr);
/**
* @param ep_addr The address of the USB endpoint, on which stall needs to be set or cleared.
* @param stall The boolean variable to decide on set or clear of stall on EP.
*
* @return ::XMC_USBD_STATUS_t.
*
* \par<b>Description:</b><BR>
* Set or Clear stall on the USB endpoint \a ep_addr, based on \a stall parameter.<BR>
*
* By programming stall bit in the doepctl and diepctl, it sets or clears the stall on the endpoint.
* The endpoint can be stalled when a non supported request comes from the USB host.
* The XMC_USBD_EndpointStall() should be called with \a stall set to 0, in the clear feature standard request
* in the USB device event call back handler. *
*
* \par<b>Note:</b><BR>
* The host should clear the stall set on the endpoint by sending the clear feature standard
* request on the non EP0 endpoints. On EP0, the stall will automatically gets cleared on the next control request.\n
*
* \par<b>Related APIs:</b><BR>
* ::XMC_USBD_EndpointAbort()\n
**/
XMC_USBD_STATUS_t XMC_USBD_EndpointStall(uint8_t ep_addr, bool stall);
/**
* @param ep_addr The address of the USB endpoint, from which data need to be read.
* @param size The number of bytes to be read.
*
* @return ::XMC_USBD_STATUS_t.
*
* \par<b>Description:</b><BR>
* Prepares an endpoint to receive OUT tokens from the USB host.<BR>
* The selected endpoint gets configured, so that it receives the specified amount of data from the host.
* As part of streaming of OUT data, after reading the current OUT buffer using ::XMC_USBD_EndpointRead(),\n
* user can prepare endpoint for the next OUT packet by using ::XMC_USBD_EndpointReadStart().
*
* The registers DOEPDMA,DOEPTSIZ and DOEPCTL are programmed to start a new read request.
*
* \par<b>Note:</b><BR>
* For the data received on OUT EP buffer, use ::XMC_USBD_EndpointRead().\n
*
* \par<b>Related APIs:</b><BR>
* XMC_USBD_EndpointRead()\n
**/
XMC_USBD_STATUS_t XMC_USBD_EndpointReadStart(const uint8_t ep_addr, uint32_t size);
/**
* @param ep_addr The address of the USB OUT endpoint, from which data need to be read.
* @param buffer The pointer to the user buffer,in which data need to be received.
* @param length The number of bytes to be read from OUT EP.
*
* @return <BR>
* The actual number of bytes received.
*
* \par<b>Description:</b><BR>
* Read \a length number of bytes from an OUT endpoint \a ep_addr.<BR>
* If data has been received for this endpoint, it gets copied into the user buffer until its full
* or no data is left in the driver buffer.
*
* \par<b>Note:</b><BR>
* For preparing the next OUT token, use ::XMC_USBD_EndpointReadStart() after ::XMC_USBD_EndpointRead().\n
*
*
* \par<b>Related APIs:</b><BR>
* ::XMC_USBD_EndpointReadStart()\n
**/
int32_t XMC_USBD_EndpointRead(const uint8_t ep_addr,uint8_t * buffer, uint32_t length);
/**
* @param ep_addr The address of the USB IN endpoint, on which data should be sent.
* @param buffer The pointer to the data buffer, to write to the endpoint.
* @param length The number of bytes to be written to IN EP.
*
* @return <BR>
* The actual amount of data written to the endpoint buffer.
*
* \par<b>Description:</b><BR>
* Write the \a length bytes of data to an IN endpoint \a ep_addr.<BR>
* The User data gets copied into the driver buffer or will be send directly based on the buffer concept
* selected in the ::XMC_USBD_TRANSFER_MODE_t configuration.
*
* Then the endpoint is set up to transfer the data to the host.\n
* DIEPDMA,DIEPTSIZ and DIEPCTL registers are programmed to start the IN transfer.
*
*
* \par<b>Related APIs:</b><BR>
* ::XMC_USBD_EndpointRead()\n
**/
int32_t XMC_USBD_EndpointWrite(const uint8_t ep_addr,const uint8_t * buffer,uint32_t length);
/**
* @param ep_addr The address of the USB endpoint, on which the data need to be aborted.
*
* @return ::XMC_USBD_STATUS_t
*
* \par<b>Description:</b><BR>
* Abort the transfer on endpoint \a ep_addr.<BR>
* On any failure with the USB transmission user can reset the endpoint into default state and clear all
* assigned buffers, to start from a clean point. The endpoint will not be unconfigured or disabled.
*
* \par<b>Related APIs:</b><BR>
* ::XMC_USBD_EndpointUnconfigure()\n
**/
XMC_USBD_STATUS_t XMC_USBD_EndpointAbort(uint8_t ep_addr);
/**
* @param None.
*
* @return The 16 bit current USB frame number.
*
* \par<b>Description:</b><BR>
* Read the current USB frame number.<BR> *
* Reads the device status register (DSTS) and returns the SOFFN field.
*
**/
uint16_t XMC_USBD_GetFrameNumber(void);
/**
* @param None.
*
* @return Returns 1, if the speed enumeration is done and 0 otherwise.
*
* \par<b>Description:</b><BR>
* Gets the speed enumeration completion status of the USB device.<BR>
*
* \par<b>Note:</b><BR>
* This should not be used for the actual USB enumeration completion status. For the actual USB enumeration status,
* the application layer should check for the completion of USB standard request 'Set configuration'.\n
*
**/
uint32_t XMC_USBD_IsEnumDone(void);
/**
* @param obj The pointer to the USB device handle structure.
*
* @return None.
*
* \par<b>Description:</b><BR>
* USB device default IRQ handler.<BR>
* USBD Peripheral LLD provides default implementation of ISR.
* The user needs to explicitly either use our default implementation or use its own one using the LLD APIs.
*
* For example:
* XMC_USBD_t *obj;
* void USB0_0_IRQHandler(void)
* {
* XMC_USBD_IRQHandler(obj);
* }
*
* \par<b>Note:</b><BR>
* The user should initialize the XMC USB device configuration structure before calling
* ::XMC_USBD_IRQHandler() in the actual USB0 IRQ handler.
*
**/
void XMC_USBD_IRQHandler(const XMC_USBD_t *const obj);
#ifdef __cplusplus
}
#endif
/**
* MISRA C 2004 Deviations
*
* 1. Function like macro- defined- MISRA Advisory Rule 19.7
* 2. usage of unions - MISRA Required Rule 18.4
*/
/**
* @}
*/
/**
* @}
*/
#endif /* defined(USB0) */
#endif /* XMC_USBD_H */
| 42.028141 | 203 | 0.652996 | [
"object"
] |
89d53e6018a403278d3a536bf313c3b4bdb711f5 | 151,142 | h | C | cegui/include/CEGUI/String.h | OpenTechEngine-Libraries/CEGUI | 6f00952d31f318f9482766d1ad2206cb540a78b9 | [
"MIT"
] | 57 | 2015-05-15T11:42:42.000Z | 2022-03-24T06:13:17.000Z | cegui/include/CEGUI/String.h | OpenTechEngine-Libraries/CEGUI | 6f00952d31f318f9482766d1ad2206cb540a78b9 | [
"MIT"
] | null | null | null | cegui/include/CEGUI/String.h | OpenTechEngine-Libraries/CEGUI | 6f00952d31f318f9482766d1ad2206cb540a78b9 | [
"MIT"
] | 22 | 2015-05-07T16:17:22.000Z | 2019-12-18T05:58:41.000Z | /***********************************************************************
created: 26/2/2004
author: Paul D Turner
purpose: Defines string class used within the GUI system.
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* 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 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 _String_h_
#define _String_h_
#include "CEGUI/Base.h"
#include <cstring>
#include <stdexcept>
#include <cstddef>
// Start of CEGUI namespace section
namespace CEGUI
{
/*************************************************************************
Basic Types
*************************************************************************/
typedef uint8 utf8;
//typedef uint16 utf16; // removed typedef to prevent usage, as utf16 is not supported (yet)
typedef uint32 utf32;
#if CEGUI_STRING_CLASS == CEGUI_STRING_CLASS_UNICODE
/// encoded char signifies that it's a char (8bit) with encoding (in this case utf8)
typedef utf8 encoded_char;
#define CEGUI_STR_QUICKBUFF_SIZE 32
/*!
\brief
String class used within the GUI system.
For the most part, this class can replace std::string in basic usage. However, currently String does not use the
current locale, and also comparisons do not take into account the Unicode data tables, so are not 'correct'
as such.
*/
class CEGUIEXPORT String
{
public:
/*************************************************************************
Integral Types
*************************************************************************/
typedef utf32 value_type; //!< Basic 'code point' type used for String (utf32)
typedef size_t size_type; //!< Unsigned type used for size values and indices
typedef std::ptrdiff_t difference_type; //!< Signed type used for differences
typedef utf32& reference; //!< Type used for utf32 code point references
typedef const utf32& const_reference; //!< Type used for constant utf32 code point references
typedef utf32* pointer; //!< Type used for utf32 code point pointers
typedef const utf32* const_pointer; //!< Type used for constant utf32 code point pointers
static const size_type npos; //!< Value used to represent 'not found' conditions and 'all code points' etc.
private:
/*************************************************************************
Implementation data
*************************************************************************/
size_type d_cplength; //!< holds length of string in code points (not including null termination)
size_type d_reserve; //!< code point reserve size (currently allocated buffer size in code points).
mutable utf8* d_encodedbuff; //!< holds string data encoded as utf8 (generated only by calls to c_str() and data())
mutable size_type d_encodeddatlen; //!< holds length of encoded data (in case it's smaller than buffer).
mutable size_type d_encodedbufflen; //!< length of above buffer (since buffer can be bigger then the data it holds to save re-allocations).
utf32 d_quickbuff[CEGUI_STR_QUICKBUFF_SIZE]; //!< This is a integrated 'quick' buffer to save allocations for smallish strings
utf32* d_buffer; //!< Pointer the the main buffer memory. This is only valid when quick-buffer is not being used
public:
/*************************************************************************
Iterator Classes
*************************************************************************/
//! regular iterator for String.
class iterator : public std::iterator<std::random_access_iterator_tag, utf32>
{
public:
iterator() : d_ptr(0) {}
explicit iterator(utf32* const ptr) : d_ptr(ptr) {}
utf32& operator*() const
{
return *d_ptr;
}
utf32* operator->() const
{
return &**this;
}
String::iterator& operator++()
{
++d_ptr;
return *this;
}
String::iterator operator++(int)
{
String::iterator temp = *this;
++*this;
return temp;
}
String::iterator& operator--()
{
--d_ptr;
return *this;
}
String::iterator operator--(int)
{
String::iterator temp = *this;
--*this;
return temp;
}
String::iterator& operator+=(difference_type offset)
{
d_ptr += offset;
return *this;
}
String::iterator operator+(difference_type offset) const
{
String::iterator temp = *this;
return temp += offset;
}
String::iterator& operator-=(difference_type offset)
{
return *this += -offset;
}
String::iterator operator-(difference_type offset) const
{
String::iterator temp = *this;
return temp -= offset;
}
utf32& operator[](difference_type offset) const
{
return *(*this + offset);
}
friend difference_type operator-(const String::iterator& lhs,
const String::iterator& rhs)
{ return lhs.d_ptr - rhs.d_ptr; }
friend String::iterator operator+(difference_type offset, const String::iterator& iter)
{ return iter + offset; }
friend bool operator==(const String::iterator& lhs,
const String::iterator& rhs)
{ return lhs.d_ptr == rhs.d_ptr; }
friend bool operator!=(const String::iterator& lhs,
const String::iterator& rhs)
{ return lhs.d_ptr != rhs.d_ptr; }
friend bool operator<(const String::iterator& lhs,
const String::iterator& rhs)
{ return lhs.d_ptr < rhs.d_ptr; }
friend bool operator>(const String::iterator& lhs,
const String::iterator& rhs)
{ return lhs.d_ptr > rhs.d_ptr; }
friend bool operator<=(const String::iterator& lhs,
const String::iterator& rhs)
{ return lhs.d_ptr <= rhs.d_ptr; }
friend bool operator>=(const String::iterator& lhs,
const String::iterator& rhs)
{ return lhs.d_ptr >= rhs.d_ptr; }
utf32* d_ptr;
};
//! const iterator for String.
class const_iterator : public std::iterator<std::random_access_iterator_tag, const utf32>
{
public:
const_iterator() : d_ptr(0) {}
explicit const_iterator(const utf32* const ptr) : d_ptr(ptr) {}
const_iterator(const String::iterator& iter) : d_ptr(iter.d_ptr) {}
const utf32& operator*() const
{
return *d_ptr;
}
const utf32* operator->() const
{
return &**this;
}
String::const_iterator& operator++()
{
++d_ptr;
return *this;
}
String::const_iterator operator++(int)
{
String::const_iterator temp = *this;
++*this;
return temp;
}
String::const_iterator& operator--()
{
--d_ptr;
return *this;
}
String::const_iterator operator--(int)
{
String::const_iterator temp = *this;
--*this;
return temp;
}
String::const_iterator& operator+=(difference_type offset)
{
d_ptr += offset;
return *this;
}
String::const_iterator operator+(difference_type offset) const
{
String::const_iterator temp = *this;
return temp += offset;
}
String::const_iterator& operator-=(difference_type offset)
{
return *this += -offset;
}
String::const_iterator operator-(difference_type offset) const
{
String::const_iterator temp = *this;
return temp -= offset;
}
const utf32& operator[](difference_type offset) const
{
return *(*this + offset);
}
String::const_iterator& operator=(const String::iterator& iter)
{
d_ptr = iter.d_ptr;
return *this;
}
friend String::const_iterator operator+(difference_type offset, const String::const_iterator& iter)
{ return iter + offset; }
friend difference_type operator-(const String::const_iterator& lhs,
const String::const_iterator& rhs)
{ return lhs.d_ptr - rhs.d_ptr; }
friend bool operator==(const String::const_iterator& lhs,
const String::const_iterator& rhs)
{ return lhs.d_ptr == rhs.d_ptr; }
friend bool operator!=(const String::const_iterator& lhs,
const String::const_iterator& rhs)
{ return lhs.d_ptr != rhs.d_ptr; }
friend bool operator<(const String::const_iterator& lhs,
const String::const_iterator& rhs)
{ return lhs.d_ptr < rhs.d_ptr; }
friend bool operator>(const String::const_iterator& lhs,
const String::const_iterator& rhs)
{ return lhs.d_ptr > rhs.d_ptr; }
friend bool operator<=(const String::const_iterator& lhs,
const String::const_iterator& rhs)
{ return lhs.d_ptr <= rhs.d_ptr; }
friend bool operator>=(const String::const_iterator& lhs,
const String::const_iterator& rhs)
{ return lhs.d_ptr >= rhs.d_ptr; }
const utf32* d_ptr;
};
/*!
\brief
Constant reverse iterator class for String objects
*/
#if defined(_MSC_VER) && ((_MSC_VER <= 1200) || ((_MSC_VER <= 1300) && defined(_STLPORT_VERSION)))
typedef std::reverse_iterator<const_iterator, const_pointer, const_reference, difference_type> const_reverse_iterator;
#else
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
#endif
/*!
\brief
Reverse iterator class for String objects
*/
#if defined(_MSC_VER) && ((_MSC_VER <= 1200) || ((_MSC_VER <= 1300) && defined(_STLPORT_VERSION)))
typedef std::reverse_iterator<iterator, pointer, reference, difference_type> reverse_iterator;
#else
typedef std::reverse_iterator<iterator> reverse_iterator;
#endif
public:
//////////////////////////////////////////////////////////////////////////
// Default Construction and Destructor
//////////////////////////////////////////////////////////////////////////
/*!
\brief
Constructs an empty string
*/
String(void)
{
init();
}
/*!
\brief
Destructor for String objects
*/
~String(void);
//////////////////////////////////////////////////////////////////////////
// Construction via CEGUI::String
//////////////////////////////////////////////////////////////////////////
/*!
\brief
Copy constructor - Creates a new string with the same value as \a str
\param str
String object used to initialise the newly created string
\return
Nothing
*/
String(const String& str)
{
init();
assign(str);
}
/*!
\brief
Constructs a new string initialised with code points from another String object.
\param str
String object used to initialise the newly created string
\param str_idx
Starting code-point of \a str to be used when initialising the new String
\param str_num
Maximum number of code points from \a str that are to be assigned to the new String
\return
Nothing
*/
String(const String& str, size_type str_idx, size_type str_num = npos)
{
init();
assign(str, str_idx, str_num);
}
//////////////////////////////////////////////////////////////////////////
// Construction via std::string
//////////////////////////////////////////////////////////////////////////
/*!
\brief
Constructs a new string and initialises it using the std::string std_str
\param std_str
The std::string object that is to be used to initialise the new String object.
\note
The characters of \a std_str are taken to be unencoded data which represent Unicode code points 0x00..0xFF. No translation of
the provided data will occur.
\return
Nothing
\exception std::length_error Thrown if resulting String object would be too big.
*/
String(const std::string& std_str)
{
init();
assign(std_str);
}
/*!
\brief
Constructs a new string initialised with characters from the given std::string object.
\param std_str
std::string object used to initialise the newly created string
\param str_idx
Starting character of \a std_str to be used when initialising the new String
\note
The characters of \a std_str are taken to be unencoded data which represent Unicode code points 0x00..0xFF. No translation of
the provided data will occur.
\param str_num
Maximum number of characters from \a std_str that are to be assigned to the new String
\return
Nothing
\exception std::length_error Thrown if resulting String object would be too big.
*/
String(const std::string& std_str, size_type str_idx, size_type str_num = npos)
{
init();
assign(std_str, str_idx, str_num);
}
//////////////////////////////////////////////////////////////////////////
// Construction via UTF-8 stream (for straight ASCII use, only codes 0x00 - 0x7f are valid)
//////////////////////////////////////////////////////////////////////////
/*!
\brief
Constructs a new String object and initialise it using the provided utf8 encoded string buffer.
\param utf8_str
Pointer to a buffer containing a null-terminated Unicode string encoded as utf8 data.
\note
A basic string literal (cast to utf8*) can be passed to this function, provided that the string is
comprised only of code points 0x00..0x7f. The use of extended ASCII characters (with values >0x7f)
would result in incorrect behaviour as the String will attempt to 'decode' the data, with unpredictable
results.
\return
Nothing
\exception std::length_error Thrown if resulting String object would be too big.
*/
String(const utf8* utf8_str)
{
init();
assign(utf8_str);
}
/*!
\brief
Constructs a new String object and initialise it using the provided utf8 encoded string buffer.
A basic string literal (cast to utf8*) can be passed to this function, provided that the string is
comprised only of code points 0x00..0x7f. The use of extended ASCII characters (with values >0x7f)
would result in incorrect behaviour as the String will attempt to 'decode' the data, with unpredictable
results.
\param utf8_str
Pointer to a buffer containing Unicode string data encoded as utf8.
\note
A basic string literal (cast to utf8*) can be passed to this function, provided that the string is
comprised only of code points 0x00..0x7f. The use of extended ASCII characters (with values >0x7f)
would result in incorrect behaviour as the String will attempt to 'decode' the data, with unpredictable
results.
\param chars_len
Length of the provided utf8 string in code units (not code-points).
\return
Nothing
\exception std::length_error Thrown if resulting String object would be too big.
*/
String(const utf8* utf8_str, size_type chars_len)
{
init();
assign(utf8_str, chars_len);
}
//////////////////////////////////////////////////////////////////////////
// Construction via code-point (using a UTF-32 code unit)
//////////////////////////////////////////////////////////////////////////
/*!
\brief
Constructs a new String that is initialised with the specified code point
\param num
The number of times \a code_point is to be put into new String object
\param code_point
The Unicode code point to be used when initialising the String object
\return
Nothing
\exception std::length_error Thrown if resulting String object would be too big.
*/
String(size_type num, utf32 code_point)
{
init();
assign(num, code_point);
}
//////////////////////////////////////////////////////////////////////////
// Construction via iterator
//////////////////////////////////////////////////////////////////////////
// Create string with characters in the range [beg, end)
/*!
\brief
Construct a new string object and initialise it with code-points from the range [beg, end).
\param beg
Iterator describing the start of the data to be used when initialising the String object
\param end
Iterator describing the (exclusive) end of the data to be used when initialising the String object
\return
Nothing
*/
String(const_iterator iter_beg, const_iterator iter_end)
{
init();
append(iter_beg, iter_end);
}
//////////////////////////////////////////////////////////////////////////
// Construction via c-string
//////////////////////////////////////////////////////////////////////////
/*!
\brief
Constructs a new String object and initialise it using the provided c-string.
\param c_str
Pointer to a c-string.
\return
Nothing
\exception std::length_error Thrown if resulting String object would be too big.
*/
String(const char* cstr)
{
init();
assign(cstr);
}
/*!
\brief
Constructs a new String object and initialise it using characters from the provided char array.
\param chars
char array.
\param chars_len
Number of chars from the array to be used.
\return
Nothing
\exception std::length_error Thrown if resulting String object would be too big.
*/
String(const char* chars, size_type chars_len)
{
init();
assign(chars, chars_len);
}
//////////////////////////////////////////////////////////////////////////
// Size operations
//////////////////////////////////////////////////////////////////////////
/*!
\brief
Returns the size of the String in code points
\return
Number of code points currently in the String
*/
size_type size(void) const
{
return d_cplength;
}
/*!
\brief
Returns the size of the String in code points
\return
Number of code points currently in the String
*/
size_type length(void) const
{
return d_cplength;
}
/*!
\brief
Returns true if the String is empty
\return
true if the String is empty, else false.
*/
bool empty(void) const
{
return (d_cplength == 0);
}
/*!
\brief
Returns the maximum size of a String.
Any operation that would result in a String that is larger than this value will throw the std::length_error exception.
\return
The maximum number of code points that a string can contain
*/
size_type max_size(void) const
{
return (((size_type)-1) / sizeof(utf32));
}
//////////////////////////////////////////////////////////////////////////
// Capacity Operations
//////////////////////////////////////////////////////////////////////////
// return the number of code points the string could hold without re-allocation
// (due to internal encoding this will always report the figure for worst-case encoding, and could even be < size()!)
/*!
\brief
Return the number of code points that the String could hold before a re-allocation would be required.
\return
Size of the current reserve buffer. This is the maximum number of code points the String could hold before a buffer
re-allocation would be required
*/
size_type capacity(void) const
{
return d_reserve - 1;
}
// reserve internal memory for at-least 'num' code-points (characters). if num is 0, request is shrink-to-fit.
/*!
\brief
Specifies the amount of reserve capacity to allocate.
\param num
The number of code points to allocate space for. If \a num is larger that the current reserve, then a re-allocation will occur. If
\a num is smaller than the current reserve (but not 0) the buffer may be shrunk to the larger of the specified number, or the current
String size (operation is currently not implemented). If \a num is 0, then the buffer is re-allocated to fit the current String size.
\return
Nothing
\exception std::length_error Thrown if resulting String object would be too big.
*/
void reserve(size_type num = 0)
{
if (num == 0)
trim();
else
grow(num);
}
//////////////////////////////////////////////////////////////////////////
// Comparisons
//////////////////////////////////////////////////////////////////////////
/*!
\brief
Compares this String with the String 'str'.
\note
This does currently not properly consider Unicode and / or the system locale.
\param str
The String object that is to compared with this String.
\return
- 0 if the String objects are equal
- <0 if this String is lexicographically smaller than \a str
- >0 if this String is lexicographically greater than \a str
*/
int compare(const String& str) const
{
return compare(0, d_cplength, str);
}
/*!
\brief
Compares code points from this String with code points from the String 'str'.
\note
This does currently not properly consider Unicode and / or the system locale.
\param idx
Index of the first code point from this String to consider.
\param len
Maximum number of code points from this String to consider.
\param str
The String object that is to compared with this String.
\param str_idx
Index of the first code point from String \a str to consider.
\param str_len
Maximum number of code points from String \a str to consider
\return
- 0 if the specified sub-strings are equal
- <0 if specified sub-strings are lexicographically smaller than \a str
- >0 if specified sub-strings are lexicographically greater than \a str
\exception std::out_of_range Thrown if either \a idx or \a str_idx are invalid.
*/
int compare(size_type idx, size_type len, const String& str, size_type str_idx = 0, size_type str_len = npos) const
{
if ((d_cplength < idx) || (str.d_cplength < str_idx))
CEGUI_THROW(std::out_of_range("Index is out of range for CEGUI::String"));
if ((len == npos) || (idx + len > d_cplength))
len = d_cplength - idx;
if ((str_len == npos) || (str_idx + str_len > str.d_cplength))
str_len = str.d_cplength - str_idx;
int val = (len == 0) ? 0 : utf32_comp_utf32(&ptr()[idx], &str.ptr()[str_idx], (len < str_len) ? len : str_len);
return (val != 0) ? ((val < 0) ? -1 : 1) : (len < str_len) ? -1 : (len == str_len) ? 0 : 1;
}
/*!
\brief
Compares this String with the std::string 'std_str'.
\note
This does currently not properly consider Unicode and / or the system locale.
\param std_str
The std::string object that is to compared with this String.
\note
Characters from \a std_str are considered to represent Unicode code points in the range 0x00..0xFF. No translation of
the encountered data is performed.
\return
- 0 if the string objects are equal
- <0 if this string is lexicographically smaller than \a std_str
- >0 if this string is lexicographically greater than \a std_str
*/
int compare(const std::string& std_str) const
{
return compare(0, d_cplength, std_str);
}
/*!
\brief
Compares code points from this String with code points from the std::string 'std_str'.
\note
This does currently not properly consider Unicode and / or the system locale.
\param idx
Index of the first code point from this String to consider.
\param len
Maximum number of code points from this String to consider.
\param std_str
The std::string object that is to compared with this String.
\note
Characters from \a std_str are considered to represent Unicode code points in the range 0x00..0xFF. No translation of
the encountered data is performed.
\param str_idx
Index of the first character from std::string \a std_str to consider.
\param str_len
Maximum number of characters from std::string \a std_str to consider
\return
- 0 if the specified sub-strings are equal
- <0 if specified sub-strings are lexicographically smaller than \a std_str
- >0 if specified sub-strings are lexicographically greater than \a std_str
\exception std::out_of_range Thrown if either \a idx or \a str_idx are invalid.
*/
int compare(size_type idx, size_type len, const std::string& std_str, size_type str_idx = 0, size_type str_len = npos) const
{
if (d_cplength < idx)
CEGUI_THROW(std::out_of_range("Index is out of range for CEGUI::String"));
if (std_str.size() < str_idx)
CEGUI_THROW(std::out_of_range("Index is out of range for std::string"));
if ((len == npos) || (idx + len > d_cplength))
len = d_cplength - idx;
if ((str_len == npos) || (str_idx + str_len > std_str.size()))
str_len = (size_type)std_str.size() - str_idx;
int val = (len == 0) ? 0 : utf32_comp_char(&ptr()[idx], &std_str.c_str()[str_idx], (len < str_len) ? len : str_len);
return (val != 0) ? ((val < 0) ? -1 : 1) : (len < str_len) ? -1 : (len == str_len) ? 0 : 1;
}
/*!
\brief
Compares this String with the null-terminated utf8 encoded 'utf8_str'.
\note
This does currently not properly consider Unicode and / or the system locale.
\param utf8_str
The buffer containing valid Unicode data encoded as utf8 that is to compared with this String.
\note
A basic string literal (cast to utf8*) can be passed to this function, provided that the string is
comprised only of code points 0x00..0x7f. The use of extended ASCII characters (with values >0x7f)
would result in incorrect behaviour as the String will attempt to 'decode' the data, with unpredictable
results.
\return
- 0 if the strings are equal
- <0 if this string is lexicographically smaller than \a utf8_str
- >0 if this string is lexicographically greater than \a utf8_str
*/
int compare(const utf8* utf8_str) const
{
return compare(0, d_cplength, utf8_str, encoded_size(utf8_str));
}
/*!
\brief
Compares code points from this String with the null-terminated utf8 encoded 'utf8_str'.
\note
This does currently not properly consider Unicode and / or the system locale.
\param idx
Index of the first code point from this String to consider.
\param len
Maximum number of code points from this String to consider.
\param utf8_str
The buffer containing valid Unicode data encoded as utf8 that is to compared with this String.
\note
A basic string literal (cast to utf8*) can be passed to this function, provided that the string is
comprised only of code points 0x00..0x7f. The use of extended ASCII characters (with values >0x7f)
would result in incorrect behaviour as the String will attempt to 'decode' the data, with unpredictable
results.
\return
- 0 if the specified sub-strings are equal
- <0 if specified sub-strings are lexicographically smaller than \a utf8_str
- >0 if specified sub-strings are lexicographically greater than \a utf8_str
\exception std::out_of_range Thrown if \a idx is invalid.
*/
int compare(size_type idx, size_type len, const utf8* utf8_str) const
{
return compare(idx, len, utf8_str, encoded_size(utf8_str));
}
/*!
\brief
Compares code points from this String with the utf8 encoded data in buffer 'utf8_str'.
\note
This does currently not properly consider Unicode and / or the system locale.
\param idx
Index of the first code point from this String to consider.
\param len
Maximum number of code points from this String to consider.
\param utf8_str
The buffer containing valid Unicode data encoded as utf8 that is to compared with this String.
\note
A basic string literal (cast to utf8*) can be passed to this function, provided that the string is
comprised only of code points 0x00..0x7f. The use of extended ASCII characters (with values >0x7f)
would result in incorrect behaviour as the String will attempt to 'decode' the data, with unpredictable
results.
\param str_cplen
The number of encoded code points in the buffer \a utf8_str (this is not the same as the number of code units).
\return
- 0 if the specified sub-strings are equal
- <0 if specified sub-strings are lexicographically smaller than \a utf8_str
- >0 if specified sub-strings are lexicographically greater than \a utf8_str
\exception std::out_of_range Thrown if \a idx is invalid.
\exception std::length_error Thrown if \a str_cplen is set to npos.
*/
int compare(size_type idx, size_type len, const utf8* utf8_str, size_type str_cplen) const
{
if (d_cplength < idx)
CEGUI_THROW(std::out_of_range("Index is out of range for CEGUI::String"));
if (str_cplen == npos)
CEGUI_THROW(std::length_error("Length for utf8 encoded string can not be 'npos'"));
if ((len == npos) || (idx + len > d_cplength))
len = d_cplength - idx;
int val = (len == 0) ? 0 : utf32_comp_utf8(&ptr()[idx], utf8_str, (len < str_cplen) ? len : str_cplen);
return (val != 0) ? ((val < 0) ? -1 : 1) : (len < str_cplen) ? -1 : (len == str_cplen) ? 0 : 1;
}
/*!
\brief
Compares this String with the given c-string.
\note
This does currently not properly consider Unicode and / or the system locale.
\param c_str
The c-string that is to compared with this String.
\return
- 0 if the strings are equal
- <0 if this string is lexicographically smaller than \a c_str
- >0 if this string is lexicographically greater than \a c_str
*/
int compare(const char* cstr) const
{
return compare(0, d_cplength, cstr, strlen(cstr));
}
/*!
\brief
Compares code points from this String with the given c-string.
\note
This does currently not properly consider Unicode and / or the system locale.
\param idx
Index of the first code point from this String to consider.
\param len
Maximum number of code points from this String to consider.
\param c_str
The c-string that is to compared with this String.
\return
- 0 if the specified sub-strings are equal
- <0 if specified sub-strings are lexicographically smaller than \a c_str
- >0 if specified sub-strings are lexicographically greater than \a c_str
\exception std::out_of_range Thrown if \a idx is invalid.
*/
int compare(size_type idx, size_type len, const char* cstr) const
{
return compare(idx, len, cstr, strlen(cstr));
}
/*!
\brief
Compares code points from this String with chars in the given char array.
\note
This does currently not properly consider Unicode and / or the system locale.
\param idx
Index of the first code point from this String to consider.
\param len
Maximum number of code points from this String to consider.
\param chars
The array containing the chars that are to compared with this String.
\param chars_len
The number of chars in the array.
\return
- 0 if the specified sub-strings are equal
- <0 if specified sub-strings are lexicographically smaller than \a chars
- >0 if specified sub-strings are lexicographically greater than \a chars
\exception std::out_of_range Thrown if \a idx is invalid.
\exception std::length_error Thrown if \a chars_len is set to npos.
*/
int compare(size_type idx, size_type len, const char* chars, size_type chars_len) const
{
if (d_cplength < idx)
CEGUI_THROW(std::out_of_range("Index is out of range for CEGUI::String"));
if (chars_len == npos)
CEGUI_THROW(std::length_error("Length for char array can not be 'npos'"));
if ((len == npos) || (idx + len > d_cplength))
len = d_cplength - idx;
int val = (len == 0) ? 0 : utf32_comp_char(&ptr()[idx], chars, (len < chars_len) ? len : chars_len);
return (val != 0) ? ((val < 0) ? -1 : 1) : (len < chars_len) ? -1 : (len == chars_len) ? 0 : 1;
}
//////////////////////////////////////////////////////////////////////////
// Character access
//////////////////////////////////////////////////////////////////////////
/*!
\brief
Returns the code point at the given index.
\param idx
Zero based index of the code point to be returned.
\note
- For constant strings length()/size() provide a valid index and will access the default utf32 value.
- For non-constant strings length()/size() is an invalid index, and acceesing (especially writing) this index could cause string corruption.
\return
The utf32 code point at the given index within the String.
*/
reference operator[](size_type idx)
{
return (ptr()[idx]);
}
/*!
\brief
Returns the code point at the given index.
\param idx
Zero based index of the code point to be returned.
\note
- For constant strings length()/size() provide a valid index and will access the default utf32 value.
- For non-constant strings length()/size() is an invalid index, and acceesing (especially writing) this index could cause string corruption.
\return
The utf32 code point at the given index within the String.
*/
value_type operator[](size_type idx) const
{
return ptr()[idx];
}
/*!
\brief
Returns the code point at the given index.
\param idx
Zero based index of the code point to be returned.
\return
The utf32 code point at the given index within the String.
\exception std::out_of_range Thrown if \a idx is >= length().
*/
reference at(size_type idx)
{
if (d_cplength <= idx)
CEGUI_THROW(std::out_of_range("Index is out of range for CEGUI::String"));
return ptr()[idx];
}
/*!
\brief
Returns the code point at the given index.
\param idx
Zero based index of the code point to be returned.
\return
The utf32 code point at the given index within the String.
\exception std::out_of_range Thrown if \a idx is >= length().
*/
const_reference at(size_type idx) const
{
if (d_cplength <= idx)
CEGUI_THROW(std::out_of_range("Index is out of range for CEGUI::String"));
return ptr()[idx];
}
//////////////////////////////////////////////////////////////////////////
// C-Strings and arrays
//////////////////////////////////////////////////////////////////////////
/*!
\brief
Returns contents of the String as a null terminated string of utf8 encoded data.
\return
Pointer to a char buffer containing the contents of the String encoded as null-terminated utf8 data.
\note
The buffer returned from this function is owned by the String object.
\note
Any function that modifies the String data will invalidate the buffer returned by this call.
*/
const char* c_str(void) const
{
return (const char*)build_utf8_buff();
}
/*!
\brief
Returns contents of the String as utf8 encoded data.
\return
Pointer to a buffer containing the contents of the String encoded utf8 data.
\note
The buffer returned from this function is owned by the String object.
\note
Any function that modifies the String data will invalidate the buffer returned by this call.
*/
const utf8* data(void) const
{
return build_utf8_buff();
}
/*!
\brief
Returns a pointer to the buffer in use.
*/
utf32* ptr(void)
{
return (d_reserve > CEGUI_STR_QUICKBUFF_SIZE) ? d_buffer : d_quickbuff;
}
/*!
\brief
Returns a pointer to the buffer in use. (const version)
*/
const utf32* ptr(void) const
{
return (d_reserve > CEGUI_STR_QUICKBUFF_SIZE) ? d_buffer : d_quickbuff;
}
// copy, at most, 'len' code-points of the string, begining with code-point 'idx', into the array 'buf' as valid utf8 encoded data
// return number of utf8 code units placed into the buffer
/*!
\brief
Copies an area of the String into the provided buffer as encoded utf8 data.
\param buf
Pointer to a buffer that is to receive the encoded data (this must be big enough to hold the encoded data)
\param len
Maximum number of code points from the String that should be encoded into the buffer
\param idx
Index of the first code point to be encoded into the buffer
\return
The number of utf8 encoded code units transferred to the buffer.
\note A code unit does not equal a code point. A utf32 code point, when encoded as utf8, can occupy between 1 and 4 code units.
\exception std::out_of_range Thrown if \a idx was invalid for this String.
*/
size_type copy(utf8* buf, size_type len = npos, size_type idx = 0) const
{
if (d_cplength < idx)
CEGUI_THROW(std::out_of_range("Index is out of range for CEGUI::String"));
if (len == npos)
len = d_cplength;
return encode(&ptr()[idx], buf, npos, len);
}
//////////////////////////////////////////////////////////////////////////
// UTF8 Encoding length information
//////////////////////////////////////////////////////////////////////////
// return the number of bytes required to hold 'num' code-points, starting at code-point 'idx', of the the string when encoded as utf8 data.
/*!
\brief
Return the number of utf8 code units required to hold an area of the String when encoded as utf8 data
\param num
Maximum number of code points to consider when calculating utf8 encoded size.
\param idx
Index of the first code point to consider when calculating the utf8 encoded size
\return
The number of utf8 code units (bytes) required to hold the specified sub-string when encoded as utf8 data.
\exception std::out_of_range Thrown if \a idx was invalid for this String.
*/
size_type utf8_stream_len(size_type num = npos, size_type idx = 0) const
{
using namespace std;
if (d_cplength < idx)
CEGUI_THROW(out_of_range("Index was out of range for CEGUI::String object"));
size_type maxlen = d_cplength - idx;
return encoded_size(&ptr()[idx], ceguimin(num, maxlen));
}
//////////////////////////////////////////////////////////////////////////
// Assignment Functions
//////////////////////////////////////////////////////////////////////////
/*!
\brief
Assign the value of String \a str to this String
\param str
String object containing the string value to be assigned.
\return
This String after the assignment has happened
*/
String& operator=(const String& str)
{
return assign(str);
}
/*!
\brief
Assign a sub-string of String \a str to this String
\param str
String object containing the string data to be assigned.
\param str_idx
Index of the first code point in \a str that is to be assigned
\param str_num
Maximum number of code points from \a str that are be be assigned
\return
This String after the assignment has happened
\exception std::out_of_range Thrown if str_idx is invalid for \a str
*/
String& assign(const String& str, size_type str_idx = 0, size_type str_num = npos)
{
if (str.d_cplength < str_idx)
CEGUI_THROW(std::out_of_range("Index was out of range for CEGUI::String object"));
if ((str_num == npos) || (str_num > str.d_cplength - str_idx))
str_num = str.d_cplength - str_idx;
grow(str_num);
setlen(str_num);
memcpy(ptr(), &str.ptr()[str_idx], str_num * sizeof(utf32));
return *this;
}
/*!
\brief
Assign the value of std::string \a std_str to this String
\note
The characters of \a std_str are taken to be unencoded data which represent Unicode code points 0x00..0xFF. No translation of
the provided data will occur.
\param std_str
std::string object containing the string value to be assigned.
\return
This String after the assignment has happened
\exception std::length_error Thrown if the resulting String would have been too large.
*/
String& operator=(const std::string& std_str)
{
return assign(std_str);
}
/*!
\brief
Assign a sub-string of std::string \a std_str to this String
\note
The characters of \a std_str are taken to be unencoded data which represent Unicode code points 0x00..0xFF. No translation of
the provided data will occur.
\param std_str
std::string object containing the string value to be assigned.
\param str_idx
Index of the first character of \a std_str to be assigned
\param str_num
Maximum number of characters from \a std_str to be assigned
\return
This String after the assignment has happened
\exception std::out_of_range Thrown if \a str_idx is invalid for \a std_str
\exception std::length_error Thrown if the resulting String would have been too large.
*/
String& assign(const std::string& std_str, size_type str_idx = 0, size_type str_num = npos)
{
if (std_str.size() < str_idx)
CEGUI_THROW(std::out_of_range("Index was out of range for std::string object"));
if ((str_num == npos) || (str_num > (size_type)std_str.size() - str_idx))
str_num = (size_type)std_str.size() - str_idx;
grow(str_num);
setlen(str_num);
while(str_num--)
{
((*this)[str_num]) = static_cast<utf32>(static_cast<unsigned char>(std_str[str_num + str_idx]));
}
return *this;
}
/*!
\brief
Assign to this String the string value represented by the given null-terminated utf8 encoded data
\note
A basic string literal (cast to utf8*) can be passed to this function, provided that the string is
comprised only of code points 0x00..0x7f. The use of extended ASCII characters (with values >0x7f)
would result in incorrect behaviour as the String will attempt to 'decode' the data, with unpredictable
results.
\param utf8_str
Buffer containing valid null-terminated utf8 encoded data
\return
This String after the assignment has happened
\exception std::length_error Thrown if the resulting String would have been too large.
*/
String& operator=(const utf8* utf8_str)
{
return assign(utf8_str, utf_length(utf8_str));
}
/*!
\brief
Assign to this String the string value represented by the given null-terminated utf8 encoded data
\note
A basic string literal (cast to utf8*) can be passed to this function, provided that the string is
comprised only of code points 0x00..0x7f. The use of extended ASCII characters (with values >0x7f)
would result in incorrect behaviour as the String will attempt to 'decode' the data, with unpredictable
results.
\param utf8_str
Buffer containing valid null-terminated utf8 encoded data
\return
This String after the assignment has happened
\exception std::length_error Thrown if the resulting String would have been too large.
*/
String& assign(const utf8* utf8_str)
{
return assign(utf8_str, utf_length(utf8_str));
}
/*!
\brief
Assign to this String the string value represented by the given utf8 encoded data
\note
A basic string literal (cast to utf8*) can be passed to this function, provided that the string is
comprised only of code points 0x00..0x7f. The use of extended ASCII characters (with values >0x7f)
would result in incorrect behaviour as the String will attempt to 'decode' the data, with unpredictable
results.
\param utf8_str
Buffer containing valid utf8 encoded data
\param str_num
Number of code units (not code points) in the buffer pointed to by \a utf8_str
\return
This String after the assignment has happened
\exception std::length_error Thrown if the resulting String would have been too large, or if str_num is 'npos'.
*/
String& assign(const utf8* utf8_str, size_type str_num)
{
if (str_num == npos)
CEGUI_THROW(std::length_error("Length for utf8 encoded string can not be 'npos'"));
size_type enc_sze = encoded_size(utf8_str, str_num);
grow(enc_sze);
encode(utf8_str, ptr(), d_reserve, str_num);
setlen(enc_sze);
return *this;
}
/*!
\brief
Assigns the specified utf32 code point to this String. Result is always a String 1 code point in length.
\param code_point
Valid utf32 Unicode code point to be assigned to the string
\return
This String after assignment
*/
String& operator=(utf32 code_point)
{
return assign(1, code_point);
}
/*!
\brief
Assigns the specified code point repeatedly to the String
\param num
The number of times to assign the code point
\param code_point
Valid utf32 Unicode code point to be assigned to the string
\return
This String after assignment.
\exception std::length_error Thrown if \a num was 'npos'
*/
String& assign(size_type num, utf32 code_point)
{
if (num == npos)
CEGUI_THROW(std::length_error("Code point count can not be 'npos'"));
grow(num);
setlen(num);
utf32* p = ptr();
while(num--)
*p++ = code_point;
return *this;
}
/*!
\brief
Assign to this String the given C-string.
\param c_str
Pointer to a valid C style string.
\return
This String after the assignment has happened
\exception std::length_error Thrown if the resulting String would have been too large.
*/
String& operator=(const char* cstr)
{
return assign(cstr, strlen(cstr));
}
/*!
\brief
Assign to this String the given C-string.
\param c_str
Pointer to a valid C style string.
\return
This String after the assignment has happened
\exception std::length_error Thrown if the resulting String would have been too large.
*/
String& assign(const char* cstr)
{
return assign(cstr, strlen(cstr));
}
/*!
\brief
Assign to this String a number of chars from a char array.
\param chars
char array.
\param chars_len
Number of chars to be assigned.
\return
This String after the assignment has happened
\exception std::length_error Thrown if the resulting String would have been too large.
*/
String& assign(const char* chars, size_type chars_len)
{
grow(chars_len);
utf32* pt = ptr();
for (size_type i = 0; i < chars_len; ++i)
{
*pt++ = static_cast<utf32>(static_cast<unsigned char>(*chars++));
}
setlen(chars_len);
return *this;
}
/*!
\brief
Swaps the value of this String with the given String \a str
\param str
String object whos value is to be swapped with this String.
\return
Nothing
*/
void swap(String& str)
{
size_type temp_len = d_cplength;
d_cplength = str.d_cplength;
str.d_cplength = temp_len;
size_type temp_res = d_reserve;
d_reserve = str.d_reserve;
str.d_reserve = temp_res;
utf32* temp_buf = d_buffer;
d_buffer = str.d_buffer;
str.d_buffer = temp_buf;
// see if we need to swap 'quick buffer' data
if (temp_res <= CEGUI_STR_QUICKBUFF_SIZE)
{
utf32 temp_qbf[CEGUI_STR_QUICKBUFF_SIZE];
memcpy(temp_qbf, d_quickbuff, CEGUI_STR_QUICKBUFF_SIZE * sizeof(utf32));
memcpy(d_quickbuff, str.d_quickbuff, CEGUI_STR_QUICKBUFF_SIZE * sizeof(utf32));
memcpy(str.d_quickbuff, temp_qbf, CEGUI_STR_QUICKBUFF_SIZE * sizeof(utf32));
}
}
//////////////////////////////////////////////////////////////////////////
// Appending Functions
//////////////////////////////////////////////////////////////////////////
/*!
\brief
Appends the String \a str
\param str
String object that is to be appended
\return
This String after the append operation
\exception std::length_error Thrown if resulting String would be too large.
*/
String& operator+=(const String& str)
{
return append(str);
}
/*!
\brief
Appends a sub-string of the String \a str
\param str
String object containing data to be appended
\param str_idx
Index of the first code point to be appended
\param str_num
Maximum number of code points to be appended
\return
This String after the append operation
\exception std::out_of_range Thrown if \a str_idx is invalid for \a str.
\exception std::length_error Thrown if resulting String would be too large.
*/
String& append(const String& str, size_type str_idx = 0, size_type str_num = npos)
{
if (str.d_cplength < str_idx)
CEGUI_THROW(std::out_of_range("Index is out of range for CEGUI::String"));
if ((str_num == npos) || (str_num > str.d_cplength - str_idx))
str_num = str.d_cplength - str_idx;
grow(d_cplength + str_num);
memcpy(&ptr()[d_cplength], &str.ptr()[str_idx], str_num * sizeof(utf32));
setlen(d_cplength + str_num);
return *this;
}
/*!
\brief
Appends the std::string \a std_str
\param std_str
std::string object that is to be appended
\note
The characters of \a std_str are taken to be unencoded data which represent Unicode code points 0x00..0xFF. No translation of
the provided data will occur.
\return
This String after the append operation
\exception std::length_error Thrown if resulting String would be too large.
*/
String& operator+=(const std::string& std_str)
{
return append(std_str);
}
/*!
\brief
Appends a sub-string of the std::string \a std_str
\param std_str
std::string object containing data to be appended
\note
The characters of \a std_str are taken to be unencoded data which represent Unicode code points 0x00..0xFF. No translation of
the provided data will occur.
\param str_idx
Index of the first character to be appended
\param str_num
Maximum number of characters to be appended
\return
This String after the append operation
\exception std::out_of_range Thrown if \a str_idx is invalid for \a std_str.
\exception std::length_error Thrown if resulting String would be too large.
*/
String& append(const std::string& std_str, size_type str_idx = 0, size_type str_num = npos)
{
if (std_str.size() < str_idx)
CEGUI_THROW(std::out_of_range("Index is out of range for std::string"));
if ((str_num == npos) || (str_num > (size_type)std_str.size() - str_idx))
str_num = (size_type)std_str.size() - str_idx;
size_type newsze = d_cplength + str_num;
grow(newsze);
utf32* pt = &ptr()[newsze-1];
while(str_num--)
*pt-- = static_cast<utf32>(static_cast<unsigned char>(std_str[str_num]));
setlen(newsze);
return *this;
}
/*!
\brief
Appends to the String the null-terminated utf8 encoded data in the buffer utf8_str.
\param utf8_str
buffer holding the null-terminated utf8 encoded data that is to be appended
\note
A basic string literal (cast to utf8*) can be passed to this function, provided that the string is
comprised only of code points 0x00..0x7f. The use of extended ASCII characters (with values >0x7f)
would result in incorrect behaviour as the String will attempt to 'decode' the data, with unpredictable
results.
\return
This String after the append operation
\exception std::length_error Thrown if resulting String would be too large.
*/
String& operator+=(const utf8* utf8_str)
{
return append(utf8_str, utf_length(utf8_str));
}
/*!
\brief
Appends to the String the null-terminated utf8 encoded data in the buffer utf8_str.
\param utf8_str
Buffer holding the null-terminated utf8 encoded data that is to be appended
\note
A basic string literal (cast to utf8*) can be passed to this function, provided that the string is
comprised only of code points 0x00..0x7f. The use of extended ASCII characters (with values >0x7f)
would result in incorrect behaviour as the String will attempt to 'decode' the data, with unpredictable
results.
\return
This String after the append operation
\exception std::length_error Thrown if resulting String would be too large.
*/
String& append(const utf8* utf8_str)
{
return append(utf8_str, utf_length(utf8_str));
}
/*!
\brief
Appends to the String the utf8 encoded data in the buffer utf8_str.
\param utf8_str
Buffer holding the utf8 encoded data that is to be appended
\note
A basic string literal (cast to utf8*) can be passed to this function, provided that the string is
comprised only of code points 0x00..0x7f. The use of extended ASCII characters (with values >0x7f)
would result in incorrect behaviour as the String will attempt to 'decode' the data, with unpredictable
results.
\param len
Number of code units (not code points) in the buffer to be appended
\return
This String after the append operation
\exception std::length_error Thrown if resulting String would be too large, or if \a len was 'npos'
*/
String& append(const utf8* utf8_str, size_type len)
{
if (len == npos)
CEGUI_THROW(std::length_error("Length for utf8 encoded string can not be 'npos'"));
size_type encsz = encoded_size(utf8_str, len);
size_type newsz = d_cplength + encsz;
grow(newsz);
encode(utf8_str, &ptr()[d_cplength], encsz, len);
setlen(newsz);
return *this;
}
/*!
\brief
Appends a single code point to the string
\param code_point
utf32 Unicode code point that is to be appended
\return
This String after the append operation
\exception std::length_error Thrown if resulting String would be too long.
*/
String& operator+=(utf32 code_point)
{
return append(1, code_point);
}
/*!
\brief
Appends a single code point multiple times to the string
\param num
Number of copies of the code point to be appended
\param code_point
utf32 Unicode code point that is to be appended
\return
This String after the append operation
\exception std::length_error Thrown if resulting String would be too long, or if \a num was 'npos'.
*/
String& append(size_type num, utf32 code_point)
{
if (num == npos)
CEGUI_THROW(std::length_error("Code point count can not be 'npos'"));
size_type newsz = d_cplength + num;
grow(newsz);
utf32* p = &ptr()[d_cplength];
while(num--)
*p++ = code_point;
setlen(newsz);
return *this;
}
/*!
\brief
Appends a single code point to the string
\param code_point
utf32 Unicode code point that is to be appended
\return
Nothing
\exception std::length_error Thrown if resulting String would be too long.
*/
void push_back(utf32 code_point)
{
append(1, code_point);
}
/*!
\brief
Appends the code points in the reange [beg, end)
\param beg
Iterator describing the start of the range to be appended
\param end
Iterator describing the (exclusive) end of the range to be appended.
\return
This String after the append operation
\exception std::length_error Thrown if the resulting string would be too large.
*/
String& append(const_iterator iter_beg, const_iterator iter_end)
{
return replace(end(), end(), iter_beg, iter_end);
}
/*!
\brief
Appends to the String the given c-string.
\param c_str
c-string that is to be appended.
\return
This String after the append operation
\exception std::length_error Thrown if resulting String would be too large.
*/
String& operator+=(const char* cstr)
{
return append(cstr, strlen(cstr));
}
/*!
\brief
Appends to the String the given c-string.
\param c_str
c-string that is to be appended.
\return
This String after the append operation
\exception std::length_error Thrown if resulting String would be too large.
*/
String& append(const char* cstr)
{
return append(cstr, strlen(cstr));
}
/*!
\brief
Appends to the String chars from the given char array.
\param chars
char array holding the chars that are to be appended
\param chars_len
Number of chars to be appended
\return
This String after the append operation
\exception std::length_error Thrown if resulting String would be too large, or if \a chars_len was 'npos'
*/
String& append(const char* chars, size_type chars_len)
{
if (chars_len == npos)
CEGUI_THROW(std::length_error("Length for char array can not be 'npos'"));
size_type newsz = d_cplength + chars_len;
grow(newsz);
utf32* pt = &ptr()[newsz-1];
while(chars_len--)
*pt-- = static_cast<utf32>(static_cast<unsigned char>(chars[chars_len]));
setlen(newsz);
return *this;
}
//////////////////////////////////////////////////////////////////////////
// Insertion Functions
//////////////////////////////////////////////////////////////////////////
/*!
\brief
Inserts the given String object at the specified position.
\param idx
Index where the string is to be inserted.
\param str
String object that is to be inserted.
\return
This String after the insert.
\exception std::out_of_range Thrown if \a idx is invalid for this String.
\exception std::length_error Thrown if resulting String would be too large.
*/
String& insert(size_type idx, const String& str)
{
return insert(idx, str, 0, npos);
}
/*!
\brief
Inserts a sub-string of the given String object at the specified position.
\param idx
Index where the string is to be inserted.
\param str
String object containing data to be inserted.
\param str_idx
Index of the first code point from \a str to be inserted.
\param str_num
Maximum number of code points from \a str to be inserted.
\return
This String after the insert.
\exception std::out_of_range Thrown if \a idx or \a str_idx are out of range.
\exception std::length_error Thrown if resulting String would be too large.
*/
String& insert(size_type idx, const String& str, size_type str_idx, size_type str_num)
{
if ((d_cplength < idx) || (str.d_cplength < str_idx))
CEGUI_THROW(std::out_of_range("Index is out of range for CEGUI::String"));
if ((str_num == npos) || (str_num > str.d_cplength - str_idx))
str_num = str.d_cplength - str_idx;
size_type newsz = d_cplength + str_num;
grow(newsz);
memmove(&ptr()[idx + str_num], &ptr()[idx], (d_cplength - idx) * sizeof(utf32));
memcpy(&ptr()[idx], &str.ptr()[str_idx], str_num * sizeof(utf32));
setlen(newsz);
return *this;
}
/*!
\brief
Inserts the given std::string object at the specified position.
\param idx
Index where the std::string is to be inserted.
\param std_str
std::string object that is to be inserted.
\note
The characters of \a std_str are taken to be unencoded data which represent Unicode code points 0x00..0xFF. No translation of
the provided data will occur.
\return
This String after the insert.
\exception std::out_of_range Thrown if \a idx is invalid for this String.
\exception std::length_error Thrown if resulting String would be too large.
*/
String& insert(size_type idx, const std::string& std_str)
{
return insert(idx, std_str, 0, npos);
}
/*!
\brief
Inserts a sub-string of the given std::string object at the specified position.
\param idx
Index where the string is to be inserted.
\param std_str
std::string object containing data to be inserted.
\note
The characters of \a std_str are taken to be unencoded data which represent Unicode code points 0x00..0xFF. No translation of
the provided data will occur.
\param str_idx
Index of the first character from \a std_str to be inserted.
\param str_num
Maximum number of characters from \a str to be inserted.
\return
This String after the insert.
\exception std::out_of_range Thrown if \a idx or \a str_idx are out of range.
\exception std::length_error Thrown if resulting String would be too large.
*/
String& insert(size_type idx, const std::string& std_str, size_type str_idx, size_type str_num)
{
if (d_cplength < idx)
CEGUI_THROW(std::out_of_range("Index is out of range for CEGUI::String"));
if (std_str.size() < str_idx)
CEGUI_THROW(std::out_of_range("Index is out of range for std::string"));
if ((str_num == npos) || (str_num > (size_type)std_str.size() - str_idx))
str_num = (size_type)std_str.size() - str_idx;
size_type newsz = d_cplength + str_num;
grow(newsz);
memmove(&ptr()[idx + str_num], &ptr()[idx], (d_cplength - idx) * sizeof(utf32));
utf32* pt = &ptr()[idx + str_num - 1];
while(str_num--)
*pt-- = static_cast<utf32>(static_cast<unsigned char>(std_str[str_idx + str_num]));
setlen(newsz);
return *this;
}
/*!
\brief
Inserts the given null-terminated utf8 encoded data at the specified position.
\param idx
Index where the data is to be inserted.
\param utf8_str
Buffer containing the null-terminated utf8 encoded data that is to be inserted.
\note
A basic string literal (cast to utf8*) can be passed to this function, provided that the string is
comprised only of code points 0x00..0x7f. The use of extended ASCII characters (with values >0x7f)
would result in incorrect behaviour as the String will attempt to 'decode' the data, with unpredictable
results.
\return
This String after the insert.
\exception std::out_of_range Thrown if \a idx is invalid for this String.
\exception std::length_error Thrown if resulting String would be too large.
*/
String& insert(size_type idx, const utf8* utf8_str)
{
return insert(idx, utf8_str, utf_length(utf8_str));
}
/*!
\brief
Inserts the given utf8 encoded data at the specified position.
\param idx
Index where the data is to be inserted.
\param utf8_str
Buffer containing the utf8 encoded data that is to be inserted.
\note
A basic string literal (cast to utf8*) can be passed to this function, provided that the string is
comprised only of code points 0x00..0x7f. The use of extended ASCII characters (with values >0x7f)
would result in incorrect behaviour as the String will attempt to 'decode' the data, with unpredictable
results.
\param len
Length of the data to be inserted in uf8 code units (not code points)
\return
This String after the insert.
\exception std::out_of_range Thrown if \a idx is invalid for this String.
\exception std::length_error Thrown if resulting String would be too large, or if \a len is 'npos'
*/
String& insert(size_type idx, const utf8* utf8_str, size_type len)
{
if (d_cplength < idx)
CEGUI_THROW(std::out_of_range("Index is out of range for CEGUI::String"));
if (len == npos)
CEGUI_THROW(std::length_error("Length of utf8 encoded string can not be 'npos'"));
size_type encsz = encoded_size(utf8_str, len);
size_type newsz = d_cplength + encsz;
grow(newsz);
memmove(&ptr()[idx + encsz], &ptr()[idx], (d_cplength - idx) * sizeof(utf32));
encode(utf8_str, &ptr()[idx], encsz, len);
setlen(newsz);
return *this;
}
/*!
\brief
Inserts a code point multiple times into the String
\param idx
Index where the code point(s) are to be inserted
\param num
The number of times to insert the code point
\param code_point
The utf32 code point that is to be inserted
\return
This String after the insertion.
\exception std::out_of_range Thrown if \a idx is invalid for this String.
\exception std::length_error Thrown if resulting String would be too large, or if \a num is 'npos'
*/
String& insert(size_type idx, size_type num, utf32 code_point)
{
if (d_cplength < idx)
CEGUI_THROW(std::out_of_range("Index is out of range for CEGUI::String"));
if (num == npos)
CEGUI_THROW(std::length_error("Code point count can not be 'npos'"));
size_type newsz = d_cplength + num;
grow(newsz);
memmove(&ptr()[idx + num], &ptr()[idx], (d_cplength - idx) * sizeof(utf32));
utf32* pt = &ptr()[idx + num - 1];
while(num--)
*pt-- = code_point;
setlen(newsz);
return *this;
}
/*!
\brief
Inserts a code point multiple times into the String
\param pos
Iterator describing the position where the code point(s) are to be inserted
\param num
The number of times to insert the code point
\param code_point
The utf32 code point that is to be inserted
\return
This String after the insertion.
\exception std::length_error Thrown if resulting String would be too large, or if \a num is 'npos'
*/
void insert(iterator pos, size_type num, utf32 code_point)
{
insert(safe_iter_dif(pos, begin()), num, code_point);
}
/*!
\brief
Inserts a single code point into the String
\param pos
Iterator describing the position where the code point is to be inserted
\param code_point
The utf32 code point that is to be inserted
\return
This String after the insertion.
\exception std::length_error Thrown if resulting String would be too large.
*/
iterator insert(iterator pos, utf32 code_point)
{
insert(pos, 1, code_point);
return pos;
}
/*!
\brief
Inserts code points specified by the range [beg, end).
\param pos
Iterator describing the position where the data is to be inserted
\param beg
Iterator describing the begining of the range to be inserted
\param end
Iterator describing the (exclusive) end of the range to be inserted.
\return
Nothing.
\exception std::length_error Thrown if resulting String would be too large.
*/
void insert(iterator iter_pos, const_iterator iter_beg, const_iterator iter_end)
{
replace(iter_pos, iter_pos, iter_beg, iter_end);
}
/*!
\brief
Inserts the given c-string at the specified position.
\param idx
Index where the c-string is to be inserted.
\param c_str
c-string that is to be inserted.
\return
This String after the insert.
\exception std::out_of_range Thrown if \a idx is invalid for this String.
\exception std::length_error Thrown if resulting String would be too large.
*/
String& insert(size_type idx, const char* cstr)
{
return insert(idx, cstr, strlen(cstr));
}
/*!
\brief
Inserts chars from the given char array at the specified position.
\param idx
Index where the data is to be inserted.
\param chars
char array containing the chars that are to be inserted.
\param chars_len
Length of the char array to be inserted.
\return
This String after the insert.
\exception std::out_of_range Thrown if \a idx is invalid for this String.
\exception std::length_error Thrown if resulting String would be too large, or if \a chars_len is 'npos'
*/
String& insert(size_type idx, const char* chars, size_type chars_len)
{
if (d_cplength < idx)
CEGUI_THROW(std::out_of_range("Index is out of range for CEGUI::String"));
if (chars_len == npos)
CEGUI_THROW(std::length_error("Length of char array can not be 'npos'"));
size_type newsz = d_cplength + chars_len;
grow(newsz);
memmove(&ptr()[idx + chars_len], &ptr()[idx], (d_cplength - idx) * sizeof(utf32));
utf32* pt = &ptr()[idx + chars_len - 1];
while(chars_len--)
*pt-- = static_cast<utf32>(static_cast<unsigned char>(chars[chars_len]));
setlen(newsz);
return *this;
}
//////////////////////////////////////////////////////////////////////////
// Erasing characters
//////////////////////////////////////////////////////////////////////////
/*!
\brief
Removes all data from the String
\return
Nothing
*/
void clear(void)
{
setlen(0);
trim();
}
/*!
\brief
Removes all data from the String
\return
The empty String (*this)
*/
String& erase(void)
{
clear();
return *this;
}
/*!
\brief
Erase a single code point from the string
\param idx
The index of the code point to be removed.
\return
This String after the erase operation
\exception std::out_of_range Thrown if \a idx is invalid for this String.
*/
String& erase(size_type idx)
{
return erase(idx, 1);
}
/*!
\brief
Erase a range of code points
\param idx
Index of the first code point to be removed.
\param len
Maximum number of code points to be removed.
\return
This String after the erase operation.
\exception std::out_of_range Thrown if \a idx is invalid for this String.
*/
String& erase(size_type idx, size_type len)
{
// cover the no-op case.
if (len == 0)
return *this;
if (d_cplength <= idx)
CEGUI_THROW(std::out_of_range("Index is out of range for CEGUI::String"));
if (len == npos)
len = d_cplength - idx;
size_type newsz = d_cplength - len;
memmove(&ptr()[idx], &ptr()[idx + len], (d_cplength - idx - len) * sizeof(utf32));
setlen(newsz);
return *this;
}
/*!
\brief
Erase the code point described by the given iterator
\param pos
Iterator describing the code point to be erased
\return
This String after the erase operation.
*/
String& erase(iterator pos)
{
return erase(safe_iter_dif(pos, begin()), 1);
}
/*!
\brief
Erase a range of code points described by the iterators [beg, end).
\param beg
Iterator describing the postion of the beginning of the range to erase
\param end
Iterator describing the postion of the (exclusive) end of the range to erase
\return
This String after the erase operation.
*/
String& erase(iterator iter_beg, iterator iter_end)
{
return erase(safe_iter_dif(iter_beg, begin()), safe_iter_dif(iter_end, iter_beg));
}
//////////////////////////////////////////////////////////////////////////
// Resizing
//////////////////////////////////////////////////////////////////////////
/*!
\brief
Resizes the String either by inserting default utf32 code points to make it larger, or by truncating to make it smaller
\param num
The length, in code points, that the String is to be made.
\return
Nothing.
\exception std::length_error Thrown if the String would be too large.
*/
void resize(size_type num)
{
resize(num, utf32());
}
/*!
\brief
Resizes the String either by inserting the given utf32 code point to make it larger, or by truncating to make it smaller
\param num
The length, in code points, that the String is to be made.
\param code_point
The utf32 code point that should be used when majing the String larger
\return
Nothing.
\exception std::length_error Thrown if the String would be too large.
*/
void resize(size_type num, utf32 code_point)
{
if (num < d_cplength)
{
setlen(num);
}
else
{
append(num - d_cplength, code_point);
}
}
//////////////////////////////////////////////////////////////////////////
// Replacing Characters
//////////////////////////////////////////////////////////////////////////
/*!
\brief
Replace code points in the String with the specified String object
\param idx
Index of the first code point to be replaced
\param len
Maximum number of code points to be replaced (if this is 0, operation is an insert at position \a idx)
\param str
The String object that is to replace the specified code points
\return
This String after the replace operation
\exception std::out_of_range Thrown if \a idx is invalid for this String
\exception std::length_error Thrown if the resulting String would be too large.
*/
String& replace(size_type idx, size_type len, const String& str)
{
return replace(idx, len, str, 0, npos);
}
/*!
\brief
Replace the code points in the range [beg, end) with the specified String object
\note
If \a beg == \a end, the operation is a insert at iterator position \a beg
\param beg
Iterator describing the start of the range to be replaced
\param end
Iterator describing the (exclusive) end of the range to be replaced.
\param str
The String object that is to replace the specified range of code points
\return
This String after the replace operation
\exception std::length_error Thrown if the resulting String would be too large.
*/
String& replace(iterator iter_beg, iterator iter_end, const String& str)
{
return replace(safe_iter_dif(iter_beg, begin()), safe_iter_dif(iter_end, iter_beg), str, 0, npos);
}
/*!
\brief
Replace code points in the String with a specified sub-string of a given String object.
\param idx
Index of the first code point to be replaced
\param len
Maximum number of code points to be replaced. If this is 0, the operation is an insert at position \a idx.
\param str
String object containing the data that will replace the specified range of code points
\param str_idx
Index of the first code point of \a str that is to replace the specified code point range
\param str_num
Maximum number of code points of \a str that are to replace the specified code point range
\return
This String after the replace operation
\exception std::out_of_range Thrown if either \a idx, or \a str_idx are invalid
\exception std::length_error Thrown if the resulting String would have been too large.
*/
String& replace(size_type idx, size_type len, const String& str, size_type str_idx, size_type str_num)
{
if ((d_cplength < idx) || (str.d_cplength < str_idx))
CEGUI_THROW(std::out_of_range("Index is out of range for CEGUI::String"));
if (((str_idx + str_num) > str.d_cplength) || (str_num == npos))
str_num = str.d_cplength - str_idx;
if (((len + idx) > d_cplength) || (len == npos))
len = d_cplength - idx;
size_type newsz = d_cplength + str_num - len;
grow(newsz);
if ((idx + len) < d_cplength)
memmove(&ptr()[idx + str_num], &ptr()[len + idx], (d_cplength - idx - len) * sizeof(utf32));
memcpy(&ptr()[idx], &str.ptr()[str_idx], str_num * sizeof(utf32));
setlen(newsz);
return *this;
}
/*!
\brief
Replace code points in the String with the specified std::string object
\param idx
Index of the first code point to be replaced
\param len
Maximum number of code points to be replaced (if this is 0, operation is an insert at position \a idx)
\param std_str
The std::string object that is to replace the specified code points
\note
Characters from \a std_str are considered to represent Unicode code points in the range 0x00..0xFF. No translation of
the encountered data is performed.
\return
This String after the replace operation
\exception std::out_of_range Thrown if \a idx is invalid for this String
\exception std::length_error Thrown if the resulting String would be too large.
*/
String& replace(size_type idx, size_type len, const std::string& std_str)
{
return replace(idx, len, std_str, 0, npos);
}
/*!
\brief
Replace the code points in the range [beg, end) with the specified std::string object
\note
If \a beg == \a end, the operation is a insert at iterator position \a beg
\param beg
Iterator describing the start of the range to be replaced
\param end
Iterator describing the (exclusive) end of the range to be replaced.
\param std_str
The std::string object that is to replace the specified range of code points
\note
Characters from \a std_str are considered to represent Unicode code points in the range 0x00..0xFF. No translation of
the encountered data is performed.
\return
This String after the replace operation
\exception std::length_error Thrown if the resulting String would be too large.
*/
String& replace(iterator iter_beg, iterator iter_end, const std::string& std_str)
{
return replace(safe_iter_dif(iter_beg, begin()), safe_iter_dif(iter_end, iter_beg), std_str, 0, npos);
}
/*!
\brief
Replace code points in the String with a specified sub-string of a given std::string object.
\param idx
Index of the first code point to be replaced
\param len
Maximum number of code points to be replaced. If this is 0, the operation is an insert at position \a idx.
\param std_str
std::string object containing the data that will replace the specified range of code points
\note
Characters from \a std_str are considered to represent Unicode code points in the range 0x00..0xFF. No translation of
the encountered data is performed.
\param str_idx
Index of the first code point of \a std_str that is to replace the specified code point range
\param str_num
Maximum number of code points of \a std_str that are to replace the specified code point range
\return
This String after the replace operation
\exception std::out_of_range Thrown if either \a idx, or \a str_idx are invalid
\exception std::length_error Thrown if the resulting String would have been too large.
*/
String& replace(size_type idx, size_type len, const std::string& std_str, size_type str_idx, size_type str_num)
{
if (d_cplength < idx)
CEGUI_THROW(std::out_of_range("Index is out of range for CEGUI::String"));
if (std_str.size() < str_idx)
CEGUI_THROW(std::out_of_range("Index is out of range for std::string"));
if (((str_idx + str_num) > std_str.size()) || (str_num == npos))
str_num = (size_type)std_str.size() - str_idx;
if (((len + idx) > d_cplength) || (len == npos))
len = d_cplength - idx;
size_type newsz = d_cplength + str_num - len;
grow(newsz);
if ((idx + len) < d_cplength)
memmove(&ptr()[idx + str_num], &ptr()[len + idx], (d_cplength - idx - len) * sizeof(utf32));
utf32* pt = &ptr()[idx + str_num - 1];
while (str_num--)
*pt-- = static_cast<utf32>(static_cast<unsigned char>(std_str[str_idx + str_num]));
setlen(newsz);
return *this;
}
/*!
\brief
Replace code points in the String with the specified null-terminated utf8 encoded data.
\param idx
Index of the first code point to be replaced
\param len
Maximum number of code points to be replaced (if this is 0, operation is an insert at position \a idx)
\param utf8_str
Buffer containing the null-terminated utf8 encoded data that is to replace the specified code points
\note
A basic string literal (cast to utf8*) can be passed to this function, provided that the string is
comprised only of code points 0x00..0x7f. The use of extended ASCII characters (with values >0x7f)
would result in incorrect behaviour as the String will attempt to 'decode' the data, with unpredictable
results.
\return
This String after the replace operation
\exception std::out_of_range Thrown if \a idx is invalid for this String
\exception std::length_error Thrown if the resulting String would be too large.
*/
String& replace(size_type idx, size_type len, const utf8* utf8_str)
{
return replace(idx, len, utf8_str, utf_length(utf8_str));
}
/*!
\brief
Replace the code points in the range [beg, end) with the specified null-terminated utf8 encoded data.
\note
If \a beg == \a end, the operation is a insert at iterator position \a beg
\param beg
Iterator describing the start of the range to be replaced
\param end
Iterator describing the (exclusive) end of the range to be replaced.
\param utf8_str
Buffer containing the null-terminated utf8 encoded data that is to replace the specified range of code points
\note
A basic string literal (cast to utf8*) can be passed to this function, provided that the string is
comprised only of code points 0x00..0x7f. The use of extended ASCII characters (with values >0x7f)
would result in incorrect behaviour as the String will attempt to 'decode' the data, with unpredictable
results.
\return
This String after the replace operation
\exception std::length_error Thrown if the resulting String would be too large.
*/
String& replace(iterator iter_beg, iterator iter_end, const utf8* utf8_str)
{
return replace(iter_beg, iter_end, utf8_str, utf_length(utf8_str));
}
/*!
\brief
Replace code points in the String with the specified utf8 encoded data.
\param idx
Index of the first code point to be replaced
\param len
Maximum number of code points to be replaced (if this is 0, operation is an insert at position \a idx)
\param utf8_str
Buffer containing the null-terminated utf8 encoded data that is to replace the specified code points
\note
A basic string literal (cast to utf8*) can be passed to this function, provided that the string is
comprised only of code points 0x00..0x7f. The use of extended ASCII characters (with values >0x7f)
would result in incorrect behaviour as the String will attempt to 'decode' the data, with unpredictable
results.
\param str_len
Length of the utf8 encoded data in utf8 code units (not code points).
\return
This String after the replace operation
\exception std::out_of_range Thrown if \a idx is invalid for this String
\exception std::length_error Thrown if the resulting String would be too large, or if \a str_len was 'npos'.
*/
String& replace(size_type idx, size_type len, const utf8* utf8_str, size_type str_len)
{
if (d_cplength < idx)
CEGUI_THROW(std::out_of_range("Index is out of range for CEGUI::String"));
if (str_len == npos)
CEGUI_THROW(std::length_error("Length for utf8 encoded string can not be 'npos'"));
if (((len + idx) > d_cplength) || (len == npos))
len = d_cplength - idx;
size_type encsz = encoded_size(utf8_str, str_len);
size_type newsz = d_cplength + encsz - len;
grow(newsz);
if ((idx + len) < d_cplength)
memmove(&ptr()[idx + encsz], &ptr()[len + idx], (d_cplength - idx - len) * sizeof(utf32));
encode(utf8_str, &ptr()[idx], encsz, str_len);
setlen(newsz);
return *this;
}
/*!
\brief
Replace the code points in the range [beg, end) with the specified null-terminated utf8 encoded data.
\note
If \a beg == \a end, the operation is a insert at iterator position \a beg
\param beg
Iterator describing the start of the range to be replaced
\param end
Iterator describing the (exclusive) end of the range to be replaced.
\param utf8_str
Buffer containing the null-terminated utf8 encoded data that is to replace the specified range of code points
\note
A basic string literal (cast to utf8*) can be passed to this function, provided that the string is
comprised only of code points 0x00..0x7f. The use of extended ASCII characters (with values >0x7f)
would result in incorrect behaviour as the String will attempt to 'decode' the data, with unpredictable
results.
\param str_len
Length of the utf8 encoded data in utf8 code units (not code points).
\return
This String after the replace operation
\exception std::length_error Thrown if the resulting String would be too large, or if \a str_len was 'npos'.
*/
String& replace(iterator iter_beg, iterator iter_end, const utf8* utf8_str, size_type str_len)
{
return replace(safe_iter_dif(iter_beg, begin()), safe_iter_dif(iter_end, iter_beg), utf8_str, str_len);
}
/*!
\brief
Replaces a specified range of code points with occurrences of a given code point
\param idx
Index of the first code point to be replaced
\param len
Maximum number of code points to replace. If this is 0 the operation is an insert
\param num
Number of occurrences of \a code_point that are to replace the specified range of code points
\param code_point
Code point that is to be used when replacing the specified range of code points
\return
This String after the replace operation.
\exception std::out_of_range Thrown if \a idx is invalid for this String
\exception std::length_error Thrown if resulting String would have been too long, or if \a num was 'npos'.
*/
String& replace(size_type idx, size_type len, size_type num, utf32 code_point)
{
if (d_cplength < idx)
CEGUI_THROW(std::out_of_range("Index is out of range for CEGUI::String"));
if (num == npos)
CEGUI_THROW(std::length_error("Code point count can not be 'npos'"));
if (((len + idx) > d_cplength) || (len == npos))
len = d_cplength - idx;
size_type newsz = d_cplength + num - len;
grow(newsz);
if ((idx + len) < d_cplength)
memmove(&ptr()[idx + num], &ptr()[len + idx], (d_cplength - idx - len) * sizeof(utf32));
utf32* pt = &ptr()[idx + num - 1];
while (num--)
*pt-- = code_point;
setlen(newsz);
return *this;
}
/*!
\brief
Replace the code points in the range [beg, end) with occurrences of a given code point
\note
If \a beg == \a end, the operation is an insert at iterator position \a beg
\param beg
Iterator describing the start of the range to be replaced
\param end
Iterator describing the (exclusive) end of the range to be replaced.
\param num
Number of occurrences of \a code_point that are to replace the specified range of code points
\param code_point
Code point that is to be used when replacing the specified range of code points
\return
This String after the replace operation
\exception std::length_error Thrown if resulting String would have been too long, or if \a num was 'npos'.
*/
String& replace(iterator iter_beg, iterator iter_end, size_type num, utf32 code_point)
{
return replace(safe_iter_dif(iter_beg, begin()), safe_iter_dif(iter_end, iter_beg), num, code_point);
}
/*!
\brief
Replace the code points in the range [beg, end) with code points from the range [newBeg, newEnd).
\note
If \a beg == \a end, the operation is an insert at iterator position \a beg
\param beg
Iterator describing the start of the range to be replaced
\param end
Iterator describing the (exclusive) end of the range to be replaced.
\param newBeg
Iterator describing the beginning of the range to insert.
\param newEnd
Iterator describing the (exclusive) end of the range to insert.
\return
This String after the insert operation.
\exception std::length_error Thrown if the resulting string would be too long.
*/
String& replace(iterator iter_beg, iterator iter_end, const_iterator iter_newBeg, const_iterator iter_newEnd)
{
if (iter_newBeg == iter_newEnd)
{
erase(safe_iter_dif(iter_beg, begin()), safe_iter_dif(iter_end, iter_beg));
}
else
{
size_type str_len = safe_iter_dif(iter_newEnd, iter_newBeg);
size_type idx = safe_iter_dif(iter_beg, begin());
size_type len = safe_iter_dif(iter_end, iter_beg);
if ((len + idx) > d_cplength)
len = d_cplength - idx;
size_type newsz = d_cplength + str_len - len;
grow(newsz);
if ((idx + len) < d_cplength)
memmove(&ptr()[idx + str_len], &ptr()[len + idx], (d_cplength - idx - len) * sizeof(utf32));
memcpy(&ptr()[idx], iter_newBeg.d_ptr, str_len * sizeof(utf32));
setlen(newsz);
}
return *this;
}
/*!
\brief
Replace code points in the String with the specified c-string.
\param idx
Index of the first code point to be replaced
\param len
Maximum number of code points to be replaced (if this is 0, operation is an insert at position \a idx)
\param c_str
c-string that is to replace the specified code points
\return
This String after the replace operation
\exception std::out_of_range Thrown if \a idx is invalid for this String
\exception std::length_error Thrown if the resulting String would be too large.
*/
String& replace(size_type idx, size_type len, const char* cstr)
{
return replace(idx, len, cstr, strlen(cstr));
}
/*!
\brief
Replace the code points in the range [beg, end) with the specified c-string.
\note
If \a beg == \a end, the operation is a insert at iterator position \a beg
\param beg
Iterator describing the start of the range to be replaced
\param end
Iterator describing the (exclusive) end of the range to be replaced.
\param c_str
c-string that is to replace the specified range of code points
\return
This String after the replace operation
\exception std::length_error Thrown if the resulting String would be too large.
*/
String& replace(iterator iter_beg, iterator iter_end, const char* cstr)
{
return replace(iter_beg, iter_end, cstr, strlen(cstr));
}
/*!
\brief
Replace code points in the String with chars from the given char array.
\param idx
Index of the first code point to be replaced
\param len
Maximum number of code points to be replaced (if this is 0, operation is an insert at position \a idx)
\param chars
char array containing the cars that are to replace the specified code points
\param chars_len
Number of chars in the char array.
\return
This String after the replace operation
\exception std::out_of_range Thrown if \a idx is invalid for this String
\exception std::length_error Thrown if the resulting String would be too large, or if \a chars_len was 'npos'.
*/
String& replace(size_type idx, size_type len, const char* chars, size_type chars_len)
{
if (d_cplength < idx)
CEGUI_THROW(std::out_of_range("Index is out of range for CEGUI::String"));
if (chars_len == npos)
CEGUI_THROW(std::length_error("Length for the char array can not be 'npos'"));
if (((len + idx) > d_cplength) || (len == npos))
len = d_cplength - idx;
size_type newsz = d_cplength + chars_len - len;
grow(newsz);
if ((idx + len) < d_cplength)
memmove(&ptr()[idx + chars_len], &ptr()[len + idx], (d_cplength - idx - len) * sizeof(utf32));
utf32* pt = &ptr()[idx + chars_len - 1];
while (chars_len--)
*pt-- = static_cast<utf32>(static_cast<unsigned char>(chars[chars_len]));
setlen(newsz);
return *this;
}
/*!
\brief
Replace the code points in the range [beg, end) with chars from the given char array.
\note
If \a beg == \a end, the operation is a insert at iterator position \a beg
\param beg
Iterator describing the start of the range to be replaced
\param end
Iterator describing the (exclusive) end of the range to be replaced.
\param chars
char array containing the chars that are to replace the specified range of code points
\param chars_len
Number of chars in the char array.
\return
This String after the replace operation
\exception std::length_error Thrown if the resulting String would be too large, or if \a chars_len was 'npos'.
*/
String& replace(iterator iter_beg, iterator iter_end, const char* chars, size_type chars_len)
{
return replace(safe_iter_dif(iter_beg, begin()), safe_iter_dif(iter_end, iter_beg), chars, chars_len);
}
//////////////////////////////////////////////////////////////////////////
// Find a code point
//////////////////////////////////////////////////////////////////////////
/*!
\brief
Search forwards for a given code point
\param code_point
The utf32 code point to search for
\param idx
Index of the code point where the search is to start.
\return
- Index of the first occurrence of \a code_point travelling forwards from \a idx.
- npos if the code point could not be found
*/
size_type find(utf32 code_point, size_type idx = 0) const
{
if (idx < d_cplength)
{
const utf32* pt = &ptr()[idx];
while (idx < d_cplength)
{
if (*pt++ == code_point)
return idx;
++idx;
}
}
return npos;
}
/*!
\brief
Search backwards for a given code point
\param code_point
The utf32 code point to search for
\param idx
Index of the code point where the search is to start.
\return
- Index of the first occurrence of \a code_point travelling backwards from \a idx.
- npos if the code point could not be found
*/
size_type rfind(utf32 code_point, size_type idx = npos) const
{
if (idx >= d_cplength)
idx = d_cplength - 1;
if (d_cplength > 0)
{
const utf32* pt = &ptr()[idx];
do
{
if (*pt-- == code_point)
return idx;
} while (idx-- != 0);
}
return npos;
}
//////////////////////////////////////////////////////////////////////////
// Find a substring
//////////////////////////////////////////////////////////////////////////
/*!
\brief
Search forwards for a sub-string
\param str
String object describing the sub-string to search for
\param idx
Index of the code point where the search is to start
\return
- Index of the first occurrence of sub-string \a str travelling forwards from \a idx.
- npos if the sub-string could not be found
*/
size_type find(const String& str, size_type idx = 0) const
{
if ((str.d_cplength == 0) && (idx < d_cplength))
return idx;
if (idx < d_cplength)
{
// loop while search string could fit in to search area
while (d_cplength - idx >= str.d_cplength)
{
if (0 == compare(idx, str.d_cplength, str))
return idx;
++idx;
}
}
return npos;
}
/*!
\brief
Search backwards for a sub-string
\param str
String object describing the sub-string to search for
\param idx
Index of the code point where the search is to start
\return
- Index of the first occurrence of sub-string \a str travelling backwards from \a idx.
- npos if the sub-string could not be found
*/
size_type rfind(const String& str, size_type idx = npos) const
{
if (str.d_cplength == 0)
return (idx < d_cplength) ? idx : d_cplength;
if (str.d_cplength <= d_cplength)
{
if (idx > (d_cplength - str.d_cplength))
idx = d_cplength - str.d_cplength;
do
{
if (0 == compare(idx, str.d_cplength, str))
return idx;
} while (idx-- != 0);
}
return npos;
}
/*!
\brief
Search forwards for a sub-string
\param std_str
std::string object describing the sub-string to search for
\note
Characters from \a std_str are considered to represent Unicode code points in the range 0x00..0xFF. No translation of
the encountered data is performed.
\param idx
Index of the code point where the search is to start
\return
- Index of the first occurrence of sub-string \a std_str travelling forwards from \a idx.
- npos if the sub-string could not be found
*/
size_type find(const std::string& std_str, size_type idx = 0) const
{
std::string::size_type sze = std_str.size();
if ((sze == 0) && (idx < d_cplength))
return idx;
if (idx < d_cplength)
{
// loop while search string could fit in to search area
while (d_cplength - idx >= sze)
{
if (0 == compare(idx, (size_type)sze, std_str))
return idx;
++idx;
}
}
return npos;
}
/*!
\brief
Search backwards for a sub-string
\param std_str
std::string object describing the sub-string to search for
\note
Characters from \a std_str are considered to represent Unicode code points in the range 0x00..0xFF. No translation of
the encountered data is performed.
\param idx
Index of the code point where the search is to start
\return
- Index of the first occurrence of sub-string \a std_str travelling backwards from \a idx.
- npos if the sub-string could not be found
*/
size_type rfind(const std::string& std_str, size_type idx = npos) const
{
std::string::size_type sze = std_str.size();
if (sze == 0)
return (idx < d_cplength) ? idx : d_cplength;
if (sze <= d_cplength)
{
if (idx > (d_cplength - sze))
idx = d_cplength - sze;
do
{
if (0 == compare(idx, (size_type)sze, std_str))
return idx;
} while (idx-- != 0);
}
return npos;
}
/*!
\brief
Search forwards for a sub-string
\param utf8_str
Buffer containing null-terminated utf8 encoded data describing the sub-string to search for
\note
A basic string literal (cast to utf8*) can be passed to this function, provided that the string is
comprised only of code points 0x00..0x7f. The use of extended ASCII characters (with values >0x7f)
would result in incorrect behaviour as the String will attempt to 'decode' the data, with unpredictable
results.
\param idx
Index of the code point where the search is to start
\return
- Index of the first occurrence of sub-string \a utf8_str travelling forwards from \a idx.
- npos if the sub-string could not be found
\exception std::out_of_range Thrown if \a idx is invalid for this String.
*/
size_type find(const utf8* utf8_str, size_type idx = 0) const
{
return find(utf8_str, idx, utf_length(utf8_str));
}
/*!
\brief
Search backwards for a sub-string
\param utf8_str
Buffer containing null-terminated utf8 encoded data describing the sub-string to search for
\note
A basic string literal (cast to utf8*) can be passed to this function, provided that the string is
comprised only of code points 0x00..0x7f. The use of extended ASCII characters (with values >0x7f)
would result in incorrect behaviour as the String will attempt to 'decode' the data, with unpredictable
results.
\param idx
Index of the code point where the search is to start
\return
- Index of the first occurrence of sub-string \a utf8_str travelling backwards from \a idx.
- npos if the sub-string could not be found
\exception std::out_of_range Thrown if \a idx is invalid for this String.
*/
size_type rfind(const utf8* utf8_str, size_type idx = npos) const
{
return rfind(utf8_str, idx, utf_length(utf8_str));
}
/*!
\brief
Search forwards for a sub-string
\param utf8_str
Buffer containing utf8 encoded data describing the sub-string to search for
\note
A basic string literal (cast to utf8*) can be passed to this function, provided that the string is
comprised only of code points 0x00..0x7f. The use of extended ASCII characters (with values >0x7f)
would result in incorrect behaviour as the String will attempt to 'decode' the data, with unpredictable
results.
\param idx
Index of the code point where the search is to start
\param str_len
Length of the utf8 encoded sub-string in utf8 code units (not code points)
\return
- Index of the first occurrence of sub-string \a utf8_str travelling forwards from \a idx.
- npos if the sub-string could not be found
\exception std::length_error Thrown if \a str_len is 'npos'
*/
size_type find(const utf8* utf8_str, size_type idx, size_type str_len) const
{
if (str_len == npos)
CEGUI_THROW(std::length_error("Length for utf8 encoded string can not be 'npos'"));
size_type sze = encoded_size(utf8_str, str_len);
if ((sze == 0) && (idx < d_cplength))
return idx;
if (idx < d_cplength)
{
// loop while search string could fit in to search area
while (d_cplength - idx >= sze)
{
if (0 == compare(idx, sze, utf8_str, sze))
return idx;
++idx;
}
}
return npos;
}
/*!
\brief
Search backwards for a sub-string
\param utf8_str
Buffer containing utf8 encoded data describing the sub-string to search for
\note
A basic string literal (cast to utf8*) can be passed to this function, provided that the string is
comprised only of code points 0x00..0x7f. The use of extended ASCII characters (with values >0x7f)
would result in incorrect behaviour as the String will attempt to 'decode' the data, with unpredictable
results.
\param idx
Index of the code point where the search is to start
\param str_len
Length of the utf8 encoded sub-string in utf8 code units (not code points)
\return
- Index of the first occurrence of sub-string \a utf8_str travelling backwards from \a idx.
- npos if the sub-string could not be found
\exception std::length_error Thrown if \a str_len is 'npos'
*/
size_type rfind(const utf8* utf8_str, size_type idx, size_type str_len) const
{
if (str_len == npos)
CEGUI_THROW(std::length_error("Length for utf8 encoded string can not be 'npos'"));
size_type sze = encoded_size(utf8_str, str_len);
if (sze == 0)
return (idx < d_cplength) ? idx : d_cplength;
if (sze <= d_cplength)
{
if (idx > (d_cplength - sze))
idx = d_cplength - sze;
do
{
if (0 == compare(idx, sze, utf8_str, sze))
return idx;
} while (idx-- != 0);
}
return npos;
}
/*!
\brief
Search forwards for a sub-string
\param c_str
c-string describing the sub-string to search for
\param idx
Index of the code point where the search is to start
\return
- Index of the first occurrence of sub-string \a c_str travelling forwards from \a idx.
- npos if the sub-string could not be found
\exception std::out_of_range Thrown if \a idx is invalid for this String.
*/
size_type find(const char* cstr, size_type idx = 0) const
{
return find(cstr, idx, strlen(cstr));
}
/*!
\brief
Search backwards for a sub-string
\param c_str
c-string describing the sub-string to search for
\param idx
Index of the code point where the search is to start
\return
- Index of the first occurrence of sub-string \a c_str travelling backwards from \a idx.
- npos if the sub-string could not be found
\exception std::out_of_range Thrown if \a idx is invalid for this String.
*/
size_type rfind(const char* cstr, size_type idx = npos) const
{
return rfind(cstr, idx, strlen(cstr));
}
/*!
\brief
Search forwards for a sub-string
\param chars
char array describing the sub-string to search for
\param idx
Index of the code point where the search is to start
\param chars_len
Number of chars in the char array.
\return
- Index of the first occurrence of sub-string \a chars travelling forwards from \a idx.
- npos if the sub-string could not be found
\exception std::length_error Thrown if \a chars_len is 'npos'
*/
size_type find(const char* chars, size_type idx, size_type chars_len) const
{
if (chars_len == npos)
CEGUI_THROW(std::length_error("Length for char array can not be 'npos'"));
if ((chars_len == 0) && (idx < d_cplength))
return idx;
if (idx < d_cplength)
{
// loop while search string could fit in to search area
while (d_cplength - idx >= chars_len)
{
if (0 == compare(idx, chars_len, chars, chars_len))
return idx;
++idx;
}
}
return npos;
}
/*!
\brief
Search backwards for a sub-string
\param chars
char array describing the sub-string to search for
\param idx
Index of the code point where the search is to start
\param chars_len
Number of chars in the char array.
\return
- Index of the first occurrence of sub-string \a chars travelling backwards from \a idx.
- npos if the sub-string could not be found
\exception std::length_error Thrown if \a chars_len is 'npos'
*/
size_type rfind(const char* chars, size_type idx, size_type chars_len) const
{
if (chars_len == npos)
CEGUI_THROW(std::length_error("Length for char array can not be 'npos'"));
if (chars_len == 0)
return (idx < d_cplength) ? idx : d_cplength;
if (chars_len <= d_cplength)
{
if (idx > (d_cplength - chars_len))
idx = d_cplength - chars_len;
do
{
if (0 == compare(idx, chars_len, chars, chars_len))
return idx;
} while (idx-- != 0);
}
return npos;
}
//////////////////////////////////////////////////////////////////////////
// Find first of different code-points
//////////////////////////////////////////////////////////////////////////
/*!
\brief
Find the first occurrence of one of a set of code points.
\param str
String object describing the set of code points.
\param idx
Index of the start point for the search
\return
- Index of the first occurrence of any one of the code points in \a str starting from from \a idx.
- npos if none of the code points in \a str were found.
*/
size_type find_first_of(const String& str, size_type idx = 0) const
{
if (idx < d_cplength)
{
const utf32* pt = &ptr()[idx];
do
{
if (npos != str.find(*pt++))
return idx;
} while (++idx != d_cplength);
}
return npos;
}
/*!
\brief
Find the first code point that is not one of a set of code points.
\param str
String object describing the set of code points.
\param idx
Index of the start point for the search
\return
- Index of the first code point that does not match any one of the code points in \a str starting from from \a idx.
- npos if all code points matched one of the code points in \a str.
*/
size_type find_first_not_of(const String& str, size_type idx = 0) const
{
if (idx < d_cplength)
{
const utf32* pt = &ptr()[idx];
do
{
if (npos == str.find(*pt++))
return idx;
} while (++idx != d_cplength);
}
return npos;
}
/*!
\brief
Find the first occurrence of one of a set of code points.
\param std_str
std::string object describing the set of code points.
\note
The characters of \a std_str are taken to be unencoded data which represent Unicode code points 0x00..0xFF. No translation of
the provided data will occur.
\param idx
Index of the start point for the search
\return
- Index of the first occurrence of any one of the code points in \a std_str starting from from \a idx.
- npos if none of the code points in \a std_str were found.
*/
size_type find_first_of(const std::string& std_str, size_type idx = 0) const
{
if (idx < d_cplength)
{
const utf32* pt = &ptr()[idx];
do
{
if (npos != find_codepoint(std_str, *pt++))
return idx;
} while (++idx != d_cplength);
}
return npos;
}
/*!
\brief
Find the first code point that is not one of a set of code points.
\param std_str
std::string object describing the set of code points.
\note
The characters of \a std_str are taken to be unencoded data which represent Unicode code points 0x00..0xFF. No translation of
the provided data will occur.
\param idx
Index of the start point for the search
\return
- Index of the first code point that does not match any one of the code points in \a std_str starting from from \a idx.
- npos if all code points matched one of the code points in \a std_str.
*/
size_type find_first_not_of(const std::string& std_str, size_type idx = 0) const
{
if (idx < d_cplength)
{
const utf32* pt = &ptr()[idx];
do
{
if (npos == find_codepoint(std_str, *pt++))
return idx;
} while (++idx != d_cplength);
}
return npos;
}
/*!
\brief
Find the first occurrence of one of a set of code points.
\param utf8_str
Buffer containing null-terminated utf8 encoded data describing the set of code points.
\note
A basic string literal (cast to utf8*) can be passed to this function, provided that the string is
comprised only of code points 0x00..0x7f. The use of extended ASCII characters (with values >0x7f)
would result in incorrect behaviour as the String will attempt to 'decode' the data, with unpredictable
results.
\param idx
Index of the start point for the search
\return
- Index of the first occurrence of any one of the code points in \a utf8_str starting from from \a idx.
- npos if none of the code points in \a utf8_str were found.
\exception std::out_of_range Thrown if \a idx is invalid for this String.
*/
size_type find_first_of(const utf8* utf8_str, size_type idx = 0) const
{
return find_first_of(utf8_str, idx, utf_length(utf8_str));
}
/*!
\brief
Find the first code point that is not one of a set of code points.
\param utf8_str
Buffer containing null-terminated utf8 encoded data describing the set of code points.
\note
A basic string literal (cast to utf8*) can be passed to this function, provided that the string is
comprised only of code points 0x00..0x7f. The use of extended ASCII characters (with values >0x7f)
would result in incorrect behaviour as the String will attempt to 'decode' the data, with unpredictable
results.
\param idx
Index of the start point for the search
\return
- Index of the first code point that does not match any one of the code points in \a utf8_str starting from from \a idx.
- npos if all code points matched one of the code points in \a utf8_str.
\exception std::out_of_range Thrown if \a idx is invalid for this String.
*/
size_type find_first_not_of(const utf8* utf8_str, size_type idx = 0) const
{
return find_first_not_of(utf8_str, idx, utf_length(utf8_str));
}
/*!
\brief
Find the first occurrence of one of a set of code points.
\param utf8_str
Buffer containing utf8 encoded data describing the set of code points.
\note
A basic string literal (cast to utf8*) can be passed to this function, provided that the string is
comprised only of code points 0x00..0x7f. The use of extended ASCII characters (with values >0x7f)
would result in incorrect behaviour as the String will attempt to 'decode' the data, with unpredictable
results.
\param idx
Index of the start point for the search
\param str_len
Length of the utf8 encoded data in utf8 code units (not code points).
\return
- Index of the first occurrence of any one of the code points in \a utf8_str starting from from \a idx.
- npos if none of the code points in \a utf8_str were found.
\exception std::length_error Thrown if \a str_len was 'npos'.
*/
size_type find_first_of(const utf8* utf8_str, size_type idx, size_type str_len) const
{
if (str_len == npos)
CEGUI_THROW(std::length_error("Length for utf8 encoded string can not be 'npos'"));
if (idx < d_cplength)
{
size_type encsze = encoded_size(utf8_str, str_len);
const utf32* pt = &ptr()[idx];
do
{
if (npos != find_codepoint(utf8_str, encsze, *pt++))
return idx;
} while (++idx != d_cplength);
}
return npos;
}
/*!
\brief
Find the first code point that is not one of a set of code points.
\param utf8_str
Buffer containing utf8 encoded data describing the set of code points.
\note
A basic string literal (cast to utf8*) can be passed to this function, provided that the string is
comprised only of code points 0x00..0x7f. The use of extended ASCII characters (with values >0x7f)
would result in incorrect behaviour as the String will attempt to 'decode' the data, with unpredictable
results.
\param idx
Index of the start point for the search
\param str_len
Length of the utf8 encoded data in utf8 code units (not code points).
\return
- Index of the first code point that does not match any one of the code points in \a utf8_str starting from from \a idx.
- npos if all code points matched one of the code points in \a utf8_str.
\exception std::length_error Thrown if \a str_len was 'npos'.
*/
size_type find_first_not_of(const utf8* utf8_str, size_type idx, size_type str_len) const
{
if (str_len == npos)
CEGUI_THROW(std::length_error("Length for utf8 encoded string can not be 'npos'"));
if (idx < d_cplength)
{
size_type encsze = encoded_size(utf8_str, str_len);
const utf32* pt = &ptr()[idx];
do
{
if (npos == find_codepoint(utf8_str, encsze, *pt++))
return idx;
} while (++idx != d_cplength);
}
return npos;
}
/*!
\brief
Search forwards for a given code point
\param code_point
The utf32 code point to search for
\param idx
Index of the code point where the search is to start.
\return
- Index of the first occurrence of \a code_point starting from from \a idx.
- npos if the code point could not be found
*/
size_type find_first_of(utf32 code_point, size_type idx = 0) const
{
return find(code_point, idx);
}
/*!
\brief
Search forwards for the first code point that does not match a given code point
\param code_point
The utf32 code point to search for
\param idx
Index of the code point where the search is to start.
\return
- Index of the first code point that does not match \a code_point starting from from \a idx.
- npos if all code points matched \a code_point
\exception std::out_of_range Thrown if \a idx is invalid for this String.
*/
size_type find_first_not_of(utf32 code_point, size_type idx = 0) const
{
if (idx < d_cplength)
{
do
{
if ((*this)[idx] != code_point)
return idx;
} while(idx++ < d_cplength);
}
return npos;
}
/*!
\brief
Find the first occurrence of one of a set of chars.
\param c_str
c-string describing the set of chars.
\param idx
Index of the start point for the search
\return
- Index of the first occurrence of any one of the chars in \a c_str starting from from \a idx.
- npos if none of the chars in \a c_str were found.
\exception std::out_of_range Thrown if \a idx is invalid for this String.
*/
size_type find_first_of(const char* cstr, size_type idx = 0) const
{
return find_first_of(cstr, idx, strlen(cstr));
}
/*!
\brief
Find the first code point that is not one of a set of chars.
\param c_str
c-string describing the set of chars.
\param idx
Index of the start point for the search
\return
- Index of the first code point that does not match any one of the chars in \a c_str starting from from \a idx.
- npos if all code points matched any of the chars in \a c_str.
\exception std::out_of_range Thrown if \a idx is invalid for this String.
*/
size_type find_first_not_of(const char* cstr, size_type idx = 0) const
{
return find_first_not_of(cstr, idx, strlen(cstr));
}
/*!
\brief
Find the first occurrence of one of a set of chars.
\param chars
char array containing the set of chars.
\param idx
Index of the start point for the search
\param chars_len
Number of chars in the char array.
\return
- Index of the first occurrence of any one of the chars in \a chars starting from from \a idx.
- npos if none of the chars in \a chars were found.
\exception std::length_error Thrown if \a chars_len was 'npos'.
*/
size_type find_first_of(const char* chars, size_type idx, size_type chars_len) const
{
if (chars_len == npos)
CEGUI_THROW(std::length_error("Length for char array can not be 'npos'"));
if (idx < d_cplength)
{
const utf32* pt = &ptr()[idx];
do
{
if (npos != find_codepoint(chars, chars_len, *pt++))
return idx;
} while (++idx != d_cplength);
}
return npos;
}
/*!
\brief
Find the first code point that is not one of a set of chars.
\param chars
char array containing the set of chars.
\param idx
Index of the start point for the search
\param chars_len
Number of chars in the car array.
\return
- Index of the first code point that does not match any one of the chars in \a chars starting from from \a idx.
- npos if all code points matched any of the chars in \a chars.
\exception std::length_error Thrown if \a chars_len was 'npos'.
*/
size_type find_first_not_of(const char* chars, size_type idx, size_type chars_len) const
{
if (chars_len == npos)
CEGUI_THROW(std::length_error("Length for char array can not be 'npos'"));
if (idx < d_cplength)
{
const utf32* pt = &ptr()[idx];
do
{
if (npos == find_codepoint(chars, chars_len, *pt++))
return idx;
} while (++idx != d_cplength);
}
return npos;
}
//////////////////////////////////////////////////////////////////////////
// Find last of different code-points
//////////////////////////////////////////////////////////////////////////
/*!
\brief
Find the last occurrence of one of a set of code points.
\param str
String object describing the set of code points.
\param idx
Index of the start point for the search
\return
- Index of the last occurrence of any one of the code points in \a str starting from \a idx.
- npos if none of the code points in \a str were found.
*/
size_type find_last_of(const String& str, size_type idx = npos) const
{
if (d_cplength > 0)
{
if (idx >= d_cplength)
idx = d_cplength - 1;
const utf32* pt = &ptr()[idx];
do
{
if (npos != str.find(*pt--))
return idx;
} while (idx-- != 0);
}
return npos;
}
/*!
\brief
Find the last code point that is not one of a set of code points.
\param str
String object describing the set of code points.
\param idx
Index of the start point for the search
\return
- Index of the last code point that does not match any one of the code points in \a str starting from \a idx.
- npos if all code points matched one of the code points in \a str.
*/
size_type find_last_not_of(const String& str, size_type idx = npos) const
{
if (d_cplength > 0)
{
if (idx >= d_cplength)
idx = d_cplength - 1;
const utf32* pt = &ptr()[idx];
do
{
if (npos == str.find(*pt--))
return idx;
} while (idx-- != 0);
}
return npos;
}
/*!
\brief
Find the last occurrence of one of a set of code points.
\param std_str
std::string object describing the set of code points.
\note
The characters of \a std_str are taken to be unencoded data which represent Unicode code points 0x00..0xFF. No translation of
the provided data will occur.
\param idx
Index of the start point for the search
\return
- Index of the last occurrence of any one of the code points in \a std_str starting from \a idx.
- npos if none of the code points in \a std_str were found.
*/
size_type find_last_of(const std::string& std_str, size_type idx = npos) const
{
if (d_cplength > 0)
{
if (idx >= d_cplength)
idx = d_cplength - 1;
const utf32* pt = &ptr()[idx];
do
{
if (npos != find_codepoint(std_str, *pt--))
return idx;
} while (idx-- != 0);
}
return npos;
}
/*!
\brief
Find the last code point that is not one of a set of code points.
\param std_str
std::string object describing the set of code points.
\note
The characters of \a std_str are taken to be unencoded data which represent Unicode code points 0x00..0xFF. No translation of
the provided data will occur.
\param idx
Index of the start point for the search
\return
- Index of the last code point that does not match any one of the code points in \a std_str starting from \a idx.
- npos if all code points matched one of the code points in \a std_str.
*/
size_type find_last_not_of(const std::string& std_str, size_type idx = npos) const
{
if (d_cplength > 0)
{
if (idx >= d_cplength)
idx = d_cplength - 1;
const utf32* pt = &ptr()[idx];
do
{
if (npos == find_codepoint(std_str, *pt--))
return idx;
} while (idx-- != 0);
}
return npos;
}
/*!
\brief
Find the last occurrence of one of a set of code points.
\param utf8_str
Buffer containing null-terminated utf8 encoded data describing the set of code points.
\note
A basic string literal (cast to utf8*) can be passed to this function, provided that the string is
comprised only of code points 0x00..0x7f. The use of extended ASCII characters (with values >0x7f)
would result in incorrect behaviour as the String will attempt to 'decode' the data, with unpredictable
results.
\param idx
Index of the start point for the search
\return
- Index of the last occurrence of any one of the code points in \a utf8_str starting from \a idx.
- npos if none of the code points in \a utf8_str were found.
\exception std::out_of_range Thrown if \a idx is invalid for this String.
*/
size_type find_last_of(const utf8* utf8_str, size_type idx = npos) const
{
return find_last_of(utf8_str, idx, utf_length(utf8_str));
}
/*!
\brief
Find the last code point that is not one of a set of code points.
\param utf8_str
Buffer containing null-terminated utf8 encoded data describing the set of code points.
\note
A basic string literal (cast to utf8*) can be passed to this function, provided that the string is
comprised only of code points 0x00..0x7f. The use of extended ASCII characters (with values >0x7f)
would result in incorrect behaviour as the String will attempt to 'decode' the data, with unpredictable
results.
\param idx
Index of the start point for the search
\return
- Index of the last code point that does not match any one of the code points in \a utf8_str starting from \a idx.
- npos if all code points matched one of the code points in \a utf8_str.
\exception std::out_of_range Thrown if \a idx is invalid for this String.
*/
size_type find_last_not_of(const utf8* utf8_str, size_type idx = npos) const
{
return find_last_not_of(utf8_str, idx, utf_length(utf8_str));
}
/*!
\brief
Find the last occurrence of one of a set of code points.
\param utf8_str
Buffer containing utf8 encoded data describing the set of code points.
\note
A basic string literal (cast to utf8*) can be passed to this function, provided that the string is
comprised only of code points 0x00..0x7f. The use of extended ASCII characters (with values >0x7f)
would result in incorrect behaviour as the String will attempt to 'decode' the data, with unpredictable
results.
\param idx
Index of the start point for the search
\param str_len
Length of the utf8 encoded data in utf8 code units (not code points).
\return
- Index of the last occurrence of any one of the code points in \a utf8_str starting from from \a idx.
- npos if none of the code points in \a utf8_str were found.
\exception std::length_error Thrown if \a str_len was 'npos'.
*/
size_type find_last_of(const utf8* utf8_str, size_type idx, size_type str_len) const
{
if (str_len == npos)
CEGUI_THROW(std::length_error("Length for utf8 encoded string can not be 'npos'"));
if (d_cplength > 0)
{
if (idx >= d_cplength)
idx = d_cplength - 1;
size_type encsze = encoded_size(utf8_str, str_len);
const utf32* pt = &ptr()[idx];
do
{
if (npos != find_codepoint(utf8_str, encsze, *pt--))
return idx;
} while (idx-- != 0);
}
return npos;
}
/*!
\brief
Find the last code point that is not one of a set of code points.
\param utf8_str
Buffer containing utf8 encoded data describing the set of code points.
\note
A basic string literal (cast to utf8*) can be passed to this function, provided that the string is
comprised only of code points 0x00..0x7f. The use of extended ASCII characters (with values >0x7f)
would result in incorrect behaviour as the String will attempt to 'decode' the data, with unpredictable
results.
\param idx
Index of the start point for the search
\param str_len
Length of the utf8 encoded data in utf8 code units (not code points).
\return
- Index of the last code point that does not match any one of the code points in \a utf8_str starting from from \a idx.
- npos if all code points matched one of the code points in \a utf8_str.
\exception std::length_error Thrown if \a str_len was 'npos'.
*/
size_type find_last_not_of(const utf8* utf8_str, size_type idx, size_type str_len) const
{
if (str_len == npos)
CEGUI_THROW(std::length_error("Length for utf8 encoded string can not be 'npos'"));
if (d_cplength > 0)
{
if (idx >= d_cplength)
idx = d_cplength - 1;
size_type encsze = encoded_size(utf8_str, str_len);
const utf32* pt = &ptr()[idx];
do
{
if (npos == find_codepoint(utf8_str, encsze, *pt--))
return idx;
} while (idx-- != 0);
}
return npos;
}
/*!
\brief
Search for last occurrence of a given code point
\param code_point
The utf32 code point to search for
\param idx
Index of the code point where the search is to start.
\return
- Index of the last occurrence of \a code_point starting from \a idx.
- npos if the code point could not be found
*/
size_type find_last_of(utf32 code_point, size_type idx = npos) const
{
return rfind(code_point, idx);
}
/*!
\brief
Search for the last code point that does not match a given code point
\param code_point
The utf32 code point to search for
\param idx
Index of the code point where the search is to start.
\return
- Index of the last code point that does not match \a code_point starting from from \a idx.
- npos if all code points matched \a code_point
*/
size_type find_last_not_of(utf32 code_point, size_type idx = npos) const
{
if (d_cplength > 0)
{
if (idx >= d_cplength)
idx = d_cplength - 1;
do
{
if ((*this)[idx] != code_point)
return idx;
} while(idx-- != 0);
}
return npos;
}
/*!
\brief
Find the last occurrence of one of a set of chars.
\param c_str
c-string describing the set of chars.
\param idx
Index of the start point for the search
\return
- Index of the last occurrence of any one of the chars in \a c_str starting from \a idx.
- npos if none of the chars in \a c_str were found.
\exception std::out_of_range Thrown if \a idx is invalid for this String.
*/
size_type find_last_of(const char* cstr, size_type idx = npos) const
{
return find_last_of(cstr, idx, strlen(cstr));
}
/*!
\brief
Find the last code point that is not one of a set of chars.
\param c_str
c-string describing the set of chars.
\param idx
Index of the start point for the search
\return
- Index of the last code point that does not match any one of the chars in \a c_str starting from \a idx.
- npos if all code points matched any of the chars in \a c_str.
\exception std::out_of_range Thrown if \a idx is invalid for this String.
*/
size_type find_last_not_of(const char* cstr, size_type idx = npos) const
{
return find_last_not_of(cstr, idx, strlen(cstr));
}
/*!
\brief
Find the last occurrence of one of a set of chars.
\param chars
char array containing the set of chars.
\param idx
Index of the start point for the search
\param chars_len
Number of chars in the char array.
\return
- Index of the last occurrence of any one of the chars in \a chars, starting from from \a idx.
- npos if none of the chars in \a chars were found.
\exception std::length_error Thrown if \a chars_len was 'npos'.
*/
size_type find_last_of(const char* chars, size_type idx, size_type chars_len) const
{
if (chars_len == npos)
CEGUI_THROW(std::length_error("Length for char array can not be 'npos'"));
if (d_cplength > 0)
{
if (idx >= d_cplength)
idx = d_cplength - 1;
const utf32* pt = &ptr()[idx];
do
{
if (npos != find_codepoint(chars, chars_len, *pt--))
return idx;
} while (idx-- != 0);
}
return npos;
}
/*!
\brief
Find the last code point that is not one of a set of chars.
\param chars
char array containing the set of chars.
\param idx
Index of the start point for the search
\param chars_len
Number of chars in the char array.
\return
- Index of the last code point that does not match any one of the chars in \a chars, starting from from \a idx.
- npos if all code points matched any of the chars in \a chars.
\exception std::length_error Thrown if \a chars_len was 'npos'.
*/
size_type find_last_not_of(const char* chars, size_type idx, size_type chars_len) const
{
if (chars_len == npos)
CEGUI_THROW(std::length_error("Length for char array can not be 'npos'"));
if (d_cplength > 0)
{
if (idx >= d_cplength)
idx = d_cplength - 1;
const utf32* pt = &ptr()[idx];
do
{
if (npos == find_codepoint(chars, chars_len, *pt--))
return idx;
} while (idx-- != 0);
}
return npos;
}
//////////////////////////////////////////////////////////////////////////
// Substring
//////////////////////////////////////////////////////////////////////////
/*!
\brief
Returns a substring of this String.
\param idx
Index of the first code point to use for the sub-string.
\param len
Maximum number of code points to use for the sub-string
\return
A String object containing the specified sub-string.
\exception std::out_of_range Thrown if \a idx is invalid for this String.
*/
String substr(size_type idx = 0, size_type len = npos) const
{
if (d_cplength < idx)
CEGUI_THROW(std::out_of_range("Index is out of range for this CEGUI::String"));
return String(*this, idx, len);
}
//////////////////////////////////////////////////////////////////////////
// Iterator creation
//////////////////////////////////////////////////////////////////////////
/*!
\brief
Return a forwards iterator that describes the beginning of the String
\return
iterator object that describes the beginning of the String.
*/
iterator begin(void)
{
return iterator(ptr());
}
/*!
\brief
Return a constant forwards iterator that describes the beginning of the String
\return
const_iterator object that describes the beginning of the String.
*/
const_iterator begin(void) const
{
return const_iterator(ptr());
}
/*!
\brief
Return a forwards iterator that describes the end of the String
\return
iterator object that describes the end of the String.
*/
iterator end(void)
{
return iterator(&ptr()[d_cplength]);
}
/*!
\brief
Return a constant forwards iterator that describes the end of the String
\return
const_iterator object that describes the end of the String.
*/
const_iterator end(void) const
{
return const_iterator(&ptr()[d_cplength]);
}
/*!
\brief
Return a reverse iterator that describes the beginning of the String
\return
reverse_iterator object that describes the beginning of the String (so is actually at the end)
*/
reverse_iterator rbegin(void)
{
return reverse_iterator(end());
}
/*!
\brief
Return a constant reverse iterator that describes the beginning of the String
\return
const_reverse_iterator object that describes the beginning of the String (so is actually at the end)
*/
const_reverse_iterator rbegin(void) const
{
return const_reverse_iterator(end());
}
/*!
\brief
Return a reverse iterator that describes the end of the String
\return
reverse_iterator object that describes the end of the String (so is actually at the beginning)
*/
reverse_iterator rend(void)
{
return reverse_iterator(begin());
}
/*!
\brief
Return a constant reverse iterator that describes the end of the String
\return
const_reverse_iterator object that describes the end of the String (so is actually at the beginning)
*/
const_reverse_iterator rend(void) const
{
return const_reverse_iterator(begin());
}
private:
/*************************************************************************
Implementation Functions
*************************************************************************/
// string management
// change size of allocated buffer so it is at least 'new_size'.
// May or may not cause re-allocation and copy of buffer if size is larger
// will never re-allocate to make size smaller. (see trim())
bool grow(size_type new_size);
// perform re-allocation to remove wasted space.
void trim(void);
// set the length of the string, and terminate it, according to the given value (will not re-allocate, use grow() first).
void setlen(size_type len)
{
d_cplength = len;
ptr()[len] = (utf32)(0);
}
// initialise string object
void init(void)
{
d_reserve = CEGUI_STR_QUICKBUFF_SIZE;
d_encodedbuff = 0;
d_encodedbufflen = 0;
d_encodeddatlen = 0;
d_buffer = 0;
setlen(0);
}
// return true if the given pointer is inside the string data
bool inside(utf32* inptr)
{
if (inptr < ptr() || ptr() + d_cplength <= inptr)
return false;
else
return true;
}
// compute distance between two iterators, returning a 'safe' value
size_type safe_iter_dif(const const_iterator& iter1, const const_iterator& iter2) const
{
return (iter1.d_ptr == 0) ? 0 : (iter1 - iter2);
}
// encoding functions
// for all:
// src_len is in code units, or 0 for null terminated string.
// dest_len is in code units.
// returns number of code units put into dest buffer.
size_type encode(const utf32* src, utf8* dest, size_type dest_len, size_type src_len = 0) const
{
// count length for null terminated source...
if (src_len == 0)
{
src_len = utf_length(src);
}
size_type destCapacity = dest_len;
// while there is data in the source buffer,
for (uint idx = 0; idx < src_len; ++idx)
{
utf32 cp = src[idx];
// check there is enough destination buffer to receive this encoded unit (exit loop & return if not)
if (destCapacity < encoded_size(cp))
{
break;
}
if (cp < 0x80)
{
*dest++ = (utf8)cp;
--destCapacity;
}
else if (cp < 0x0800)
{
*dest++ = (utf8)((cp >> 6) | 0xC0);
*dest++ = (utf8)((cp & 0x3F) | 0x80);
destCapacity -= 2;
}
else if (cp < 0x10000)
{
*dest++ = (utf8)((cp >> 12) | 0xE0);
*dest++ = (utf8)(((cp >> 6) & 0x3F) | 0x80);
*dest++ = (utf8)((cp & 0x3F) | 0x80);
destCapacity -= 3;
}
else
{
*dest++ = (utf8)((cp >> 18) | 0xF0);
*dest++ = (utf8)(((cp >> 12) & 0x3F) | 0x80);
*dest++ = (utf8)(((cp >> 6) & 0x3F) | 0x80);
*dest++ = (utf8)((cp & 0x3F) | 0x80);
destCapacity -= 4;
}
}
return dest_len - destCapacity;
}
size_type encode(const utf8* src, utf32* dest, size_type dest_len, size_type src_len = 0) const
{
// count length for null terminated source...
if (src_len == 0)
{
src_len = utf_length(src);
}
size_type destCapacity = dest_len;
// while there is data in the source buffer, and space in the dest buffer
for (uint idx = 0; ((idx < src_len) && (destCapacity > 0));)
{
utf32 cp;
utf8 cu = src[idx++];
if (cu < 0x80)
{
cp = (utf32)(cu);
}
else if (cu < 0xE0)
{
cp = ((cu & 0x1F) << 6);
cp |= (src[idx++] & 0x3F);
}
else if (cu < 0xF0)
{
cp = ((cu & 0x0F) << 12);
cp |= ((src[idx++] & 0x3F) << 6);
cp |= (src[idx++] & 0x3F);
}
else
{
cp = ((cu & 0x07) << 18);
cp |= ((src[idx++] & 0x3F) << 12);
cp |= ((src[idx++] & 0x3F) << 6);
cp |= (src[idx++] & 0x3F);
}
*dest++ = cp;
--destCapacity;
}
return dest_len - destCapacity;
}
// return the number of utf8 code units required to encode the given utf32 code point
size_type encoded_size(utf32 code_point) const
{
if (code_point < 0x80)
return 1;
else if (code_point < 0x0800)
return 2;
else if (code_point < 0x10000)
return 3;
else
return 4;
}
// return number of code units required to re-encode given null-terminated utf32 data as utf8. return does not include terminating null.
size_type encoded_size(const utf32* buf) const
{
return encoded_size(buf, utf_length(buf));
}
// return number of code units required to re-encode given utf32 data as utf8. len is number of code units in 'buf'.
size_type encoded_size(const utf32* buf, size_type len) const
{
size_type count = 0;
while (len--)
{
count += encoded_size(*buf++);
}
return count;
}
// return number of utf32 code units required to re-encode given utf8 data as utf32. return does not include terminating null.
size_type encoded_size(const utf8* buf) const
{
return encoded_size(buf, utf_length(buf));
}
// return number of utf32 code units required to re-encode given utf8 data as utf32. len is number of code units in 'buf'.
size_type encoded_size(const utf8* buf, size_type len) const
{
utf8 tcp;
size_type count = 0;
while (len--)
{
tcp = *buf++;
++count;
size_type size = 0;
if (tcp < 0x80)
{
}
else if (tcp < 0xE0)
{
size = 1;
++buf;
}
else if (tcp < 0xF0)
{
size = 2;
buf += 2;
}
else
{
size = 3;
buf += 3;
}
if (len >= size)
len -= size;
else
break;
}
return count;
}
// return number of code units in a null terminated string
size_type utf_length(const utf8* utf8_str) const
{
size_type cnt = 0;
while (*utf8_str++)
cnt++;
return cnt;
}
// return number of code units in a null terminated string
size_type utf_length(const utf32* utf32_str) const
{
size_type cnt = 0;
while (*utf32_str++)
cnt++;
return cnt;
}
// build an internal buffer with the string encoded as utf8 (remains valid until string is modified).
utf8* build_utf8_buff(void) const;
// compare two utf32 buffers
int utf32_comp_utf32(const utf32* buf1, const utf32* buf2, size_type cp_count) const
{
if (!cp_count)
return 0;
while ((--cp_count) && (*buf1 == *buf2))
buf1++, buf2++;
return *buf1 - *buf2;
}
// compare utf32 buffer with char buffer (chars are taken to be code-points in the range 0x00-0xFF)
int utf32_comp_char(const utf32* buf1, const char* buf2, size_type cp_count) const
{
if (!cp_count)
return 0;
while ((--cp_count) && (*buf1 == static_cast<utf32>(static_cast<unsigned char>(*buf2))))
buf1++, buf2++;
return *buf1 - static_cast<utf32>(static_cast<unsigned char>(*buf2));
}
// compare utf32 buffer with encoded utf8 data
int utf32_comp_utf8(const utf32* buf1, const utf8* buf2, size_type cp_count) const
{
if (!cp_count)
return 0;
utf32 cp;
utf8 cu;
do
{
cu = *buf2++;
if (cu < 0x80)
{
cp = (utf32)(cu);
}
else if (cu < 0xE0)
{
cp = ((cu & 0x1F) << 6);
cp |= (*buf2++ & 0x3F);
}
else if (cu < 0xF0)
{
cp = ((cu & 0x0F) << 12);
cp |= ((*buf2++ & 0x3F) << 6);
cp |= (*buf2++ & 0x3F);
}
else
{
cp = ((cu & 0x07) << 18);
cp |= ((*buf2++ & 0x3F) << 12);
cp |= ((*buf2++ & 0x3F) << 6);
cp |= (*buf2++ & 0x3F);
}
} while ((*buf1++ == cp) && (--cp_count));
return (*--buf1) - cp;
}
// return index of first occurrence of 'code_point' in std::string 'str', or npos if none
size_type find_codepoint(const std::string& str, utf32 code_point) const
{
size_type idx = 0, sze = (size_type)str.size();
while (idx != sze)
{
if (code_point == static_cast<utf32>(static_cast<unsigned char>(str[idx])))
return idx;
++idx;
}
return npos;
}
// return index of first occurrence of 'code_point' in utf8 encoded string 'str', or npos if none. len is in code points.
size_type find_codepoint(const utf8* str, size_type len, utf32 code_point) const
{
size_type idx = 0;
utf32 cp;
utf8 cu;
while (idx != len) {
cu = *str++;
if (cu < 0x80)
{
cp = (utf32)(cu);
}
else if (cu < 0xE0)
{
cp = ((cu & 0x1F) << 6);
cp |= (*str++ & 0x3F);
}
else if (cu < 0xF0)
{
cp = ((cu & 0x0F) << 12);
cp |= ((*str++ & 0x3F) << 6);
cp |= (*str++ & 0x3F);
}
else
{
cp = ((cu & 0x07) << 18);
cp |= ((*str++ & 0x3F) << 12);
cp |= ((*str++ & 0x3F) << 6);
cp |= (*str++ & 0x3F);
}
if (code_point == cp)
return idx;
++idx;
}
return npos;
}
// return index of first occurrence of 'code_point' in char array 'chars', or npos if none
size_type find_codepoint(const char* chars, size_type chars_len, utf32 code_point) const
{
for (size_type idx = 0; idx != chars_len; ++idx)
{
if (code_point == static_cast<utf32>(static_cast<unsigned char>(chars[idx])))
return idx;
}
return npos;
}
};
//////////////////////////////////////////////////////////////////////////
// Comparison operators
//////////////////////////////////////////////////////////////////////////
/*!
\brief
Return true if String \a str1 is equal to String \a str2
*/
bool CEGUIEXPORT operator==(const String& str1, const String& str2);
/*!
\brief
Return true if String \a str is equal to std::string \a std_str
*/
bool CEGUIEXPORT operator==(const String& str, const std::string& std_str);
/*!
\brief
Return true if String \a str is equal to std::string \a std_str
*/
bool CEGUIEXPORT operator==(const std::string& std_str, const String& str);
/*!
\brief
Return true if String \a str is equal to null-terminated utf8 data \a utf8_str
*/
bool CEGUIEXPORT operator==(const String& str, const utf8* utf8_str);
/*!
\brief
Return true if String \a str is equal to null-terminated utf8 data \a utf8_str
*/
bool CEGUIEXPORT operator==(const utf8* utf8_str, const String& str);
/*!
\brief
Return true if String \a str1 is not equal to String \a str2
*/
bool CEGUIEXPORT operator!=(const String& str1, const String& str2);
/*!
\brief
Return true if String \a str is not equal to std::string \a std_str
*/
bool CEGUIEXPORT operator!=(const String& str, const std::string& std_str);
/*!
\brief
Return true if String \a str is not equal to std::string \a std_str
*/
bool CEGUIEXPORT operator!=(const std::string& std_str, const String& str);
/*!
\brief
Return true if String \a str is not equal to null-terminated utf8 data \a utf8_str
*/
bool CEGUIEXPORT operator!=(const String& str, const utf8* utf8_str);
/*!
\brief
Return true if String \a str is not equal to null-terminated utf8 data \a utf8_str
*/
bool CEGUIEXPORT operator!=(const utf8* utf8_str, const String& str);
/*!
\brief
Return true if String \a str1 is lexicographically less than String \a str2
*/
bool CEGUIEXPORT operator<(const String& str1, const String& str2);
/*!
\brief
Return true if String \a str is lexicographically less than std::string \a std_str
*/
bool CEGUIEXPORT operator<(const String& str, const std::string& std_str);
/*!
\brief
Return true if String \a str is lexicographically less than std::string \a std_str
*/
bool CEGUIEXPORT operator<(const std::string& std_str, const String& str);
/*!
\brief
Return true if String \a str is lexicographically less than null-terminated utf8 data \a utf8_str
*/
bool CEGUIEXPORT operator<(const String& str, const utf8* utf8_str);
/*!
\brief
Return true if String \a str is lexicographically less than null-terminated utf8 data \a utf8_str
*/
bool CEGUIEXPORT operator<(const utf8* utf8_str, const String& str);
/*!
\brief
Return true if String \a str1 is lexicographically greater than String \a str2
*/
bool CEGUIEXPORT operator>(const String& str1, const String& str2);
/*!
\brief
Return true if String \a str is lexicographically greater than std::string \a std_str
*/
bool CEGUIEXPORT operator>(const String& str, const std::string& std_str);
/*!
\brief
Return true if String \a str is lexicographically greater than std::string \a std_str
*/
bool CEGUIEXPORT operator>(const std::string& std_str, const String& str);
/*!
\brief
Return true if String \a str is lexicographically greater than null-terminated utf8 data \a utf8_str
*/
bool CEGUIEXPORT operator>(const String& str, const utf8* utf8_str);
/*!
\brief
Return true if String \a str is lexicographically greater than null-terminated utf8 data \a utf8_str
*/
bool CEGUIEXPORT operator>(const utf8* utf8_str, const String& str);
/*!
\brief
Return true if String \a str1 is lexicographically less than or equal to String \a str2
*/
bool CEGUIEXPORT operator<=(const String& str1, const String& str2);
/*!
\brief
Return true if String \a str is lexicographically less than or equal to std::string \a std_str
*/
bool CEGUIEXPORT operator<=(const String& str, const std::string& std_str);
/*!
\brief
Return true if String \a str is lexicographically less than or equal to std::string \a std_str
*/
bool CEGUIEXPORT operator<=(const std::string& std_str, const String& str);
/*!
\brief
Return true if String \a str is lexicographically less than or equal to null-terminated utf8 data \a utf8_str
*/
bool CEGUIEXPORT operator<=(const String& str, const utf8* utf8_str);
/*!
\brief
Return true if String \a str is lexicographically less than or equal to null-terminated utf8 data \a utf8_str
*/
bool CEGUIEXPORT operator<=(const utf8* utf8_str, const String& str);
/*!
\brief
Return true if String \a str1 is lexicographically greater than or equal to String \a str2
*/
bool CEGUIEXPORT operator>=(const String& str1, const String& str2);
/*!
\brief
Return true if String \a str is lexicographically greater than or equal to std::string \a std_str
*/
bool CEGUIEXPORT operator>=(const String& str, const std::string& std_str);
/*!
\brief
Return true if String \a str is lexicographically greater than or equal to std::string \a std_str
*/
bool CEGUIEXPORT operator>=(const std::string& std_str, const String& str);
/*!
\brief
Return true if String \a str is lexicographically greater than or equal to null-terminated utf8 data \a utf8_str
*/
bool CEGUIEXPORT operator>=(const String& str, const utf8* utf8_str);
/*!
\brief
Return true if String \a str is lexicographically greater than or equal to null-terminated utf8 data \a utf8_str
*/
bool CEGUIEXPORT operator>=(const utf8* utf8_str, const String& str);
/*!
\brief
Return true if String \a str is equal to c-string \a c_str
*/
bool CEGUIEXPORT operator==(const String& str, const char* c_str);
/*!
\brief
Return true if c-string \a c_str is equal to String \a str
*/
bool CEGUIEXPORT operator==(const char* c_str, const String& str);
/*!
\brief
Return true if String \a str is not equal to c-string \a c_str
*/
bool CEGUIEXPORT operator!=(const String& str, const char* c_str);
/*!
\brief
Return true if c-string \a c_str is not equal to String \a str
*/
bool CEGUIEXPORT operator!=(const char* c_str, const String& str);
/*!
\brief
Return true if String \a str is lexicographically less than c-string \a c_str
*/
bool CEGUIEXPORT operator<(const String& str, const char* c_str);
/*!
\brief
Return true if c-string \a c_str is lexicographically less than String \a str
*/
bool CEGUIEXPORT operator<(const char* c_str, const String& str);
/*!
\brief
Return true if String \a str is lexicographically greater than c-string \a c_str
*/
bool CEGUIEXPORT operator>(const String& str, const char* c_str);
/*!
\brief
Return true if c-string \a c_str is lexicographically greater than String \a str
*/
bool CEGUIEXPORT operator>(const char* c_str, const String& str);
/*!
\brief
Return true if String \a str is lexicographically less than or equal to c-string \a c_str
*/
bool CEGUIEXPORT operator<=(const String& str, const char* c_str);
/*!
\brief
Return true if c-string \a c_str is lexicographically less than or equal to String \a str
*/
bool CEGUIEXPORT operator<=(const char* c_str, const String& str);
/*!
\brief
Return true if String \a str is lexicographically greater than or equal to c-string \a c_str
*/
bool CEGUIEXPORT operator>=(const String& str, const char* c_str);
/*!
\brief
Return true if c-string \a c_str is lexicographically greater than or equal to String \a str
*/
bool CEGUIEXPORT operator>=(const char* c_str, const String& str);
//////////////////////////////////////////////////////////////////////////
// Concatenation operator functions
//////////////////////////////////////////////////////////////////////////
/*!
\brief
Return String object that is the concatenation of the given inputs
\param str1
String object describing first part of the new string
\param str2
String object describing the second part of the new string
\return
A String object that is the concatenation of \a str1 and \a str2
\exception std::length_error Thrown if the resulting String would be too large.
*/
String CEGUIEXPORT operator+(const String& str1, const String& str2);
/*!
\brief
Return String object that is the concatenation of the given inputs
\param str
String object describing first part of the new string
\param std_str
std::string object describing the second part of the new string
\return
A String object that is the concatenation of \a str and \a std_str
\exception std::length_error Thrown if the resulting String would be too large.
*/
String CEGUIEXPORT operator+(const String& str, const std::string& std_str);
/*!
\brief
Return String object that is the concatenation of the given inputs
\param std_str
std::string object describing the first part of the new string
\param str
String object describing the second part of the new string
\return
A String object that is the concatenation of \a std_str and \a str
\exception std::length_error Thrown if the resulting String would be too large.
*/
String CEGUIEXPORT operator+(const std::string& std_str, const String& str);
/*!
\brief
Return String object that is the concatenation of the given inputs
\param str
String object describing first part of the new string
\param utf8_str
Buffer containing null-terminated utf8 encoded data describing the second part of the new string
\return
A String object that is the concatenation of \a str and \a utf8_str
\exception std::length_error Thrown if the resulting String would be too large.
*/
String CEGUIEXPORT operator+(const String& str, const utf8* utf8_str);
/*!
\brief
Return String object that is the concatenation of the given inputs
\param utf8_str
Buffer containing null-terminated utf8 encoded data describing the first part of the new string
\param str
String object describing the second part of the new string
\return
A String object that is the concatenation of \a str and \a utf8_str
\exception std::length_error Thrown if the resulting String would be too large.
*/
String CEGUIEXPORT operator+(const utf8* utf8_str, const String& str);
/*!
\brief
Return String object that is the concatenation of the given inputs
\param str
String object describing the first part of the new string
\param code_point
utf32 code point describing the second part of the new string
\return
A String object that is the concatenation of \a str and \a code_point
\exception std::length_error Thrown if the resulting String would be too large.
*/
String CEGUIEXPORT operator+(const String& str, utf32 code_point);
/*!
\brief
Return String object that is the concatenation of the given inputs
\param code_point
utf32 code point describing the first part of the new string
\param str
String object describing the second part of the new string
\return
A String object that is the concatenation of \a code_point and \a str
\exception std::length_error Thrown if the resulting String would be too large.
*/
String CEGUIEXPORT operator+(utf32 code_point, const String& str);
/*!
\brief
Return String object that is the concatenation of the given inputs
\param str
String object describing first part of the new string
\param c_str
c-string describing the second part of the new string
\return
A String object that is the concatenation of \a str and \a c_str
\exception std::length_error Thrown if the resulting String would be too large.
*/
String CEGUIEXPORT operator+(const String& str, const char* c_str);
/*!
\brief
Return String object that is the concatenation of the given inputs
\param c_str
c-string describing the first part of the new string
\param str
String object describing the second part of the new string
\return
A String object that is the concatenation of \a c_str and \a str
\exception std::length_error Thrown if the resulting String would be too large.
*/
String CEGUIEXPORT operator+(const char* c_str, const String& str);
//////////////////////////////////////////////////////////////////////////
// Output (stream) functions
//////////////////////////////////////////////////////////////////////////
CEGUIEXPORT std::ostream& operator<<(std::ostream& s, const String& str);
//////////////////////////////////////////////////////////////////////////
// Modifying operations
//////////////////////////////////////////////////////////////////////////
/*!
\brief
Swap the contents for two String objects
\param str1
String object who's contents are to be swapped with \a str2
\param str2
String object who's contents are to be swapped with \a str1
\return
Nothing
*/
void CEGUIEXPORT swap(String& str1, String& str2);
/*!
\brief
Functor that can be used as comparator in a std::map with String keys.
It's faster than using the default, but the map will no longer be sorted alphabetically.
*/
struct StringFastLessCompare
{
bool operator() (const String& a, const String& b) const
{
const size_t la = a.length();
const size_t lb = b.length();
if (la == lb)
return (memcmp(a.ptr(), b.ptr(), la * sizeof(utf32)) < 0);
return (la < lb);
}
};
#else
/// encoded char signifies that it's a char (8bit) with encoding (in this case ASCII)
typedef char encoded_char;
#if CEGUI_STRING_CLASS == CEGUI_STRING_CLASS_STD
typedef std::string String;
#endif
/*!
\brief
Functor that can be used as comparator in a std::map with String keys.
It's faster than using the default, but the map will no longer be sorted alphabetically.
*/
struct StringFastLessCompare
{
bool operator() (const String& a, const String& b) const
{
const size_t la = a.length();
const size_t lb = b.length();
if (la == lb)
return (memcmp(a.c_str(), b.c_str(), la * sizeof(String::value_type)) < 0);
return (la < lb);
}
};
#if defined(_MSC_VER)
# pragma warning(disable : 4251)
#endif
#endif
} // End of CEGUI namespace section
#endif // end of guard _CEGUIString_h_
| 26.845826 | 142 | 0.674525 | [
"object"
] |
89debe511accb062014a89df7cba9adecbd7aed6 | 2,157 | h | C | src/map/universal_container.h | zircon-tpl/topaz | dc2f7e68e5ed84274976e8a787c29fe03eecc382 | [
"FTL"
] | 1 | 2021-10-30T11:30:33.000Z | 2021-10-30T11:30:33.000Z | src/map/universal_container.h | zircon-tpl/topaz | dc2f7e68e5ed84274976e8a787c29fe03eecc382 | [
"FTL"
] | 2 | 2020-07-01T04:11:03.000Z | 2020-07-02T03:54:24.000Z | src/map/universal_container.h | zircon-tpl/topaz | dc2f7e68e5ed84274976e8a787c29fe03eecc382 | [
"FTL"
] | 1 | 2020-07-01T05:31:49.000Z | 2020-07-01T05:31:49.000Z | /*
===========================================================================
Copyright (c) 2010-2015 Darkstar Dev Teams
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/
===========================================================================
*/
#ifndef _CUNIVERSALCONTAINER_H
#define _CUNIVERSALCONTAINER_H
#include "../common/cbasetypes.h"
#include <vector>
enum UCONTAINERTYPE
{
UCONTAINER_EMPTY,
UCONTAINER_SYNTES,
UCONTAINER_FISHING,
UCONTAINER_SHOP,
UCONTAINER_TRADE,
UCONTAINER_USEITEM,
UCONTAINER_AUCTION,
UCONTAINER_DELIVERYBOX
};
#define UCONTAINER_SIZE 16
/************************************************************************
* *
* Универсальный контейнер общего назначения *
* *
************************************************************************/
// главный предмет (gil, кристалл, используемый предмет ...)
class CItem;
class CBaseEntity;
class CUContainer
{
public:
CUContainer();
UCONTAINERTYPE GetType();
void SetLock();
void UnLock();
void SetTarget(uint16 Target);
void SetType(UCONTAINERTYPE Type);
bool SetItem(uint8 slotID, CItem* PItem);
void SetSize(uint8 size);
void ClearSlot(uint8 slotID);
void Clean();
bool IsLocked();
bool IsContainerEmpty();
bool IsSlotEmpty(uint8 slotID);
uint16 GetTarget();
uint8 GetItemsCount();
CItem* GetItem(uint8 slotID);
private:
UCONTAINERTYPE m_ContainerType;
bool m_lock;
uint8 m_count;
uint16 m_target;
std::vector<CItem*> m_PItem;
};
#endif | 24.511364 | 75 | 0.61567 | [
"vector"
] |
89e24a2a1c8081230bb058b0fe001060ce7b881f | 4,683 | c | C | example/src/main.c | davidbelliott/whitgl | bfa1a33b0059b722a773e513653ff802c8dc7d6f | [
"MIT"
] | 26 | 2016-01-09T16:46:53.000Z | 2021-05-17T02:41:13.000Z | example/src/main.c | davidbelliott/whitgl | bfa1a33b0059b722a773e513653ff802c8dc7d6f | [
"MIT"
] | null | null | null | example/src/main.c | davidbelliott/whitgl | bfa1a33b0059b722a773e513653ff802c8dc7d6f | [
"MIT"
] | 3 | 2016-02-19T06:05:19.000Z | 2021-03-10T02:19:35.000Z | #include <stdbool.h>
#include <stddef.h>
#include <whitgl/input.h>
#include <whitgl/logging.h>
#include <whitgl/math.h>
#include <whitgl/random.h>
#include <whitgl/sound.h>
#include <whitgl/sys.h>
#include <whitgl/timer.h>
const char* post_src = "\
#version 150\
\n\
in vec2 Texturepos;\
out vec4 outColor;\
uniform sampler2D tex;\
uniform sampler2D extra;\
uniform float spread;\
void main()\
{\
vec2 offset = vec2(0.1*spread);\
outColor = vec4(texture( tex, Texturepos-offset ).r, texture( tex, Texturepos ).g, texture( tex, Texturepos+offset ).ba);\
outColor = outColor + texture(extra, Texturepos);\
}\
";
int main()
{
WHITGL_LOG("Starting main.");
whitgl_sys_setup setup = whitgl_sys_setup_zero;
setup.size.x = 32;
setup.size.y = 32;
setup.pixel_size = 16;
setup.name = "main";
setup.resizable = true;
if(!whitgl_sys_init(&setup))
return 1;
whitgl_shader post_shader = whitgl_shader_zero;
post_shader.fragment_src = post_src;
post_shader.num_uniforms = 2;
post_shader.uniforms[0].name = "spread";
post_shader.uniforms[0].type = WHITGL_UNIFORM_FLOAT;
post_shader.uniforms[1].name = "extra";
post_shader.uniforms[1].type = WHITGL_UNIFORM_IMAGE;
// whitgl_sys_color bg = {0xc7,0xb2,0xf6,0xff};
// whitgl_sys_set_clear_color(bg);
if(!whitgl_change_shader(WHITGL_SHADER_POST, post_shader))
return 1;
whitgl_sound_init();
whitgl_input_init();
whitgl_loop_set_listener(whitgl_fvec_zero, whitgl_fvec_zero, 0);
whitgl_sound_add(0, "data/beam.ogg");
whitgl_sound_play(0, 1, 1);
whitgl_loop_add_positional(1, "data/loop.ogg");
whitgl_loop_set_paused(1, false);
whitgl_sys_add_image(0, "data/sprites.png");
whitgl_random_seed seed = whitgl_random_seed_init(0);
whitgl_ivec texture_size = {32,32};
unsigned char data_texture[texture_size.x*texture_size.y*4];
whitgl_int i;
for(i=0; i<texture_size.x*texture_size.y*4; i+=4)
{
whitgl_int pixel = i/4;
data_texture[i] = (pixel%32)*8;
data_texture[i+1] = (pixel/32)*8;
data_texture[i+2] = whitgl_random_int(&seed, 32)+128;
data_texture[i+3] = 255;
}
whitgl_sys_add_image_from_data(1, texture_size, data_texture);
whitgl_load_model(0, "data/torus.wmd");
whitgl_load_model(1, "data/cube.wmd");
whitgl_timer_init();
whitgl_float uniform = 0;
whitgl_float time = 0;
whitgl_int shape = 0;
whitgl_fvec old_sound_pos = whitgl_fvec_zero;
bool running = true;
while(running)
{
whitgl_sound_update();
whitgl_timer_tick();
while(whitgl_timer_should_do_frame(60))
{
time += 1/60.0f;
whitgl_input_update();
whitgl_ivec mousepos = whitgl_input_mouse_pos(setup.pixel_size);
uniform = ((float)mousepos.x-setup.size.x/2)/30;
whitgl_fvec sound_pos = whitgl_fvec_scale_val(whitgl_fvec_sub(whitgl_fvec_divide(whitgl_ivec_to_fvec(mousepos), whitgl_ivec_to_fvec(setup.size)), whitgl_fvec_val(0.5)),20);
whitgl_fvec sound_velocity = whitgl_fvec_sub(sound_pos, old_sound_pos);
old_sound_pos = sound_pos;
whitgl_loop_set_position(1, sound_pos, sound_velocity);
if(whitgl_input_pressed(WHITGL_INPUT_A))
shape = (shape+1)%2;
if(whitgl_input_pressed(WHITGL_INPUT_ESC))
running = false;
if(whitgl_sys_should_close())
running = false;
}
for(i=0; i<texture_size.x*texture_size.y*4; i+=4)
data_texture[i+2] = whitgl_random_int(&seed, 32)+128;
whitgl_sys_update_image_from_data(1, texture_size, data_texture);
whitgl_sys_draw_init(0);
whitgl_float fov = whitgl_pi/2;
whitgl_fmat perspective = whitgl_fmat_perspective(fov, (float)setup.size.x/(float)setup.size.y, 0.1f, 10.0f);
whitgl_fvec3 up = {0,1,0};
whitgl_fvec3 camera_pos = {0,0,-2};
whitgl_fvec3 camera_to = {0,0,0};
whitgl_fmat view = whitgl_fmat_lookAt(camera_pos, camera_to, up);
whitgl_fmat model_matrix = whitgl_fmat_rot_y(time);
model_matrix = whitgl_fmat_multiply(model_matrix, whitgl_fmat_rot_z(time*3));
whitgl_sys_draw_model(shape, WHITGL_SHADER_MODEL, model_matrix, view, perspective);
whitgl_sprite sprite = {0, {0,0},{16,16}};
whitgl_ivec frametr = {1, 0};
whitgl_ivec pos = {16,0};
whitgl_sys_draw_sprite(sprite, frametr, pos);
whitgl_ivec framebr = {1, 1};
pos.x = 0; pos.y = 16;
whitgl_sys_draw_sprite(sprite, framebr, pos);
whitgl_iaabb line = {{1,1},{15,15}};
whitgl_sys_draw_line(line, whitgl_sys_color_white);
whitgl_fcircle circle = {{24,24},6};
whitgl_sys_draw_fcircle(circle, whitgl_sys_color_white, 8);
whitgl_set_shader_float(WHITGL_SHADER_POST, 0, uniform);
whitgl_set_shader_image(WHITGL_SHADER_POST, 1, 1);
whitgl_sys_draw_finish();
if(!whitgl_sys_window_focused())
whitgl_timer_sleep(1.0/30.0);
}
whitgl_input_shutdown();
whitgl_sound_shutdown();
whitgl_sys_close();
return 0;
}
| 28.730061 | 175 | 0.739483 | [
"shape"
] |
89e80252fdb99215006e6818143f43bd03bc48f0 | 4,983 | c | C | sel4-camkes-proj/kernel/src/arch/x86/kernel/xapic.c | mssabr01/Dissertation-Work | 355366ed658c6d18f83d6751bf66a7f83786e22d | [
"Apache-2.0"
] | null | null | null | sel4-camkes-proj/kernel/src/arch/x86/kernel/xapic.c | mssabr01/Dissertation-Work | 355366ed658c6d18f83d6751bf66a7f83786e22d | [
"Apache-2.0"
] | null | null | null | sel4-camkes-proj/kernel/src/arch/x86/kernel/xapic.c | mssabr01/Dissertation-Work | 355366ed658c6d18f83d6751bf66a7f83786e22d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2017, Data61
* Commonwealth Scientific and Industrial Research Organisation (CSIRO)
* ABN 41 687 119 230.
*
* This software may be distributed and modified according to the terms of
* the GNU General Public License version 2. Note that NO WARRANTY is provided.
* See "LICENSE_GPLv2.txt" for details.
*
* @TAG(DATA61_GPL)
*/
#include <config.h>
#include <arch/kernel/xapic.h>
#include <arch/kernel/x2apic.h>
#ifdef CONFIG_XAPIC
#ifdef CONFIG_USE_LOGICAL_IDS
/* using flat cluster mode we only support 8 cores */
compile_assert(number_of_cores_invalid_for_logical_ids, CONFIG_MAX_NUM_NODES <= 8)
BOOT_CODE static void
init_xapic_ldr(void)
{
uint32_t ldr;
apic_write_reg(APIC_DEST_FORMAT, XAPIC_DFR_FLAT);
ldr = apic_read_reg(APIC_LOGICAL_DEST) & MASK(XAPIC_LDR_SHIFT);
ldr |= (BIT(getCurrentCPUIndex()) << XAPIC_LDR_SHIFT);
apic_write_reg(APIC_LOGICAL_DEST, ldr);
}
#endif /* CONFIG_USE_LOGICAL_IDS */
BOOT_CODE bool_t
apic_enable(void)
{
apic_base_msr_t apic_base_msr;
apic_base_msr.words[0] = x86_rdmsr_low(IA32_APIC_BASE_MSR);
if (!apic_base_msr_get_enabled(apic_base_msr)) {
printf("APIC: Enabled bit not set\n");
return false;
}
if (x2apic_is_enabled()) {
printf("x2APIC enabled in BIOS but kernel does not support that\n");
return false;
}
#ifdef CONFIG_USE_LOGICAL_IDS
init_xapic_ldr();
#endif /* CONFIG_USE_LOGICAL_IDS */
return true;
}
bool_t apic_is_interrupt_pending(void)
{
word_t i;
/* read 256-bit register: each 32-bit word is 16 byte aligned */
assert(int_irq_min % 32 == 0);
for (i = int_irq_min; i <= int_irq_max; i += 32) {
if (apic_read_reg(APIC_IRR_BASE + i / 2) != 0) {
return true;
}
}
return false;
}
BOOT_CODE void
apic_send_init_ipi(cpu_id_t cpu_id)
{
apic_write_icr(
apic_icr2_new(
cpu_id /* dest */
).words[0],
apic_icr1_new(
0, /* dest_shorthand */
1, /* trigger_mode */
1, /* level */
0, /* delivery_status */
0, /* dest_mode */
5, /* delivery_mode */
0 /* vector */
).words[0]
);
apic_write_icr(
apic_icr2_new(
cpu_id /* dest */
).words[0],
apic_icr1_new(
0, /* dest_shorthand */
1, /* trigger_mode */
0, /* level */
0, /* delivery_status */
0, /* dest_mode */
5, /* delivery_mode */
0 /* vector */
).words[0]
);
}
BOOT_CODE void
apic_send_startup_ipi(cpu_id_t cpu_id, paddr_t startup_addr)
{
/* check if 4K aligned */
assert(IS_ALIGNED(startup_addr, PAGE_BITS));
/* check if startup_addr < 640K */
assert(startup_addr < 0xa0000);
startup_addr >>= PAGE_BITS;
apic_write_icr(
apic_icr2_new(
cpu_id /* dest */
).words[0],
apic_icr1_new(
0, /* dest_shorthand */
0, /* trigger_mode */
0, /* level */
0, /* delivery_status */
0, /* dest_mode */
6, /* delivery_mode */
startup_addr /* vector */
).words[0]
);
}
void apic_send_ipi_core(irq_t vector, cpu_id_t cpu_id)
{
apic_icr1_t icr1;
/* wait till we can send an IPI */
do {
icr1.words[0] = apic_read_reg(APIC_ICR1);
} while (apic_icr1_get_delivery_status(icr1));
apic_write_icr(
apic_icr2_new(
cpu_id /* dest */
).words[0],
apic_icr1_new(
0, /* dest_shorthand */
0, /* trigger_mode */
0, /* level */
0, /* delivery_status */
0, /* dest_mode */
0, /* delivery_mode */
vector /* vector */
).words[0]
);
}
void apic_send_ipi_cluster(irq_t vector, word_t mda)
{
apic_icr1_t icr1;
/* wait till we can send an IPI */
do {
icr1.words[0] = apic_read_reg(APIC_ICR1);
} while (apic_icr1_get_delivery_status(icr1));
apic_write_icr(
apic_icr2_new(
mda /* message destination address */
).words[0],
apic_icr1_new(
0, /* dest_shorthand */
0, /* trigger_mode */
0, /* level */
0, /* delivery_status */
1, /* dest_mode */
0, /* delivery_mode */
vector /* vector */
).words[0]
);
}
#endif /* CONFIG_XAPIC */
| 28.152542 | 82 | 0.515954 | [
"vector"
] |
89e862f32a4c2a8eacdfbaf9c407acb357e5b778 | 3,393 | c | C | seL4_tools/elfloader-tool/src/binaries/efi/gnuefi/reloc_aarch64.c | Nexusoft/LLL-OS | 7b0ad5afb339e9bebc65142ee89bded5344cedbe | [
"BSD-2-Clause"
] | 4 | 2020-08-07T19:48:01.000Z | 2020-10-16T20:05:17.000Z | seL4_tools/elfloader-tool/src/binaries/efi/gnuefi/reloc_aarch64.c | Nexusoft/LX-OS | 7b0ad5afb339e9bebc65142ee89bded5344cedbe | [
"BSD-2-Clause"
] | null | null | null | seL4_tools/elfloader-tool/src/binaries/efi/gnuefi/reloc_aarch64.c | Nexusoft/LX-OS | 7b0ad5afb339e9bebc65142ee89bded5344cedbe | [
"BSD-2-Clause"
] | 2 | 2020-08-13T01:48:40.000Z | 2020-09-17T07:34:42.000Z | /* SPDX-License-Identifier: BSD-3-Clause */
/*
* reloc_aarch64.c - position independent x86 ELF shared object relocator
* Copyright (C) 2014 Linaro Ltd. <ard.biesheuvel@linaro.org>
* Copyright (C) 1999 Hewlett-Packard Co.
* Contributed by David Mosberger <davidm@hpl.hp.com>.
*
* 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 Hewlett-Packard Co. 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 ANYDIRECT, 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 <elfloader_common.h>
#include <binaries/efi/efi.h>
#include <binaries/elf/elf.h>
#include <binaries/elf/elf64.h>
long unsigned int _relocate(unsigned long ldbase, struct Elf64_Dyn *dyn,
void *image UNUSED,
void *systab UNUSED)
{
long relsz = 0, relent = 0;
struct Elf64_Rela *rel = 0;
unsigned long *addr;
int i;
for (i = 0; dyn[i].d_tag != DT_NULL; ++i) {
switch (dyn[i].d_tag) {
case DT_RELA:
rel = (struct Elf64_Rela *)
((unsigned long)dyn[i].d_un.d_ptr
+ ldbase);
break;
case DT_RELASZ:
relsz = dyn[i].d_un.d_val;
break;
case DT_RELAENT:
relent = dyn[i].d_un.d_val;
break;
default:
break;
}
}
if (!rel && relent == 0) {
return EFI_SUCCESS;
}
if (!rel || relent == 0) {
return EFI_LOAD_ERROR;
}
while (relsz > 0) {
/* apply the relocs */
switch (ELF64_R_TYPE(rel->r_info)) {
case R_AARCH64_NONE:
break;
case R_AARCH64_RELATIVE:
addr = (unsigned long *)
(ldbase + rel->r_offset);
*addr = ldbase + rel->r_addend;
break;
default:
break;
}
rel = (struct Elf64_Rela *)((char *) rel + relent);
relsz -= relent;
}
return EFI_SUCCESS;
}
| 32.625 | 73 | 0.62069 | [
"object"
] |
89f4a695aea0f2c79b7a346c10770ee604b21e86 | 5,718 | h | C | util/folder/path.h | ibr11/catboost | 842a25b4fb856a61564b163b16a3f49ba35fdc14 | [
"Apache-2.0"
] | 4 | 2020-06-24T06:07:52.000Z | 2021-04-16T22:58:09.000Z | util/folder/path.h | birichie/catboost | de75c6af12cf490700e76c22072fbdc15b35d679 | [
"Apache-2.0"
] | 6 | 2020-02-18T22:12:29.000Z | 2020-02-18T22:31:26.000Z | util/folder/path.h | birichie/catboost | de75c6af12cf490700e76c22072fbdc15b35d679 | [
"Apache-2.0"
] | 1 | 2021-04-27T23:40:09.000Z | 2021-04-27T23:40:09.000Z | #pragma once
#include "pathsplit.h"
#include <util/generic/ptr.h>
#include <util/generic/strbuf.h>
#include <util/generic/string.h>
#include <util/generic/vector.h>
#include <util/string/cast.h>
#include <util/system/fstat.h>
#include <util/system/platform.h>
#include <util/system/sysstat.h>
#include <util/system/yassert.h>
#include <utility>
/**
* Class behaviour is platform-dependent.
* It uses platform-dependent separators for path-reconstructing operations.
*/
class TFsPath {
private:
struct TSplit;
public:
TFsPath();
TFsPath(const TString& path);
TFsPath(const TStringBuf path);
TFsPath(const char* path);
void CheckDefined() const;
inline bool IsDefined() const {
return Path_.length() > 0;
}
inline explicit operator bool() const {
return IsDefined();
}
inline const char* c_str() const {
return Path_.c_str();
}
inline operator const TString&() const {
return Path_;
}
inline bool operator==(const TFsPath& that) const {
return Path_ == that.Path_;
}
inline bool operator!=(const TFsPath& that) const {
return Path_ != that.Path_;
}
TFsPath& operator/=(const TFsPath& that);
friend TFsPath operator/(const TFsPath& s, const TFsPath& p) {
TFsPath ret(s);
return ret /= p;
}
const TPathSplit& PathSplit() const;
TFsPath& Fix();
inline const TString& GetPath() const {
return Path_;
}
/// last component of path, or "/" if root
TString GetName() const;
/**
* "a.b.tmp" -> "tmp"
* "a.tmp" -> "tmp"
* ".tmp" -> ""
*/
TString GetExtension() const;
bool IsAbsolute() const;
bool IsRelative() const;
/**
* TFsPath("/a/b").IsSubpathOf("/a") -> true
*
* TFsPath("/a").IsSubpathOf("/a") -> false
*
* TFsPath("/a").IsSubpathOf("/other/path") -> false
* @param that - presumable parent path of this
* @return True if this is a subpath of that and false otherwise.
*/
bool IsSubpathOf(const TFsPath& that) const;
/**
* TFsPath("/a/b").IsNonStrictSubpathOf("/a") -> true
*
* TFsPath("/a").IsNonStrictSubpathOf("/a") -> true
*
* TFsPath("/a").IsNonStrictSubpathOf("/other/path") -> false
* @param that - presumable parent path of this
* @return True if this is a subpath of that or they are equivalent and false otherwise.
*/
bool IsNonStrictSubpathOf(const TFsPath& that) const;
bool IsContainerOf(const TFsPath& that) const {
return that.IsSubpathOf(*this);
}
TFsPath RelativeTo(const TFsPath& root) const; //must be subpath of root
/**
* @returns relative path or empty path if root equals to this.
*/
TFsPath RelativePath(const TFsPath& root) const; //..; for relative paths 1st component must be the same
/**
* Never fails. Returns this if already a root.
*/
TFsPath Parent() const;
TString Basename() const {
return GetName();
}
TString Dirname() const {
return Parent();
}
TFsPath Child(const TString& name) const;
/**
* @brief create this directory
*
* @param mode specifies permissions to use as described in mkdir(2), makes sense only on Unix-like systems.
*
* Nothing to do if dir exists.
*/
void MkDir(const int mode = MODE0777) const;
/**
* @brief create this directory and all parent directories as needed
*
* @param mode specifies permissions to use as described in mkdir(2), makes sense only on Unix-like systems.
*/
void MkDirs(const int mode = MODE0777) const;
// XXX: rewrite to return iterator
void List(TVector<TFsPath>& children) const;
void ListNames(TVector<TString>& children) const;
// Check, if path contains at least one component with a specific name.
bool Contains(const TString& component) const;
// fails to delete non-empty directory
void DeleteIfExists() const;
// delete recursively. Does nothing if not exists
void ForceDelete() const;
// XXX: ino
inline bool Stat(TFileStat& stat) const {
stat = TFileStat(Path_.data());
return stat.Mode;
}
bool Exists() const;
/// false if not exists
bool IsDirectory() const;
/// false if not exists
bool IsFile() const;
/// false if not exists
bool IsSymlink() const;
/// throw TIoException if not exists
void CheckExists() const;
void RenameTo(const TString& newPath) const;
void RenameTo(const char* newPath) const;
void RenameTo(const TFsPath& newFile) const;
void ForceRenameTo(const TString& newPath) const;
void CopyTo(const TString& newPath, bool force) const;
void Touch() const;
TFsPath RealPath() const;
TFsPath RealLocation() const;
TFsPath ReadLink() const;
/// always absolute
static TFsPath Cwd();
inline void Swap(TFsPath& p) noexcept {
DoSwap(Path_, p.Path_);
Split_.Swap(p.Split_);
}
private:
void InitSplit() const;
TSplit& GetSplit() const;
private:
TString Path_;
/// cache
mutable TSimpleIntrusivePtr<TSplit> Split_;
};
namespace NPrivate {
inline void AppendToFsPath(TFsPath&) {
}
template <class T, class... Ts>
void AppendToFsPath(TFsPath& fsPath, const T& arg, Ts&&... args) {
fsPath /= TFsPath(arg);
AppendToFsPath(fsPath, std::forward<Ts>(args)...);
}
}
template <class... Ts>
TString JoinFsPaths(Ts&&... args) {
TFsPath fsPath;
::NPrivate::AppendToFsPath(fsPath, std::forward<Ts>(args)...);
return fsPath.GetPath();
}
| 25.300885 | 112 | 0.625044 | [
"vector"
] |
89f8eb5052e5ab04b9626f9370b4951e7991901d | 649 | h | C | src/factories/headers/TS_FactoryCommand.h | thomasschwarz96/ts-timetracker | df3a190fac0d91df31dd871edd0bcf6d3a688d2d | [
"MIT"
] | 7 | 2020-02-03T08:24:16.000Z | 2020-02-26T23:51:36.000Z | src/factories/headers/TS_FactoryCommand.h | tomschwarz/ts-timetracker | df3a190fac0d91df31dd871edd0bcf6d3a688d2d | [
"MIT"
] | null | null | null | src/factories/headers/TS_FactoryCommand.h | tomschwarz/ts-timetracker | df3a190fac0d91df31dd871edd0bcf6d3a688d2d | [
"MIT"
] | null | null | null | /**
* TS-FactoryCommand
*
* Factory class for command building.
*
* @package TS-TimeTracker
* @author Thomas Schwarz
* @copyright Copyright (c) 2019, Thomas Schwarz
* @license MIT License (https://opensource.org/licenses/MIT)
* @since Version 0.1.0
* @filesource
*/
#ifndef TS_TIMETRACKER_TS_FACTORYCOMMAND_H
#define TS_TIMETRACKER_TS_FACTORYCOMMAND_H
#include "TS_IModel.h"
#include "TS_Command.h"
class TS_FactoryCommand
{
public:
TS_FactoryCommand();
~TS_FactoryCommand() = default;
static TS_Command* build(char *command, char *arguments, TS_IModel* model);
};
#endif //TS_TIMETRACKER_TS_HELPER_H
| 22.37931 | 79 | 0.718028 | [
"model"
] |
89fc5363e68d44a52d267086a853e77741483d95 | 5,494 | h | C | ge/graph/passes/buffer_pool_memory_pass.h | mindspore-ai/graphengine | 460406cbd691b963d125837f022be5d8abd1a637 | [
"Apache-2.0"
] | 207 | 2020-03-28T02:12:50.000Z | 2021-11-23T18:27:45.000Z | ge/graph/passes/buffer_pool_memory_pass.h | mindspore-ai/graphengine | 460406cbd691b963d125837f022be5d8abd1a637 | [
"Apache-2.0"
] | 4 | 2020-04-17T07:32:44.000Z | 2021-06-26T04:55:03.000Z | ge/graph/passes/buffer_pool_memory_pass.h | mindspore-ai/graphengine | 460406cbd691b963d125837f022be5d8abd1a637 | [
"Apache-2.0"
] | 13 | 2020-03-28T02:52:26.000Z | 2021-07-03T23:12:54.000Z | /**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef GE_GRAPH_PASSES_BUFFER_POOL_MEMORY_PASS_H_
#define GE_GRAPH_PASSES_BUFFER_POOL_MEMORY_PASS_H_
#include <queue>
#include "external/graph/graph.h"
#include "inc/graph_pass.h"
namespace ge {
class BufferPoolMemoryPass : public GraphPass {
public:
explicit BufferPoolMemoryPass() : logic_event_num_(0) {}
~BufferPoolMemoryPass() override = default;
struct BufferPool {
int64_t pool_id = 0;
int64_t pool_size = 0;
std::unordered_map<NodePtr, NodePtr> buffer_node_to_calc;
BufferPool(int64_t id, int64_t size, const std::unordered_map<NodePtr, NodePtr> &node_map)
: pool_id(id), pool_size(size), buffer_node_to_calc(node_map) {}
};
struct BufferPoolNodeItem {
NodePtr node = nullptr;
NodePtr out_calc_node = nullptr;
NodePtr pre_buffer_pool_node = nullptr;
int64_t total_size = 0;
int64_t offset_start = 0;
int64_t offset_end = 0;
bool is_last_input = true;
BufferPoolNodeItem(const NodePtr &buffer_n, const NodePtr &calc_n, const NodePtr &pre_buffer_n,
int64_t size, int64_t start, int64_t end, bool last)
: node(std::move(buffer_n)),
out_calc_node(std::move(calc_n)),
pre_buffer_pool_node(std::move(pre_buffer_n)),
total_size(size),
offset_start(start),
offset_end(end),
is_last_input(last) {}
BufferPoolNodeItem(const NodePtr &buffer_n, int64_t start, int64_t end)
: node(std::move(buffer_n)),
out_calc_node(nullptr),
pre_buffer_pool_node(nullptr),
total_size(0),
offset_start(start),
offset_end(end),
is_last_input(true) {}
};
Status Run(ComputeGraphPtr graph) override;
private:
static void ClearQueue(std::queue<std::pair<std::string, uint32_t>> &q);
static Status IsBufferPoolMemEnable(const ComputeGraphPtr &graph);
static Status CheckBufferPoolSize(int64_t total_size, int64_t pool_id, int64_t buffer_pool_size,
std::unordered_map<int64_t, int64_t> &calc_total_size);
static Status TryToFixNodeOrder(NodePtr &pre_node, NodePtr &curr_node, bool ¬_change);
Status InsertMemCpyNodeAfter(ComputeGraphPtr &graph, NodePtr &node);
Status CopyOutForMultiUsedOutput(ComputeGraphPtr &graph);
Status GetBufferPoolAndPeerCalcNodes(const ComputeGraphPtr &graph);
Status SetBufferPoolSize(const std::string &batch_label, int64_t id, int64_t size);
Status AllocateAllBufferPoolSpace();
Status AllocateSpaceInBatch(const std::map<int64_t, std::vector<NodePtr>> &calc_nodes,
const std::unordered_map<int64_t, int64_t> &buffer_pool_size_map,
const std::unordered_map<NodePtr, NodePtr> &buffer_node_to_calc,
std::unordered_map<NodePtr, std::vector<BufferPoolNodeItem>> &buffer_pool_nodes_item);
Status AllocateSpaceInBufferPool(const BufferPool &buffer_pool,
const std::vector<NodePtr> &calc_nodes_in_pool,
std::unordered_map<NodePtr, std::vector<BufferPoolNodeItem>> &buffer_pool_nodes_item);
Status AllocateSpaceForBufferPoolNode(int64_t &next_start,
const BufferPool buffer_pool,
BufferPoolNodeItem &buffer_pool_node_item,
std::queue<BufferPoolNodeItem> &node_mem_range_in_pool);
NodePtr GetOffsetAndDependency(int64_t &next_start,
int64_t total_mem_size,
int64_t buffer_pool_size,
const std::unordered_map<NodePtr, NodePtr> &buffer_node_to_calc,
std::queue<BufferPoolNodeItem> &nodes_in_buffer);
Status FixTheTimingOfDependentNodes(NodePtr &dependent_calc_node, NodePtr &curr_pool_node);
uint32_t GenerateEventId(const std::string &node_name, std::queue<std::pair<std::string, uint32_t>> &event_queue);
Status SetResultOfMemoryAndEvent();
// Use map to ensure that each visit is in the order of batch label and pool id
std::map<std::string, std::map<int64_t, std::vector<NodePtr>>> calc_nodes_;
std::unordered_map<std::string, std::unordered_map<NodePtr, NodePtr>> buffer_node_to_calc_;
std::unordered_map<std::string, std::unordered_map<NodePtr, std::vector<BufferPoolNodeItem>>> peer_buffer_node_item_;
std::unordered_map<std::string, std::unordered_map<int64_t, int64_t>> buffer_pool_size_;
uint32_t logic_event_num_;
std::queue<std::pair<std::string, uint32_t>> mem_ctrl_event_;
std::queue<std::pair<std::string, uint32_t>> stream_ctrl_event_;
std::unordered_map<NodePtr, std::vector<std::string>> node_event_multiplexing_;
std::unordered_map<NodePtr, std::vector<int64_t>> buffer_node_logical_offset_;
};
} // namespace ge
#endif // GE_GRAPH_PASSES_BUFFER_POOL_MEMORY_PASS_H_
| 40.10219 | 119 | 0.702767 | [
"vector"
] |
89fca5a17b9a9e96df7a8e2b9cb35d554d02f861 | 17,590 | h | C | Descending Europa/Temp/StagingArea/Data/il2cppOutput/mscorlib_System_Text_Encoding2012439129.h | screwylightbulb/europa | 3dcc98369c8066cb2310143329535206751c8846 | [
"MIT"
] | 11 | 2016-07-22T19:58:09.000Z | 2021-09-21T12:51:40.000Z | Descending Europa/Temp/StagingArea/Data/il2cppOutput/mscorlib_System_Text_Encoding2012439129.h | screwylightbulb/europa | 3dcc98369c8066cb2310143329535206751c8846 | [
"MIT"
] | 1 | 2018-05-07T14:32:13.000Z | 2018-05-08T09:15:30.000Z | iOS/Classes/Native/mscorlib_System_Text_Encoding2012439129.h | mopsicus/unity-share-plugin-ios-android | 3ee99aef36034a1e4d7b156172953f9b4dfa696f | [
"MIT"
] | null | null | null | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
// System.Text.DecoderFallback
struct DecoderFallback_t649129352;
// System.Text.EncoderFallback
struct EncoderFallback_t1901620832;
// System.Reflection.Assembly
struct Assembly_t1418687608;
// System.Object[]
struct ObjectU5BU5D_t1108656482;
// System.String
struct String_t;
// System.Text.Encoding
struct Encoding_t2012439129;
// System.Object
struct Il2CppObject;
#include "mscorlib_System_Object4170816371.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Text.Encoding
struct Encoding_t2012439129 : public Il2CppObject
{
public:
// System.Int32 System.Text.Encoding::codePage
int32_t ___codePage_0;
// System.Int32 System.Text.Encoding::windows_code_page
int32_t ___windows_code_page_1;
// System.Boolean System.Text.Encoding::is_readonly
bool ___is_readonly_2;
// System.Text.DecoderFallback System.Text.Encoding::decoder_fallback
DecoderFallback_t649129352 * ___decoder_fallback_3;
// System.Text.EncoderFallback System.Text.Encoding::encoder_fallback
EncoderFallback_t1901620832 * ___encoder_fallback_4;
// System.String System.Text.Encoding::body_name
String_t* ___body_name_8;
// System.String System.Text.Encoding::encoding_name
String_t* ___encoding_name_9;
// System.String System.Text.Encoding::header_name
String_t* ___header_name_10;
// System.Boolean System.Text.Encoding::is_mail_news_display
bool ___is_mail_news_display_11;
// System.Boolean System.Text.Encoding::is_mail_news_save
bool ___is_mail_news_save_12;
// System.Boolean System.Text.Encoding::is_browser_save
bool ___is_browser_save_13;
// System.Boolean System.Text.Encoding::is_browser_display
bool ___is_browser_display_14;
// System.String System.Text.Encoding::web_name
String_t* ___web_name_15;
public:
inline static int32_t get_offset_of_codePage_0() { return static_cast<int32_t>(offsetof(Encoding_t2012439129, ___codePage_0)); }
inline int32_t get_codePage_0() const { return ___codePage_0; }
inline int32_t* get_address_of_codePage_0() { return &___codePage_0; }
inline void set_codePage_0(int32_t value)
{
___codePage_0 = value;
}
inline static int32_t get_offset_of_windows_code_page_1() { return static_cast<int32_t>(offsetof(Encoding_t2012439129, ___windows_code_page_1)); }
inline int32_t get_windows_code_page_1() const { return ___windows_code_page_1; }
inline int32_t* get_address_of_windows_code_page_1() { return &___windows_code_page_1; }
inline void set_windows_code_page_1(int32_t value)
{
___windows_code_page_1 = value;
}
inline static int32_t get_offset_of_is_readonly_2() { return static_cast<int32_t>(offsetof(Encoding_t2012439129, ___is_readonly_2)); }
inline bool get_is_readonly_2() const { return ___is_readonly_2; }
inline bool* get_address_of_is_readonly_2() { return &___is_readonly_2; }
inline void set_is_readonly_2(bool value)
{
___is_readonly_2 = value;
}
inline static int32_t get_offset_of_decoder_fallback_3() { return static_cast<int32_t>(offsetof(Encoding_t2012439129, ___decoder_fallback_3)); }
inline DecoderFallback_t649129352 * get_decoder_fallback_3() const { return ___decoder_fallback_3; }
inline DecoderFallback_t649129352 ** get_address_of_decoder_fallback_3() { return &___decoder_fallback_3; }
inline void set_decoder_fallback_3(DecoderFallback_t649129352 * value)
{
___decoder_fallback_3 = value;
Il2CppCodeGenWriteBarrier(&___decoder_fallback_3, value);
}
inline static int32_t get_offset_of_encoder_fallback_4() { return static_cast<int32_t>(offsetof(Encoding_t2012439129, ___encoder_fallback_4)); }
inline EncoderFallback_t1901620832 * get_encoder_fallback_4() const { return ___encoder_fallback_4; }
inline EncoderFallback_t1901620832 ** get_address_of_encoder_fallback_4() { return &___encoder_fallback_4; }
inline void set_encoder_fallback_4(EncoderFallback_t1901620832 * value)
{
___encoder_fallback_4 = value;
Il2CppCodeGenWriteBarrier(&___encoder_fallback_4, value);
}
inline static int32_t get_offset_of_body_name_8() { return static_cast<int32_t>(offsetof(Encoding_t2012439129, ___body_name_8)); }
inline String_t* get_body_name_8() const { return ___body_name_8; }
inline String_t** get_address_of_body_name_8() { return &___body_name_8; }
inline void set_body_name_8(String_t* value)
{
___body_name_8 = value;
Il2CppCodeGenWriteBarrier(&___body_name_8, value);
}
inline static int32_t get_offset_of_encoding_name_9() { return static_cast<int32_t>(offsetof(Encoding_t2012439129, ___encoding_name_9)); }
inline String_t* get_encoding_name_9() const { return ___encoding_name_9; }
inline String_t** get_address_of_encoding_name_9() { return &___encoding_name_9; }
inline void set_encoding_name_9(String_t* value)
{
___encoding_name_9 = value;
Il2CppCodeGenWriteBarrier(&___encoding_name_9, value);
}
inline static int32_t get_offset_of_header_name_10() { return static_cast<int32_t>(offsetof(Encoding_t2012439129, ___header_name_10)); }
inline String_t* get_header_name_10() const { return ___header_name_10; }
inline String_t** get_address_of_header_name_10() { return &___header_name_10; }
inline void set_header_name_10(String_t* value)
{
___header_name_10 = value;
Il2CppCodeGenWriteBarrier(&___header_name_10, value);
}
inline static int32_t get_offset_of_is_mail_news_display_11() { return static_cast<int32_t>(offsetof(Encoding_t2012439129, ___is_mail_news_display_11)); }
inline bool get_is_mail_news_display_11() const { return ___is_mail_news_display_11; }
inline bool* get_address_of_is_mail_news_display_11() { return &___is_mail_news_display_11; }
inline void set_is_mail_news_display_11(bool value)
{
___is_mail_news_display_11 = value;
}
inline static int32_t get_offset_of_is_mail_news_save_12() { return static_cast<int32_t>(offsetof(Encoding_t2012439129, ___is_mail_news_save_12)); }
inline bool get_is_mail_news_save_12() const { return ___is_mail_news_save_12; }
inline bool* get_address_of_is_mail_news_save_12() { return &___is_mail_news_save_12; }
inline void set_is_mail_news_save_12(bool value)
{
___is_mail_news_save_12 = value;
}
inline static int32_t get_offset_of_is_browser_save_13() { return static_cast<int32_t>(offsetof(Encoding_t2012439129, ___is_browser_save_13)); }
inline bool get_is_browser_save_13() const { return ___is_browser_save_13; }
inline bool* get_address_of_is_browser_save_13() { return &___is_browser_save_13; }
inline void set_is_browser_save_13(bool value)
{
___is_browser_save_13 = value;
}
inline static int32_t get_offset_of_is_browser_display_14() { return static_cast<int32_t>(offsetof(Encoding_t2012439129, ___is_browser_display_14)); }
inline bool get_is_browser_display_14() const { return ___is_browser_display_14; }
inline bool* get_address_of_is_browser_display_14() { return &___is_browser_display_14; }
inline void set_is_browser_display_14(bool value)
{
___is_browser_display_14 = value;
}
inline static int32_t get_offset_of_web_name_15() { return static_cast<int32_t>(offsetof(Encoding_t2012439129, ___web_name_15)); }
inline String_t* get_web_name_15() const { return ___web_name_15; }
inline String_t** get_address_of_web_name_15() { return &___web_name_15; }
inline void set_web_name_15(String_t* value)
{
___web_name_15 = value;
Il2CppCodeGenWriteBarrier(&___web_name_15, value);
}
};
struct Encoding_t2012439129_StaticFields
{
public:
// System.Reflection.Assembly System.Text.Encoding::i18nAssembly
Assembly_t1418687608 * ___i18nAssembly_5;
// System.Boolean System.Text.Encoding::i18nDisabled
bool ___i18nDisabled_6;
// System.Object[] System.Text.Encoding::encodings
ObjectU5BU5D_t1108656482* ___encodings_7;
// System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::asciiEncoding
Encoding_t2012439129 * ___asciiEncoding_16;
// System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::bigEndianEncoding
Encoding_t2012439129 * ___bigEndianEncoding_17;
// System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::defaultEncoding
Encoding_t2012439129 * ___defaultEncoding_18;
// System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::utf7Encoding
Encoding_t2012439129 * ___utf7Encoding_19;
// System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::utf8EncodingWithMarkers
Encoding_t2012439129 * ___utf8EncodingWithMarkers_20;
// System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::utf8EncodingWithoutMarkers
Encoding_t2012439129 * ___utf8EncodingWithoutMarkers_21;
// System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::unicodeEncoding
Encoding_t2012439129 * ___unicodeEncoding_22;
// System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::isoLatin1Encoding
Encoding_t2012439129 * ___isoLatin1Encoding_23;
// System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::utf8EncodingUnsafe
Encoding_t2012439129 * ___utf8EncodingUnsafe_24;
// System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::utf32Encoding
Encoding_t2012439129 * ___utf32Encoding_25;
// System.Text.Encoding modreq(System.Runtime.CompilerServices.IsVolatile) System.Text.Encoding::bigEndianUTF32Encoding
Encoding_t2012439129 * ___bigEndianUTF32Encoding_26;
// System.Object System.Text.Encoding::lockobj
Il2CppObject * ___lockobj_27;
public:
inline static int32_t get_offset_of_i18nAssembly_5() { return static_cast<int32_t>(offsetof(Encoding_t2012439129_StaticFields, ___i18nAssembly_5)); }
inline Assembly_t1418687608 * get_i18nAssembly_5() const { return ___i18nAssembly_5; }
inline Assembly_t1418687608 ** get_address_of_i18nAssembly_5() { return &___i18nAssembly_5; }
inline void set_i18nAssembly_5(Assembly_t1418687608 * value)
{
___i18nAssembly_5 = value;
Il2CppCodeGenWriteBarrier(&___i18nAssembly_5, value);
}
inline static int32_t get_offset_of_i18nDisabled_6() { return static_cast<int32_t>(offsetof(Encoding_t2012439129_StaticFields, ___i18nDisabled_6)); }
inline bool get_i18nDisabled_6() const { return ___i18nDisabled_6; }
inline bool* get_address_of_i18nDisabled_6() { return &___i18nDisabled_6; }
inline void set_i18nDisabled_6(bool value)
{
___i18nDisabled_6 = value;
}
inline static int32_t get_offset_of_encodings_7() { return static_cast<int32_t>(offsetof(Encoding_t2012439129_StaticFields, ___encodings_7)); }
inline ObjectU5BU5D_t1108656482* get_encodings_7() const { return ___encodings_7; }
inline ObjectU5BU5D_t1108656482** get_address_of_encodings_7() { return &___encodings_7; }
inline void set_encodings_7(ObjectU5BU5D_t1108656482* value)
{
___encodings_7 = value;
Il2CppCodeGenWriteBarrier(&___encodings_7, value);
}
inline static int32_t get_offset_of_asciiEncoding_16() { return static_cast<int32_t>(offsetof(Encoding_t2012439129_StaticFields, ___asciiEncoding_16)); }
inline Encoding_t2012439129 * get_asciiEncoding_16() const { return ___asciiEncoding_16; }
inline Encoding_t2012439129 ** get_address_of_asciiEncoding_16() { return &___asciiEncoding_16; }
inline void set_asciiEncoding_16(Encoding_t2012439129 * value)
{
___asciiEncoding_16 = value;
Il2CppCodeGenWriteBarrier(&___asciiEncoding_16, value);
}
inline static int32_t get_offset_of_bigEndianEncoding_17() { return static_cast<int32_t>(offsetof(Encoding_t2012439129_StaticFields, ___bigEndianEncoding_17)); }
inline Encoding_t2012439129 * get_bigEndianEncoding_17() const { return ___bigEndianEncoding_17; }
inline Encoding_t2012439129 ** get_address_of_bigEndianEncoding_17() { return &___bigEndianEncoding_17; }
inline void set_bigEndianEncoding_17(Encoding_t2012439129 * value)
{
___bigEndianEncoding_17 = value;
Il2CppCodeGenWriteBarrier(&___bigEndianEncoding_17, value);
}
inline static int32_t get_offset_of_defaultEncoding_18() { return static_cast<int32_t>(offsetof(Encoding_t2012439129_StaticFields, ___defaultEncoding_18)); }
inline Encoding_t2012439129 * get_defaultEncoding_18() const { return ___defaultEncoding_18; }
inline Encoding_t2012439129 ** get_address_of_defaultEncoding_18() { return &___defaultEncoding_18; }
inline void set_defaultEncoding_18(Encoding_t2012439129 * value)
{
___defaultEncoding_18 = value;
Il2CppCodeGenWriteBarrier(&___defaultEncoding_18, value);
}
inline static int32_t get_offset_of_utf7Encoding_19() { return static_cast<int32_t>(offsetof(Encoding_t2012439129_StaticFields, ___utf7Encoding_19)); }
inline Encoding_t2012439129 * get_utf7Encoding_19() const { return ___utf7Encoding_19; }
inline Encoding_t2012439129 ** get_address_of_utf7Encoding_19() { return &___utf7Encoding_19; }
inline void set_utf7Encoding_19(Encoding_t2012439129 * value)
{
___utf7Encoding_19 = value;
Il2CppCodeGenWriteBarrier(&___utf7Encoding_19, value);
}
inline static int32_t get_offset_of_utf8EncodingWithMarkers_20() { return static_cast<int32_t>(offsetof(Encoding_t2012439129_StaticFields, ___utf8EncodingWithMarkers_20)); }
inline Encoding_t2012439129 * get_utf8EncodingWithMarkers_20() const { return ___utf8EncodingWithMarkers_20; }
inline Encoding_t2012439129 ** get_address_of_utf8EncodingWithMarkers_20() { return &___utf8EncodingWithMarkers_20; }
inline void set_utf8EncodingWithMarkers_20(Encoding_t2012439129 * value)
{
___utf8EncodingWithMarkers_20 = value;
Il2CppCodeGenWriteBarrier(&___utf8EncodingWithMarkers_20, value);
}
inline static int32_t get_offset_of_utf8EncodingWithoutMarkers_21() { return static_cast<int32_t>(offsetof(Encoding_t2012439129_StaticFields, ___utf8EncodingWithoutMarkers_21)); }
inline Encoding_t2012439129 * get_utf8EncodingWithoutMarkers_21() const { return ___utf8EncodingWithoutMarkers_21; }
inline Encoding_t2012439129 ** get_address_of_utf8EncodingWithoutMarkers_21() { return &___utf8EncodingWithoutMarkers_21; }
inline void set_utf8EncodingWithoutMarkers_21(Encoding_t2012439129 * value)
{
___utf8EncodingWithoutMarkers_21 = value;
Il2CppCodeGenWriteBarrier(&___utf8EncodingWithoutMarkers_21, value);
}
inline static int32_t get_offset_of_unicodeEncoding_22() { return static_cast<int32_t>(offsetof(Encoding_t2012439129_StaticFields, ___unicodeEncoding_22)); }
inline Encoding_t2012439129 * get_unicodeEncoding_22() const { return ___unicodeEncoding_22; }
inline Encoding_t2012439129 ** get_address_of_unicodeEncoding_22() { return &___unicodeEncoding_22; }
inline void set_unicodeEncoding_22(Encoding_t2012439129 * value)
{
___unicodeEncoding_22 = value;
Il2CppCodeGenWriteBarrier(&___unicodeEncoding_22, value);
}
inline static int32_t get_offset_of_isoLatin1Encoding_23() { return static_cast<int32_t>(offsetof(Encoding_t2012439129_StaticFields, ___isoLatin1Encoding_23)); }
inline Encoding_t2012439129 * get_isoLatin1Encoding_23() const { return ___isoLatin1Encoding_23; }
inline Encoding_t2012439129 ** get_address_of_isoLatin1Encoding_23() { return &___isoLatin1Encoding_23; }
inline void set_isoLatin1Encoding_23(Encoding_t2012439129 * value)
{
___isoLatin1Encoding_23 = value;
Il2CppCodeGenWriteBarrier(&___isoLatin1Encoding_23, value);
}
inline static int32_t get_offset_of_utf8EncodingUnsafe_24() { return static_cast<int32_t>(offsetof(Encoding_t2012439129_StaticFields, ___utf8EncodingUnsafe_24)); }
inline Encoding_t2012439129 * get_utf8EncodingUnsafe_24() const { return ___utf8EncodingUnsafe_24; }
inline Encoding_t2012439129 ** get_address_of_utf8EncodingUnsafe_24() { return &___utf8EncodingUnsafe_24; }
inline void set_utf8EncodingUnsafe_24(Encoding_t2012439129 * value)
{
___utf8EncodingUnsafe_24 = value;
Il2CppCodeGenWriteBarrier(&___utf8EncodingUnsafe_24, value);
}
inline static int32_t get_offset_of_utf32Encoding_25() { return static_cast<int32_t>(offsetof(Encoding_t2012439129_StaticFields, ___utf32Encoding_25)); }
inline Encoding_t2012439129 * get_utf32Encoding_25() const { return ___utf32Encoding_25; }
inline Encoding_t2012439129 ** get_address_of_utf32Encoding_25() { return &___utf32Encoding_25; }
inline void set_utf32Encoding_25(Encoding_t2012439129 * value)
{
___utf32Encoding_25 = value;
Il2CppCodeGenWriteBarrier(&___utf32Encoding_25, value);
}
inline static int32_t get_offset_of_bigEndianUTF32Encoding_26() { return static_cast<int32_t>(offsetof(Encoding_t2012439129_StaticFields, ___bigEndianUTF32Encoding_26)); }
inline Encoding_t2012439129 * get_bigEndianUTF32Encoding_26() const { return ___bigEndianUTF32Encoding_26; }
inline Encoding_t2012439129 ** get_address_of_bigEndianUTF32Encoding_26() { return &___bigEndianUTF32Encoding_26; }
inline void set_bigEndianUTF32Encoding_26(Encoding_t2012439129 * value)
{
___bigEndianUTF32Encoding_26 = value;
Il2CppCodeGenWriteBarrier(&___bigEndianUTF32Encoding_26, value);
}
inline static int32_t get_offset_of_lockobj_27() { return static_cast<int32_t>(offsetof(Encoding_t2012439129_StaticFields, ___lockobj_27)); }
inline Il2CppObject * get_lockobj_27() const { return ___lockobj_27; }
inline Il2CppObject ** get_address_of_lockobj_27() { return &___lockobj_27; }
inline void set_lockobj_27(Il2CppObject * value)
{
___lockobj_27 = value;
Il2CppCodeGenWriteBarrier(&___lockobj_27, value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| 49.971591 | 180 | 0.827914 | [
"object"
] |
d607f84e107544867134c61ee13d1f1e85bf9b65 | 56,091 | c | C | emuboot/src/northbridge/intel/gm45/raminit.c | leetobin/firebrick | 9109e8025d949357a0320aa2903bbad876593143 | [
"Apache-2.0"
] | 9 | 2015-03-24T12:39:13.000Z | 2021-03-31T20:08:03.000Z | emuboot/src/northbridge/intel/gm45/raminit.c | leetobin/firebrickRemote | e825e194d09752b32db3c8d5a9b8d0e912030df9 | [
"Apache-2.0"
] | null | null | null | emuboot/src/northbridge/intel/gm45/raminit.c | leetobin/firebrickRemote | e825e194d09752b32db3c8d5a9b8d0e912030df9 | [
"Apache-2.0"
] | 3 | 2015-11-23T14:14:18.000Z | 2018-03-14T11:49:00.000Z | /*
* This file is part of the coreboot project.
*
* Copyright (C) 2012 secunet Security Networks AG
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; version 2 of
* the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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 St, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
#include <stdint.h>
#include <arch/cpu.h>
#include <arch/io.h>
#include <device/pci_def.h>
#include <device/pnp_def.h>
#include <spd.h>
#include <console/console.h>
#include <lib.h>
#include "delay.h"
#include "gm45.h"
static const gmch_gfx_t gmch_gfx_types[][5] = {
/* MAX_667MHz MAX_533MHz MAX_400MHz MAX_333MHz MAX_800MHz */
{ GMCH_UNKNOWN, GMCH_UNKNOWN, GMCH_UNKNOWN, GMCH_UNKNOWN, GMCH_UNKNOWN },
{ GMCH_GM47, GMCH_GM45, GMCH_UNKNOWN, GMCH_UNKNOWN, GMCH_GM49 },
{ GMCH_GE45, GMCH_GE45, GMCH_GE45, GMCH_GE45, GMCH_GE45 },
{ GMCH_UNKNOWN, GMCH_GL43, GMCH_GL40, GMCH_UNKNOWN, GMCH_UNKNOWN },
{ GMCH_UNKNOWN, GMCH_GS45, GMCH_GS40, GMCH_UNKNOWN, GMCH_UNKNOWN },
{ GMCH_UNKNOWN, GMCH_UNKNOWN, GMCH_UNKNOWN, GMCH_UNKNOWN, GMCH_UNKNOWN },
{ GMCH_UNKNOWN, GMCH_UNKNOWN, GMCH_UNKNOWN, GMCH_UNKNOWN, GMCH_UNKNOWN },
{ GMCH_PM45, GMCH_PM45, GMCH_PM45, GMCH_PM45, GMCH_PM45 },
};
void get_gmch_info(sysinfo_t *sysinfo)
{
sysinfo->stepping = pci_read_config8(PCI_DEV(0, 0, 0), PCI_CLASS_REVISION);
if ((sysinfo->stepping > STEPPING_B3) &&
(sysinfo->stepping != STEPPING_CONVERSION_A1))
die("Unknown stepping.\n");
if (sysinfo->stepping <= STEPPING_B3)
printk(BIOS_DEBUG, "Stepping %c%d\n", 'A' + sysinfo->stepping / 4, sysinfo->stepping % 4);
else
printk(BIOS_DEBUG, "Conversion stepping A1\n");
const u32 eax = cpuid_ext(0x04, 0).eax;
sysinfo->cores = ((eax >> 26) & 0x3f) + 1;
printk(BIOS_SPEW, "%d CPU cores\n", sysinfo->cores);
u32 capid = pci_read_config16(PCI_DEV(0, 0, 0), D0F0_CAPID0+8);
if (!(capid & (1<<(79-64)))) {
printk(BIOS_SPEW, "iTPM enabled\n");
}
capid = pci_read_config32(PCI_DEV(0, 0, 0), D0F0_CAPID0+4);
if (!(capid & (1<<(57-32)))) {
printk(BIOS_SPEW, "ME enabled\n");
}
if (!(capid & (1<<(56-32)))) {
printk(BIOS_SPEW, "AMT enabled\n");
}
sysinfo->max_ddr2_mhz = (capid & (1<<(53-32)))?667:800;
printk(BIOS_SPEW, "capable of DDR2 of %d MHz or lower\n", sysinfo->max_ddr2_mhz);
if (!(capid & (1<<(48-32)))) {
printk(BIOS_SPEW, "VT-d enabled\n");
}
const u32 gfx_variant = (capid>>(42-32)) & 0x7;
const u32 render_freq = ((capid>>(50-32) & 0x1) << 2) | ((capid>>(35-32)) & 0x3);
if (render_freq <= 4)
sysinfo->gfx_type = gmch_gfx_types[gfx_variant][render_freq];
else
sysinfo->gfx_type = GMCH_UNKNOWN;
sysinfo->gs45_low_power_mode = 0;
switch (sysinfo->gfx_type) {
case GMCH_GM45:
printk(BIOS_SPEW, "GMCH: GM45\n");
break;
case GMCH_GM47:
printk(BIOS_SPEW, "GMCH: GM47\n");
break;
case GMCH_GM49:
printk(BIOS_SPEW, "GMCH: GM49\n");
break;
case GMCH_GE45:
printk(BIOS_SPEW, "GMCH: GE45\n");
break;
case GMCH_GL40:
printk(BIOS_SPEW, "GMCH: GL40\n");
break;
case GMCH_GL43:
printk(BIOS_SPEW, "GMCH: GL43\n");
break;
case GMCH_GS40:
printk(BIOS_SPEW, "GMCH: GS40\n");
break;
case GMCH_GS45:
printk(BIOS_SPEW, "GMCH: GS45, using low power mode by default\n");
sysinfo->gs45_low_power_mode = 1;
break;
case GMCH_PM45:
printk(BIOS_SPEW, "GMCH: PM45\n");
break;
case GMCH_UNKNOWN:
printk(BIOS_SPEW, "unknown GMCH\n");
break;
}
sysinfo->txt_enabled = !(capid & (1 << (37-32)));
if (sysinfo->txt_enabled) {
printk(BIOS_SPEW, "TXT enabled\n");
}
switch (render_freq) {
case 4:
sysinfo->max_render_mhz = 800;
break;
case 0:
sysinfo->max_render_mhz = 667;
break;
case 1:
sysinfo->max_render_mhz = 533;
break;
case 2:
sysinfo->max_render_mhz = 400;
break;
case 3:
sysinfo->max_render_mhz = 333;
break;
default:
printk(BIOS_SPEW, "Unknown render frequency\n");
sysinfo->max_render_mhz = 0;
break;
}
if (sysinfo->max_render_mhz != 0) {
printk(BIOS_SPEW, "Render frequency: %d MHz\n", sysinfo->max_render_mhz);
}
if (!(capid & (1<<(33-32)))) {
printk(BIOS_SPEW, "IGD enabled\n");
}
if (!(capid & (1<<(32-32)))) {
printk(BIOS_SPEW, "PCIe-to-GMCH enabled\n");
}
capid = pci_read_config32(PCI_DEV(0, 0, 0), D0F0_CAPID0);
u32 ddr_cap = capid>>30 & 0x3;
switch (ddr_cap) {
case 0:
sysinfo->max_ddr3_mt = 1067;
break;
case 1:
sysinfo->max_ddr3_mt = 800;
break;
case 2:
case 3:
printk(BIOS_SPEW, "GMCH not DDR3 capable\n");
sysinfo->max_ddr3_mt = 0;
break;
}
if (sysinfo->max_ddr3_mt != 0) {
printk(BIOS_SPEW, "GMCH supports DDR3 with %d MT or less\n", sysinfo->max_ddr3_mt);
}
const unsigned max_fsb = (capid >> 28) & 0x3;
switch (max_fsb) {
case 1:
sysinfo->max_fsb_mhz = 1067;
break;
case 2:
sysinfo->max_fsb_mhz = 800;
break;
case 3:
sysinfo->max_fsb_mhz = 667;
break;
default:
die("unknown FSB capability\n");
break;
}
if (sysinfo->max_fsb_mhz != 0) {
printk(BIOS_SPEW, "GMCH supports FSB with up to %d MHz\n", sysinfo->max_fsb_mhz);
}
sysinfo->max_fsb = max_fsb - 1;
}
/*
* Detect if the system went through an interrupted RAM init or is incon-
* sistent. If so, initiate a cold reboot. Otherwise mark the system to be
* in RAM init, so this function would detect it on an erreneous reboot.
*/
void enter_raminit_or_reset(void)
{
/* Interrupted RAM init or inconsistent system? */
u8 reg8 = pci_read_config8(PCI_DEV(0, 0x1f, 0), 0xa2);
if (reg8 & (1 << 2)) { /* S4-assertion-width violation */
/* Ignore S4-assertion-width violation like original BIOS. */
printk(BIOS_WARNING,
"WARNING: Ignoring S4-assertion-width violation.\n");
/* Bit2 is R/WC, so it will clear itself below. */
}
if (reg8 & (1 << 7)) { /* interrupted RAM init */
/* Don't enable S4-assertion stretch. Makes trouble on roda/rk9.
reg8 = pci_read_config8(PCI_DEV(0, 0x1f, 0), 0xa4);
pci_write_config8(PCI_DEV(0, 0x1f, 0), 0xa4, reg8 | 0x08);
*/
/* Clear bit7. */
pci_write_config8(PCI_DEV(0, 0x1f, 0), 0xa2, reg8 & ~(1 << 7));
printk(BIOS_INFO, "Interrupted RAM init, reset required.\n");
gm45_early_reset();
}
/* Mark system to be in RAM init. */
pci_write_config8(PCI_DEV(0, 0x1f, 0), 0xa2, reg8 | (1 << 7));
}
/* For a detected DIMM, test the value of an SPD byte to
match the expected value after masking some bits. */
static int test_dimm(int dimm, int addr, int bitmask, int expected)
{
return (smbus_read_byte(DIMM0 + dimm, addr) & bitmask) == expected;
}
/* This function dies if dimm is unsuitable for the chipset. */
static void verify_ddr3_dimm(int dimm)
{
if (!test_dimm(dimm, 3, 15, 3))
die("Chipset only supports SO-DIMM\n");
if (!test_dimm(dimm, 8, 0x18, 0))
die("Chipset doesn't support ECC RAM\n");
if (!test_dimm(dimm, 7, 0x38, 0) &&
!test_dimm(dimm, 7, 0x38, 8))
die("Chipset wants single or double sided DIMMs\n");
if (!test_dimm(dimm, 7, 7, 1) &&
!test_dimm(dimm, 7, 7, 2))
die("Chipset requires x8 or x16 width\n");
if (!test_dimm(dimm, 4, 0x0f, 0) &&
!test_dimm(dimm, 4, 0x0f, 1) &&
!test_dimm(dimm, 4, 0x0f, 2) &&
!test_dimm(dimm, 4, 0x0f, 3))
die("Chipset requires 256Mb, 512Mb, 1Gb or 2Gb chips.");
if (!test_dimm(dimm, 4, 0x70, 0))
die("Chipset requires 8 banks on DDR3\n");
/* How to check if burst length is 8?
Other values are not supported, are they even possible? */
if (!test_dimm(dimm, 10, 0xff, 1))
die("Code assumes 1/8ns MTB\n");
if (!test_dimm(dimm, 11, 0xff, 8))
die("Code assumes 1/8ns MTB\n");
if (!test_dimm(dimm, 62, 0x9f, 0) &&
!test_dimm(dimm, 62, 0x9f, 1) &&
!test_dimm(dimm, 62, 0x9f, 2) &&
!test_dimm(dimm, 62, 0x9f, 3) &&
!test_dimm(dimm, 62, 0x9f, 5))
die("Only raw card types A, B, C, D and F are supported.\n");
}
/* For every detected DIMM, test if it's suitable for the chipset. */
static void verify_ddr3(int mask)
{
int cur = 0;
while (mask) {
if (mask & 1) {
verify_ddr3_dimm(cur);
}
mask >>= 1;
cur++;
}
}
typedef struct {
int dimm_mask;
struct {
unsigned int rows;
unsigned int cols;
unsigned int chip_capacity;
unsigned int banks;
unsigned int ranks;
unsigned int cas_latencies;
unsigned int tAAmin;
unsigned int tCKmin;
unsigned int width;
unsigned int tRAS;
unsigned int tRP;
unsigned int tRCD;
unsigned int tWR;
unsigned int page_size;
unsigned int raw_card;
} channel[2];
} spdinfo_t;
/*
* This function collects RAM characteristics from SPD, assuming that RAM
* is generally within chipset's requirements, since verify_ddr3() passed.
*/
static void collect_ddr3(spdinfo_t *const config)
{
int mask = config->dimm_mask;
int cur = 0;
while (mask != 0) {
if (mask & 1) {
int tmp;
const int smb_addr = DIMM0 + cur*2;
config->channel[cur].rows = ((smbus_read_byte(smb_addr, 5) >> 3) & 7) + 12;
config->channel[cur].cols = (smbus_read_byte(smb_addr, 5) & 7) + 9;
config->channel[cur].chip_capacity = smbus_read_byte(smb_addr, 4) & 0xf;
config->channel[cur].banks = 8; /* GM45 only accepts this for DDR3.
verify_ddr3() fails for other values. */
config->channel[cur].ranks = ((smbus_read_byte(smb_addr, 7) >> 3) & 7) + 1;
config->channel[cur].cas_latencies =
((smbus_read_byte(smb_addr, 15) << 8) | smbus_read_byte(smb_addr, 14))
<< 4; /* so bit x is CAS x */
config->channel[cur].tAAmin = smbus_read_byte(smb_addr, 16); /* in MTB */
config->channel[cur].tCKmin = smbus_read_byte(smb_addr, 12); /* in MTB */
config->channel[cur].width = smbus_read_byte(smb_addr, 7) & 7;
config->channel[cur].page_size = config->channel[cur].width *
(1 << config->channel[cur].cols); /* in Bytes */
tmp = smbus_read_byte(smb_addr, 21);
config->channel[cur].tRAS = smbus_read_byte(smb_addr, 22) | ((tmp & 0xf) << 8);
config->channel[cur].tRP = smbus_read_byte(smb_addr, 20);
config->channel[cur].tRCD = smbus_read_byte(smb_addr, 18);
config->channel[cur].tWR = smbus_read_byte(smb_addr, 17);
config->channel[cur].raw_card = smbus_read_byte(smb_addr, 62) & 0x1f;
}
cur++;
mask >>= 2; /* Only every other address is used. */
}
}
#define min(a, b) ((a) < (b))?(a):(b)
#define ROUNDUP_DIV(val, by) (((val) + (by) - 1) / (by))
#define ROUNDUP_DIV_THIS(val, by) val = ROUNDUP_DIV(val, by)
static fsb_clock_t read_fsb_clock(void)
{
switch (MCHBAR32(CLKCFG_MCHBAR) & CLKCFG_FSBCLK_MASK) {
case 6:
return FSB_CLOCK_1067MHz;
case 2:
return FSB_CLOCK_800MHz;
case 3:
return FSB_CLOCK_667MHz;
default:
die("Unsupported FSB clock.\n");
}
}
static mem_clock_t clock_index(const unsigned int clock)
{
switch (clock) {
case 533: return MEM_CLOCK_533MHz;
case 400: return MEM_CLOCK_400MHz;
case 333: return MEM_CLOCK_333MHz;
default: die("Unknown clock value.\n");
}
return -1; /* Won't be reached. */
}
static void normalize_clock(unsigned int *const clock)
{
if (*clock >= 533)
*clock = 533;
else if (*clock >= 400)
*clock = 400;
else if (*clock >= 333)
*clock = 333;
else
*clock = 0;
}
static void lower_clock(unsigned int *const clock)
{
--*clock;
normalize_clock(clock);
}
static unsigned int find_common_clock_cas(sysinfo_t *const sysinfo,
const spdinfo_t *const spdinfo)
{
/* various constraints must be fulfilled:
CAS * tCK < 20ns == 160MTB
tCK_max >= tCK >= tCK_min
CAS >= roundup(tAA_min/tCK)
CAS supported
Clock(MHz) = 1000 / tCK(ns)
Clock(MHz) = 8000 / tCK(MTB)
AND BTW: Clock(MT) = 2000 / tCK(ns) - intel uses MTs but calls them MHz
*/
int i;
/* Calculate common cas_latencies mask, tCKmin and tAAmin. */
unsigned int cas_latencies = (unsigned int)-1;
unsigned int tCKmin = 0, tAAmin = 0;
FOR_EACH_POPULATED_CHANNEL(sysinfo->dimms, i) {
cas_latencies &= spdinfo->channel[i].cas_latencies;
if (spdinfo->channel[i].tCKmin > tCKmin)
tCKmin = spdinfo->channel[i].tCKmin;
if (spdinfo->channel[i].tAAmin > tAAmin)
tAAmin = spdinfo->channel[i].tAAmin;
}
/* Get actual value of fsb clock. */
sysinfo->selected_timings.fsb_clock = read_fsb_clock();
unsigned int fsb_mhz = 0;
switch (sysinfo->selected_timings.fsb_clock) {
case FSB_CLOCK_1067MHz: fsb_mhz = 1067; break;
case FSB_CLOCK_800MHz: fsb_mhz = 800; break;
case FSB_CLOCK_667MHz: fsb_mhz = 667; break;
}
unsigned int clock = 8000 / tCKmin;
if ((clock > sysinfo->max_ddr3_mt / 2) || (clock > fsb_mhz / 2)) {
int new_clock = min(sysinfo->max_ddr3_mt / 2, fsb_mhz / 2);
printk(BIOS_SPEW, "DIMMs support %d MHz, but chipset only runs at up to %d. Limiting...\n",
clock, new_clock);
clock = new_clock;
}
normalize_clock(&clock);
/* Find compatible clock / CAS pair. */
unsigned int tCKproposed;
unsigned int CAS;
while (1) {
if (!clock)
die("Couldn't find compatible clock / CAS settings.\n");
tCKproposed = 8000 / clock;
CAS = ROUNDUP_DIV(tAAmin, tCKproposed);
printk(BIOS_SPEW, "Trying CAS %u, tCK %u.\n", CAS, tCKproposed);
for (; CAS <= DDR3_MAX_CAS; ++CAS)
if (cas_latencies & (1 << CAS))
break;
if ((CAS <= DDR3_MAX_CAS) && (CAS * tCKproposed < 160)) {
/* Found good CAS. */
printk(BIOS_SPEW, "Found compatible clock / CAS pair: %u / %u.\n", clock, CAS);
break;
}
lower_clock(&clock);
}
sysinfo->selected_timings.CAS = CAS;
sysinfo->selected_timings.mem_clock = clock_index(clock);
return tCKproposed;
}
static void calculate_derived_timings(sysinfo_t *const sysinfo,
const unsigned int tCLK,
const spdinfo_t *const spdinfo)
{
int i;
/* Calculate common tRASmin, tRPmin, tRCDmin and tWRmin. */
unsigned int tRASmin = 0, tRPmin = 0, tRCDmin = 0, tWRmin = 0;
FOR_EACH_POPULATED_CHANNEL(sysinfo->dimms, i) {
if (spdinfo->channel[i].tRAS > tRASmin)
tRASmin = spdinfo->channel[i].tRAS;
if (spdinfo->channel[i].tRP > tRPmin)
tRPmin = spdinfo->channel[i].tRP;
if (spdinfo->channel[i].tRCD > tRCDmin)
tRCDmin = spdinfo->channel[i].tRCD;
if (spdinfo->channel[i].tWR > tWRmin)
tWRmin = spdinfo->channel[i].tWR;
}
ROUNDUP_DIV_THIS(tRASmin, tCLK);
ROUNDUP_DIV_THIS(tRPmin, tCLK);
ROUNDUP_DIV_THIS(tRCDmin, tCLK);
ROUNDUP_DIV_THIS(tWRmin, tCLK);
/* Lookup tRFC and calculate common tRFCmin. */
const unsigned int tRFC_from_clock_and_cap[][4] = {
/* CAP_256M CAP_512M CAP_1G CAP_2G */
/* 533MHz */ { 40, 56, 68, 104 },
/* 400MHz */ { 30, 42, 51, 78 },
/* 333MHz */ { 25, 35, 43, 65 },
};
unsigned int tRFCmin = 0;
FOR_EACH_POPULATED_CHANNEL(sysinfo->dimms, i) {
const unsigned int tRFC = tRFC_from_clock_and_cap
[sysinfo->selected_timings.mem_clock][spdinfo->channel[i].chip_capacity];
if (tRFC > tRFCmin)
tRFCmin = tRFC;
}
/* Calculate common tRD from CAS and FSB and DRAM clocks. */
unsigned int tRDmin = sysinfo->selected_timings.CAS;
switch (sysinfo->selected_timings.fsb_clock) {
case FSB_CLOCK_667MHz:
tRDmin += 1;
break;
case FSB_CLOCK_800MHz:
tRDmin += 2;
break;
case FSB_CLOCK_1067MHz:
tRDmin += 3;
if (sysinfo->selected_timings.mem_clock == MEM_CLOCK_1067MT)
tRDmin += 1;
break;
}
/* Calculate common tRRDmin. */
unsigned int tRRDmin = 0;
FOR_EACH_POPULATED_CHANNEL(sysinfo->dimms, i) {
unsigned int tRRD = 2 + (spdinfo->channel[i].page_size / 1024);
if (sysinfo->selected_timings.mem_clock == MEM_CLOCK_1067MT)
tRRD += (spdinfo->channel[i].page_size / 1024);
if (tRRD > tRRDmin)
tRRDmin = tRRD;
}
/* Lookup and calculate common tFAWmin. */
unsigned int tFAW_from_pagesize_and_clock[][3] = {
/* 533MHz 400MHz 333MHz */
/* 1K */ { 20, 15, 13 },
/* 2K */ { 27, 20, 17 },
};
unsigned int tFAWmin = 0;
FOR_EACH_POPULATED_CHANNEL(sysinfo->dimms, i) {
const unsigned int tFAW = tFAW_from_pagesize_and_clock
[spdinfo->channel[i].page_size / 1024 - 1]
[sysinfo->selected_timings.mem_clock];
if (tFAW > tFAWmin)
tFAWmin = tFAW;
}
/* Refresh rate is fixed. */
unsigned int tWL;
if (sysinfo->selected_timings.mem_clock == MEM_CLOCK_1067MT) {
tWL = 6;
} else {
tWL = 5;
}
printk(BIOS_SPEW, "Timing values:\n"
" tCLK: %3u\n"
" tRAS: %3u\n"
" tRP: %3u\n"
" tRCD: %3u\n"
" tRFC: %3u\n"
" tWR: %3u\n"
" tRD: %3u\n"
" tRRD: %3u\n"
" tFAW: %3u\n"
" tWL: %3u\n",
tCLK, tRASmin, tRPmin, tRCDmin, tRFCmin, tWRmin, tRDmin, tRRDmin, tFAWmin, tWL);
sysinfo->selected_timings.tRAS = tRASmin;
sysinfo->selected_timings.tRP = tRPmin;
sysinfo->selected_timings.tRCD = tRCDmin;
sysinfo->selected_timings.tRFC = tRFCmin;
sysinfo->selected_timings.tWR = tWRmin;
sysinfo->selected_timings.tRD = tRDmin;
sysinfo->selected_timings.tRRD = tRRDmin;
sysinfo->selected_timings.tFAW = tFAWmin;
sysinfo->selected_timings.tWL = tWL;
}
static void collect_dimm_config(sysinfo_t *const sysinfo)
{
int i;
spdinfo_t spdinfo;
spdinfo.dimm_mask = 0;
sysinfo->spd_type = 0;
/* at most 2 dimms, on even slots */
for (i = 0; i < 4; i += 2) {
const u8 spd = smbus_read_byte(DIMM0 + i, 2);
if ((spd == 7) || (spd == 8) || (spd == 0xb)) {
spdinfo.dimm_mask |= 1 << i;
if (sysinfo->spd_type && sysinfo->spd_type != spd) {
die("Multiple types of DIMM installed in the system, don't do that!\n");
}
sysinfo->spd_type = spd;
}
}
if (spdinfo.dimm_mask == 0) {
die("Could not find any DIMM.\n");
}
/* Normalize spd_type to 1, 2, 3. */
sysinfo->spd_type = (sysinfo->spd_type & 1) | ((sysinfo->spd_type & 8) >> 2);
printk(BIOS_SPEW, "DDR mask %x, DDR %d\n", spdinfo.dimm_mask, sysinfo->spd_type);
if (sysinfo->spd_type == DDR2) {
die("DDR2 not supported at this time.\n");
} else if (sysinfo->spd_type == DDR3) {
verify_ddr3(spdinfo.dimm_mask);
collect_ddr3(&spdinfo);
} else {
die("Will never support DDR1.\n");
}
for (i = 0; i < 2; i++) {
if ((spdinfo.dimm_mask >> (i*2)) & 1) {
printk(BIOS_SPEW, "Bank %d populated:\n"
" Raw card type: %4c\n"
" Row addr bits: %4u\n"
" Col addr bits: %4u\n"
" byte width: %4u\n"
" page size: %4u\n"
" banks: %4u\n"
" ranks: %4u\n"
" tAAmin: %3u\n"
" tCKmin: %3u\n"
" Max clock: %3u MHz\n"
" CAS: 0x%04x\n",
i, spdinfo.channel[i].raw_card + 'A',
spdinfo.channel[i].rows, spdinfo.channel[i].cols,
spdinfo.channel[i].width, spdinfo.channel[i].page_size,
spdinfo.channel[i].banks, spdinfo.channel[i].ranks,
spdinfo.channel[i].tAAmin, spdinfo.channel[i].tCKmin,
8000 / spdinfo.channel[i].tCKmin, spdinfo.channel[i].cas_latencies);
}
}
FOR_EACH_CHANNEL(i) {
sysinfo->dimms[i].card_type =
(spdinfo.dimm_mask & (1 << (i * 2))) ? spdinfo.channel[i].raw_card + 0xa : 0;
}
/* Find common memory clock and CAS. */
const unsigned int tCLK = find_common_clock_cas(sysinfo, &spdinfo);
/* Calculate other timings from clock and CAS. */
calculate_derived_timings(sysinfo, tCLK, &spdinfo);
/* Initialize DIMM infos. */
/* Always prefer interleaved over async channel mode. */
FOR_EACH_CHANNEL(i) {
IF_CHANNEL_POPULATED(sysinfo->dimms, i) {
sysinfo->dimms[i].banks = spdinfo.channel[i].banks;
sysinfo->dimms[i].ranks = spdinfo.channel[i].ranks;
/* .width is 1 for x8 or 2 for x16, bus width is 8 bytes. */
const unsigned int chips_per_rank = 8 / spdinfo.channel[i].width;
sysinfo->dimms[i].chip_width = spdinfo.channel[i].width;
sysinfo->dimms[i].chip_capacity = spdinfo.channel[i].chip_capacity;
sysinfo->dimms[i].page_size = spdinfo.channel[i].page_size * chips_per_rank;
sysinfo->dimms[i].rank_capacity_mb =
/* offset of chip_capacity is 8 (256M), therefore, add 8
chip_capacity is in Mbit, we want MByte, therefore, subtract 3 */
(1 << (spdinfo.channel[i].chip_capacity + 8 - 3)) * chips_per_rank;
}
}
if (CHANNEL_IS_POPULATED(sysinfo->dimms, 0) &&
CHANNEL_IS_POPULATED(sysinfo->dimms, 1))
sysinfo->selected_timings.channel_mode = CHANNEL_MODE_DUAL_INTERLEAVED;
else
sysinfo->selected_timings.channel_mode = CHANNEL_MODE_SINGLE;
}
static void reset_on_bad_warmboot(void)
{
/* Check self refresh channel status. */
const u32 reg = MCHBAR32(PMSTS_MCHBAR);
/* Clear status bits. R/WC */
MCHBAR32(PMSTS_MCHBAR) = reg;
if ((reg & PMSTS_WARM_RESET) && !(reg & PMSTS_BOTH_SELFREFRESH)) {
printk(BIOS_INFO, "DRAM was not in self refresh "
"during warm boot, reset required.\n");
gm45_early_reset();
}
}
static void set_system_memory_frequency(const timings_t *const timings)
{
MCHBAR16(CLKCFG_MCHBAR + 0x60) &= ~(1 << 15);
MCHBAR16(CLKCFG_MCHBAR + 0x48) &= ~(1 << 15);
/* Calculate wanted frequency setting. */
const int want_freq = 6 - timings->mem_clock;
/* Read current memory frequency. */
const u32 clkcfg = MCHBAR32(CLKCFG_MCHBAR);
int cur_freq = (clkcfg & CLKCFG_MEMCLK_MASK) >> CLKCFG_MEMCLK_SHIFT;
if (0 == cur_freq) {
/* Try memory frequency from scratchpad. */
printk(BIOS_DEBUG, "Reading current memory frequency from scratchpad.\n");
cur_freq = (MCHBAR16(SSKPD_MCHBAR) & SSKPD_CLK_MASK) >> SSKPD_CLK_SHIFT;
}
if (cur_freq != want_freq) {
printk(BIOS_DEBUG, "Changing memory frequency: old %x, new %x.\n", cur_freq, want_freq);
/* When writing new frequency setting, reset, then set update bit. */
MCHBAR32(CLKCFG_MCHBAR) = (MCHBAR32(CLKCFG_MCHBAR) & ~(CLKCFG_UPDATE | CLKCFG_MEMCLK_MASK)) |
(want_freq << CLKCFG_MEMCLK_SHIFT);
MCHBAR32(CLKCFG_MCHBAR) = (MCHBAR32(CLKCFG_MCHBAR) & ~CLKCFG_MEMCLK_MASK) |
(want_freq << CLKCFG_MEMCLK_SHIFT) | CLKCFG_UPDATE;
/* Reset update bit. */
MCHBAR32(CLKCFG_MCHBAR) &= ~CLKCFG_UPDATE;
}
if ((timings->fsb_clock == FSB_CLOCK_1067MHz) && (timings->mem_clock == MEM_CLOCK_667MT)) {
MCHBAR32(CLKCFG_MCHBAR + 0x16) = 0x000030f0;
MCHBAR32(CLKCFG_MCHBAR + 0x64) = 0x000050c1;
MCHBAR32(CLKCFG_MCHBAR) = (MCHBAR32(CLKCFG_MCHBAR) & ~(1 << 12)) | (1 << 17);
MCHBAR32(CLKCFG_MCHBAR) |= (1 << 17) | (1 << 12);
MCHBAR32(CLKCFG_MCHBAR) &= ~(1 << 12);
MCHBAR32(CLKCFG_MCHBAR + 0x04) = 0x9bad1f1f;
MCHBAR8(CLKCFG_MCHBAR + 0x08) = 0xf4;
MCHBAR8(CLKCFG_MCHBAR + 0x0a) = 0x43;
MCHBAR8(CLKCFG_MCHBAR + 0x0c) = 0x10;
MCHBAR8(CLKCFG_MCHBAR + 0x0d) = 0x80;
MCHBAR32(CLKCFG_MCHBAR + 0x50) = 0x0b0e151b;
MCHBAR8(CLKCFG_MCHBAR + 0x54) = 0xb4;
MCHBAR8(CLKCFG_MCHBAR + 0x55) = 0x10;
MCHBAR8(CLKCFG_MCHBAR + 0x56) = 0x08;
MCHBAR32(CLKCFG_MCHBAR) |= (1 << 10);
MCHBAR32(CLKCFG_MCHBAR) |= (1 << 11);
MCHBAR32(CLKCFG_MCHBAR) &= ~(1 << 10);
MCHBAR32(CLKCFG_MCHBAR) &= ~(1 << 11);
}
MCHBAR32(CLKCFG_MCHBAR + 0x48) |= 0x3f << 24;
}
int raminit_read_vco_index(void)
{
switch (MCHBAR8(0x0c0f) & 0x7) {
case VCO_2666:
return 0;
case VCO_3200:
return 1;
case VCO_4000:
return 2;
case VCO_5333:
return 3;
default:
die("Unknown VCO frequency.\n");
return 0;
}
}
static void set_igd_memory_frequencies(const sysinfo_t *const sysinfo)
{
const int gfx_idx = ((sysinfo->gfx_type == GMCH_GS45) &&
!sysinfo->gs45_low_power_mode)
? (GMCH_GS45 + 1) : sysinfo->gfx_type;
/* Render and sampler frequency values seem to be some kind of factor. */
const u16 render_freq_from_vco_and_gfxtype[][10] = {
/* GM45 GM47 GM49 GE45 GL40 GL43 GS40 GS45 (perf) */
/* VCO 2666 */ { 0xd, 0xd, 0xe, 0xd, 0xb, 0xd, 0xb, 0xa, 0xd },
/* VCO 3200 */ { 0xd, 0xe, 0xf, 0xd, 0xb, 0xd, 0xb, 0x9, 0xd },
/* VCO 4000 */ { 0xc, 0xd, 0xf, 0xc, 0xa, 0xc, 0xa, 0x9, 0xc },
/* VCO 5333 */ { 0xb, 0xc, 0xe, 0xb, 0x9, 0xb, 0x9, 0x8, 0xb },
};
const u16 sampler_freq_from_vco_and_gfxtype[][10] = {
/* GM45 GM47 GM49 GE45 GL40 GL43 GS40 GS45 (perf) */
/* VCO 2666 */ { 0xc, 0xc, 0xd, 0xc, 0x9, 0xc, 0x9, 0x8, 0xc },
/* VCO 3200 */ { 0xc, 0xd, 0xe, 0xc, 0x9, 0xc, 0x9, 0x8, 0xc },
/* VCO 4000 */ { 0xa, 0xc, 0xd, 0xa, 0x8, 0xa, 0x8, 0x8, 0xa },
/* VCO 5333 */ { 0xa, 0xa, 0xc, 0xa, 0x7, 0xa, 0x7, 0x6, 0xa },
};
const u16 display_clock_select_from_gfxtype[] = {
/* GM45 GM47 GM49 GE45 GL40 GL43 GS40 GS45 (perf) */
1, 1, 1, 1, 1, 1, 1, 0, 1
};
if (pci_read_config16(GCFGC_PCIDEV, 0) != 0x8086) {
printk(BIOS_DEBUG, "Skipping IGD memory frequency setting.\n");
return;
}
MCHBAR16(0x119e) = 0xa800;
MCHBAR16(0x11c0) = (MCHBAR16(0x11c0) & ~0xff00) | (0x01 << 8);
MCHBAR16(0x119e) = 0xb800;
MCHBAR8(0x0f10) |= 1 << 7;
/* Read VCO. */
const int vco_idx = raminit_read_vco_index();
printk(BIOS_DEBUG, "Setting IGD memory frequencies for VCO #%d.\n", vco_idx);
const u32 freqcfg =
((render_freq_from_vco_and_gfxtype[vco_idx][gfx_idx]
<< GCFGC_CR_SHIFT) & GCFGC_CR_MASK) |
((sampler_freq_from_vco_and_gfxtype[vco_idx][gfx_idx]
<< GCFGC_CS_SHIFT) & GCFGC_CS_MASK);
/* Set frequencies, clear update bit. */
u32 gcfgc = pci_read_config16(GCFGC_PCIDEV, GCFGC_OFFSET);
gcfgc &= ~(GCFGC_CS_MASK | GCFGC_UPDATE | GCFGC_CR_MASK);
gcfgc |= freqcfg;
pci_write_config16(GCFGC_PCIDEV, GCFGC_OFFSET, gcfgc);
/* Set frequencies, set update bit. */
gcfgc = pci_read_config16(GCFGC_PCIDEV, GCFGC_OFFSET);
gcfgc &= ~(GCFGC_CS_MASK | GCFGC_CR_MASK);
gcfgc |= freqcfg | GCFGC_UPDATE;
pci_write_config16(GCFGC_PCIDEV, GCFGC_OFFSET, gcfgc);
/* Clear update bit. */
pci_write_config16(GCFGC_PCIDEV, GCFGC_OFFSET,
pci_read_config16(GCFGC_PCIDEV, GCFGC_OFFSET) & ~GCFGC_UPDATE);
/* Set display clock select bit. */
pci_write_config16(GCFGC_PCIDEV, GCFGC_OFFSET,
(pci_read_config16(GCFGC_PCIDEV, GCFGC_OFFSET) & ~GCFGC_CD_MASK) |
(display_clock_select_from_gfxtype[gfx_idx] << GCFGC_CD_SHIFT));
}
static void configure_dram_control_mode(const timings_t *const timings, const dimminfo_t *const dimms)
{
int ch, r;
FOR_EACH_CHANNEL(ch) {
unsigned int mchbar = CxDRC0_MCHBAR(ch);
u32 cxdrc = MCHBAR32(mchbar);
cxdrc &= ~CxDRC0_RANKEN_MASK;
FOR_EACH_POPULATED_RANK_IN_CHANNEL(dimms, ch, r)
cxdrc |= CxDRC0_RANKEN(r);
cxdrc = (cxdrc & ~CxDRC0_RMS_MASK) |
/* Always 7.8us for DDR3: */
CxDRC0_RMS_78US;
MCHBAR32(mchbar) = cxdrc;
mchbar = CxDRC1_MCHBAR(ch);
cxdrc = MCHBAR32(mchbar);
cxdrc |= CxDRC1_NOTPOP_MASK;
FOR_EACH_POPULATED_RANK_IN_CHANNEL(dimms, ch, r)
cxdrc &= ~CxDRC1_NOTPOP(r);
cxdrc |= CxDRC1_MUSTWR;
MCHBAR32(mchbar) = cxdrc;
mchbar = CxDRC2_MCHBAR(ch);
cxdrc = MCHBAR32(mchbar);
cxdrc |= CxDRC2_NOTPOP_MASK;
FOR_EACH_POPULATED_RANK_IN_CHANNEL(dimms, ch, r)
cxdrc &= ~CxDRC2_NOTPOP(r);
cxdrc |= CxDRC2_MUSTWR;
if (timings->mem_clock == MEM_CLOCK_1067MT)
cxdrc |= CxDRC2_CLK1067MT;
MCHBAR32(mchbar) = cxdrc;
}
}
static void rcomp_initialization(const stepping_t stepping, const int sff)
{
/* Programm RCOMP codes. */
if (sff)
die("SFF platform unsupported in RCOMP initialization.\n");
/* Values are for DDR3. */
MCHBAR8(0x6ac) &= ~0x0f;
MCHBAR8(0x6b0) = 0x55;
MCHBAR8(0x6ec) &= ~0x0f;
MCHBAR8(0x6f0) = 0x66;
MCHBAR8(0x72c) &= ~0x0f;
MCHBAR8(0x730) = 0x66;
MCHBAR8(0x76c) &= ~0x0f;
MCHBAR8(0x770) = 0x66;
MCHBAR8(0x7ac) &= ~0x0f;
MCHBAR8(0x7b0) = 0x66;
MCHBAR8(0x7ec) &= ~0x0f;
MCHBAR8(0x7f0) = 0x66;
MCHBAR8(0x86c) &= ~0x0f;
MCHBAR8(0x870) = 0x55;
MCHBAR8(0x8ac) &= ~0x0f;
MCHBAR8(0x8b0) = 0x66;
/* ODT multiplier bits. */
MCHBAR32(0x04d0) = (MCHBAR32(0x04d0) & ~((7 << 3) | (7 << 0))) | (2 << 3) | (2 << 0);
/* Perform RCOMP calibration for DDR3. */
raminit_rcomp_calibration(stepping);
/* Run initial RCOMP. */
MCHBAR32(0x418) |= 1 << 17;
MCHBAR32(0x40c) &= ~(1 << 23);
MCHBAR32(0x41c) &= ~((1 << 7) | (1 << 3));
MCHBAR32(0x400) |= 1;
while (MCHBAR32(0x400) & 1) {}
/* Run second RCOMP. */
MCHBAR32(0x40c) |= 1 << 19;
MCHBAR32(0x400) |= 1;
while (MCHBAR32(0x400) & 1) {}
/* Cleanup and start periodic RCOMP. */
MCHBAR32(0x40c) &= ~(1 << 19);
MCHBAR32(0x40c) |= 1 << 23;
MCHBAR32(0x418) &= ~(1 << 17);
MCHBAR32(0x41c) |= (1 << 7) | (1 << 3);
MCHBAR32(0x400) |= (1 << 1);
}
static void dram_powerup(const int resume)
{
udelay_from_reset(200);
MCHBAR32(CLKCFG_MCHBAR) = (MCHBAR32(CLKCFG_MCHBAR) & ~(1 << 3)) | (3 << 21);
if (!resume) {
MCHBAR32(0x1434) |= (1 << 10);
ns100delay(2);
}
MCHBAR32(0x1434) |= (1 << 6);
if (!resume) {
ns100delay(1);
MCHBAR32(0x1434) |= (1 << 9);
MCHBAR32(0x1434) &= ~(1 << 10);
udelay(500);
}
}
static void dram_program_timings(const timings_t *const timings)
{
/* Values are for DDR3. */
const int burst_length = 8;
const int tWTR = 4, tRTP = 1;
int i;
FOR_EACH_CHANNEL(i) {
u32 reg = MCHBAR32(CxDRT0_MCHBAR(i));
const int btb_wtp = timings->tWL + burst_length/2 + timings->tWR;
const int btb_wtr = timings->tWL + burst_length/2 + tWTR;
reg = (reg & ~(CxDRT0_BtB_WtP_MASK | CxDRT0_BtB_WtR_MASK)) |
((btb_wtp << CxDRT0_BtB_WtP_SHIFT) & CxDRT0_BtB_WtP_MASK) |
((btb_wtr << CxDRT0_BtB_WtR_SHIFT) & CxDRT0_BtB_WtR_MASK);
if (timings->mem_clock != MEM_CLOCK_1067MT) {
reg = (reg & ~(0x7 << 15)) | ((9 - timings->CAS) << 15);
reg = (reg & ~(0xf << 10)) | ((timings->CAS - 3) << 10);
} else {
reg = (reg & ~(0x7 << 15)) | ((10 - timings->CAS) << 15);
reg = (reg & ~(0xf << 10)) | ((timings->CAS - 4) << 10);
}
reg = (reg & ~(0x7 << 5)) | (3 << 5);
reg = (reg & ~(0x7 << 0)) | (1 << 0);
MCHBAR32(CxDRT0_MCHBAR(i)) = reg;
reg = MCHBAR32(CxDRT1_MCHBAR(i));
reg = (reg & ~(0x03 << 28)) | ((tRTP & 0x03) << 28);
reg = (reg & ~(0x1f << 21)) | ((timings->tRAS & 0x1f) << 21);
reg = (reg & ~(0x07 << 10)) | (((timings->tRRD - 2) & 0x07) << 10);
reg = (reg & ~(0x07 << 5)) | (((timings->tRCD - 2) & 0x07) << 5);
reg = (reg & ~(0x07 << 0)) | (((timings->tRP - 2) & 0x07) << 0);
MCHBAR32(CxDRT1_MCHBAR(i)) = reg;
reg = MCHBAR32(CxDRT2_MCHBAR(i));
reg = (reg & ~(0x1f << 17)) | ((timings->tFAW & 0x1f) << 17);
if (timings->mem_clock != MEM_CLOCK_1067MT) {
reg = (reg & ~(0x7 << 12)) | (0x2 << 12);
reg = (reg & ~(0xf << 6)) | (0x9 << 6);
} else {
reg = (reg & ~(0x7 << 12)) | (0x3 << 12);
reg = (reg & ~(0xf << 6)) | (0xc << 6);
}
reg = (reg & ~(0x1f << 0)) | (0x13 << 0);
MCHBAR32(CxDRT2_MCHBAR(i)) = reg;
reg = MCHBAR32(CxDRT3_MCHBAR(i));
reg |= 0x3 << 28;
reg = (reg & ~(0x03 << 26));
reg = (reg & ~(0x07 << 23)) | (((timings->CAS - 3) & 0x07) << 23);
reg = (reg & ~(0xff << 13)) | ((timings->tRFC & 0xff) << 13);
reg = (reg & ~(0x07 << 0)) | (((timings->tWL - 2) & 0x07) << 0);
MCHBAR32(CxDRT3_MCHBAR(i)) = reg;
reg = MCHBAR32(CxDRT4_MCHBAR(i));
static const u8 timings_by_clock[4][3] = {
/* 333MHz 400MHz 533MHz
667MT 800MT 1067MT */
{ 0x07, 0x0a, 0x0d },
{ 0x3a, 0x46, 0x5d },
{ 0x0c, 0x0e, 0x18 },
{ 0x21, 0x28, 0x35 },
};
const int clk_idx = 2 - timings->mem_clock;
reg = (reg & ~(0x01f << 27)) | (timings_by_clock[0][clk_idx] << 27);
reg = (reg & ~(0x3ff << 17)) | (timings_by_clock[1][clk_idx] << 17);
reg = (reg & ~(0x03f << 10)) | (timings_by_clock[2][clk_idx] << 10);
reg = (reg & ~(0x1ff << 0)) | (timings_by_clock[3][clk_idx] << 0);
MCHBAR32(CxDRT4_MCHBAR(i)) = reg;
reg = MCHBAR32(CxDRT5_MCHBAR(i));
if (timings->mem_clock == MEM_CLOCK_1067MT)
reg = (reg & ~(0xf << 28)) | (0x8 << 28);
reg = (reg & ~(0x00f << 22)) | ((burst_length/2 + timings->CAS + 2) << 22);
reg = (reg & ~(0x3ff << 12)) | (0x190 << 12);
reg = (reg & ~(0x00f << 4)) | ((timings->CAS - 2) << 4);
reg = (reg & ~(0x003 << 2)) | (0x001 << 2);
reg = (reg & ~(0x003 << 0));
MCHBAR32(CxDRT5_MCHBAR(i)) = reg;
reg = MCHBAR32(CxDRT6_MCHBAR(i));
reg = (reg & ~(0xffff << 16)) | (0x066a << 16); /* always 7.8us refresh rate for DDR3 */
reg |= (1 << 2);
MCHBAR32(CxDRT6_MCHBAR(i)) = reg;
}
}
static void dram_program_banks(const dimminfo_t *const dimms)
{
int ch, r;
FOR_EACH_CHANNEL(ch) {
const int tRPALL = dimms[ch].banks == 8;
u32 reg = MCHBAR32(CxDRT1_MCHBAR(ch)) & ~(0x01 << 15);
IF_CHANNEL_POPULATED(dimms, ch)
reg |= tRPALL << 15;
MCHBAR32(CxDRT1_MCHBAR(ch)) = reg;
reg = MCHBAR32(CxDRA_MCHBAR(ch)) & ~CxDRA_BANKS_MASK;
FOR_EACH_POPULATED_RANK_IN_CHANNEL(dimms, ch, r) {
reg |= CxDRA_BANKS(r, dimms[ch].banks);
}
MCHBAR32(CxDRA_MCHBAR(ch)) = reg;
}
}
static void odt_setup(const timings_t *const timings, const int sff)
{
/* Values are for DDR3. */
int ch;
FOR_EACH_CHANNEL(ch) {
u32 reg = MCHBAR32(CxODT_HIGH(ch));
if (sff && (timings->mem_clock != MEM_CLOCK_1067MT))
reg &= ~(0x3 << (61 - 32));
else
reg |= 0x3 << (61 - 32);
reg = (reg & ~(0x3 << (52 - 32))) | (0x2 << (52 - 32));
reg = (reg & ~(0x7 << (48 - 32))) | ((timings->CAS - 3) << (48 - 32));
reg = (reg & ~(0xf << (44 - 32))) | (0x7 << (44 - 32));
if (timings->mem_clock != MEM_CLOCK_1067MT) {
reg = (reg & ~(0xf << (40 - 32))) | ((12 - timings->CAS) << (40 - 32));
reg = (reg & ~(0xf << (36 - 32))) | (( 2 + timings->CAS) << (36 - 32));
} else {
reg = (reg & ~(0xf << (40 - 32))) | ((13 - timings->CAS) << (40 - 32));
reg = (reg & ~(0xf << (36 - 32))) | (( 1 + timings->CAS) << (36 - 32));
}
reg = (reg & ~(0xf << (32 - 32))) | (0x7 << (32 - 32));
MCHBAR32(CxODT_HIGH(ch)) = reg;
reg = MCHBAR32(CxODT_LOW(ch));
reg = (reg & ~(0x7 << 28)) | (0x2 << 28);
reg = (reg & ~(0x3 << 22)) | (0x2 << 22);
reg = (reg & ~(0x7 << 12)) | (0x2 << 12);
reg = (reg & ~(0x7 << 4)) | (0x2 << 4);
switch (timings->mem_clock) {
case MEM_CLOCK_667MT:
reg = (reg & ~0x7);
break;
case MEM_CLOCK_800MT:
reg = (reg & ~0x7) | 0x2;
break;
case MEM_CLOCK_1067MT:
reg = (reg & ~0x7) | 0x5;
break;
}
MCHBAR32(CxODT_LOW(ch)) = reg;
}
}
static void misc_settings(const timings_t *const timings,
const stepping_t stepping)
{
MCHBAR32(0x1260) = (MCHBAR32(0x1260) & ~((1 << 24) | 0x1f)) | timings->tRD;
MCHBAR32(0x1360) = (MCHBAR32(0x1360) & ~((1 << 24) | 0x1f)) | timings->tRD;
MCHBAR8(0x1268) = (MCHBAR8(0x1268) & ~(0xf)) | timings->tWL;
MCHBAR8(0x1368) = (MCHBAR8(0x1368) & ~(0xf)) | timings->tWL;
MCHBAR8(0x12a0) = (MCHBAR8(0x12a0) & ~(0xf)) | 0xa;
MCHBAR8(0x13a0) = (MCHBAR8(0x13a0) & ~(0xf)) | 0xa;
MCHBAR32(0x218) = (MCHBAR32(0x218) & ~((7 << 29) | (7 << 25) | (3 << 22) | (3 << 10))) |
(4 << 29) | (3 << 25) | (0 << 22) | (1 << 10);
MCHBAR32(0x220) = (MCHBAR32(0x220) & ~(7 << 16)) | (1 << 21) | (1 << 16);
MCHBAR32(0x224) = (MCHBAR32(0x224) & ~(7 << 8)) | (3 << 8);
if (stepping >= STEPPING_B1)
MCHBAR8(0x234) |= (1 << 3);
}
static void clock_crossing_setup(const fsb_clock_t fsb,
const mem_clock_t ddr3clock,
const dimminfo_t *const dimms)
{
int ch;
static const u32 values_from_fsb_and_mem[][3][4] = {
/* FSB 1067MHz */{
/* DDR3-1067 */ { 0x00000000, 0x00000000, 0x00180006, 0x00810060 },
/* DDR3-800 */ { 0x00000000, 0x00000000, 0x0000001c, 0x000300e0 },
/* DDR3-667 */ { 0x00000000, 0x00001c00, 0x03c00038, 0x0007e000 },
},
/* FSB 800MHz */{
/* DDR3-1067 */ { 0, 0, 0, 0 },
/* DDR3-800 */ { 0x00000000, 0x00000000, 0x0030000c, 0x000300c0 },
/* DDR3-667 */ { 0x00000000, 0x00000380, 0x0060001c, 0x00030c00 },
},
/* FSB 667MHz */{
/* DDR3-1067 */ { 0, 0, 0, 0 },
/* DDR3-800 */ { 0, 0, 0, 0 },
/* DDR3-667 */ { 0x00000000, 0x00000000, 0x0030000c, 0x000300c0 },
},
};
const u32 *data = values_from_fsb_and_mem[fsb][ddr3clock];
MCHBAR32(0x0208) = data[3];
MCHBAR32(0x020c) = data[2];
if (((fsb == FSB_CLOCK_1067MHz) || (fsb == FSB_CLOCK_800MHz)) && (ddr3clock == MEM_CLOCK_667MT))
MCHBAR32(0x0210) = data[1];
static const u32 from_fsb_and_mem[][3] = {
/* DDR3-1067 DDR3-800 DDR3-667 */
/* FSB 1067MHz */{ 0x40100401, 0x10040220, 0x08040110, },
/* FSB 800MHz */{ 0x00000000, 0x40100401, 0x00080201, },
/* FSB 667MHz */{ 0x00000000, 0x00000000, 0x40100401, },
};
FOR_EACH_CHANNEL(ch) {
const unsigned int mchbar = 0x1258 + (ch * 0x0100);
if ((fsb == FSB_CLOCK_1067MHz) && (ddr3clock == MEM_CLOCK_800MT) && CHANNEL_IS_CARDF(dimms, ch))
MCHBAR32(mchbar) = 0x08040120;
else
MCHBAR32(mchbar) = from_fsb_and_mem[fsb][ddr3clock];
MCHBAR32(mchbar + 4) = 0x00000000;
}
}
/* Program egress VC1 timings. */
static void vc1_program_timings(const fsb_clock_t fsb)
{
const u32 timings_by_fsb[][2] = {
/* FSB 1067MHz */ { 0x1a, 0x01380138 },
/* FSB 800MHz */ { 0x14, 0x00f000f0 },
/* FSB 667MHz */ { 0x10, 0x00c000c0 },
};
EPBAR8(0x2c) = timings_by_fsb[fsb][0];
EPBAR32(0x38) = timings_by_fsb[fsb][1];
EPBAR32(0x3c) = timings_by_fsb[fsb][1];
}
/* @prejedec if not zero, set rank size to 128MB and page size to 4KB. */
static void program_memory_map(const dimminfo_t *const dimms, const channel_mode_t mode, const int prejedec)
{
int ch, r;
/* Program rank boundaries (CxDRBy). */
unsigned int base = 0; /* start of next rank in MB */
unsigned int total_mb[2] = { 0, 0 }; /* total memory per channel in MB */
FOR_EACH_CHANNEL(ch) {
if (mode == CHANNEL_MODE_DUAL_INTERLEAVED)
/* In interleaved mode, start every channel from 0. */
base = 0;
for (r = 0; r < RANKS_PER_CHANNEL; r += 2) {
/* Fixed capacity for pre-jedec config. */
const unsigned int rank_capacity_mb =
prejedec ? 128 : dimms[ch].rank_capacity_mb;
u32 reg = 0;
/* Program bounds in CxDRBy. */
IF_RANK_POPULATED(dimms, ch, r) {
base += rank_capacity_mb;
total_mb[ch] += rank_capacity_mb;
}
reg |= CxDRBy_BOUND_MB(r, base);
IF_RANK_POPULATED(dimms, ch, r+1) {
base += rank_capacity_mb;
total_mb[ch] += rank_capacity_mb;
}
reg |= CxDRBy_BOUND_MB(r+1, base);
MCHBAR32(CxDRBy_MCHBAR(ch, r)) = reg;
}
}
/* Program page size (CxDRA). */
FOR_EACH_CHANNEL(ch) {
u32 reg = MCHBAR32(CxDRA_MCHBAR(ch)) & ~CxDRA_PAGESIZE_MASK;
FOR_EACH_POPULATED_RANK_IN_CHANNEL(dimms, ch, r) {
/* Fixed page size for pre-jedec config. */
const unsigned int page_size = /* dimm page size in bytes */
prejedec ? 4096 : dimms[ch].page_size;
reg |= CxDRA_PAGESIZE(r, log2(page_size));
/* deferred to f5_27: reg |= CxDRA_BANKS(r, dimms[ch].banks); */
}
MCHBAR32(CxDRA_MCHBAR(ch)) = reg;
}
/* Calculate memory mapping, all values in MB. */
const unsigned int MMIOstart = 0x0c00; /* 3GB, makes MTRR configuration small. */
const unsigned int ME_SIZE = 0;
const unsigned int usedMEsize = (total_mb[0] != total_mb[1]) ? ME_SIZE : 2 * ME_SIZE;
const unsigned int claimCapable =
!(pci_read_config32(PCI_DEV(0, 0, 0), D0F0_CAPID0 + 4) & (1 << (47 - 32)));
const unsigned int TOM = total_mb[0] + total_mb[1];
unsigned int TOMminusME = TOM - usedMEsize;
unsigned int TOLUD = (TOMminusME < MMIOstart) ? TOMminusME : MMIOstart;
unsigned int TOUUD = TOMminusME;
unsigned int REMAPbase = 0xffff, REMAPlimit = 0;
if (claimCapable && (TOMminusME >= (MMIOstart + 64))) {
/* 64MB alignment: We'll lose some MBs here, if ME is on. */
TOMminusME &= ~(64 - 1);
/* 64MB alignment: Loss will be reclaimed. */
TOLUD &= ~(64 - 1);
if (TOMminusME > 4096) {
REMAPbase = TOMminusME;
REMAPlimit = REMAPbase + (4096 - TOLUD);
} else {
REMAPbase = 4096;
REMAPlimit = REMAPbase + (TOMminusME - TOLUD);
}
TOUUD = REMAPlimit;
/* REMAPlimit is an inclusive bound, all others exclusive. */
REMAPlimit -= 64;
}
pci_write_config16(PCI_DEV(0, 0, 0), D0F0_TOM, (TOM >> 7) & 0x1ff);
pci_write_config16(PCI_DEV(0, 0, 0), D0F0_TOLUD, TOLUD << 4);
pci_write_config16(PCI_DEV(0, 0, 0), D0F0_TOUUD, TOUUD);
pci_write_config16(PCI_DEV(0, 0, 0), D0F0_REMAPBASE, (REMAPbase >> 6) & 0x03ff);
pci_write_config16(PCI_DEV(0, 0, 0), D0F0_REMAPLIMIT, (REMAPlimit >> 6) & 0x03ff);
/* Program channel mode. */
switch (mode) {
case CHANNEL_MODE_SINGLE:
printk(BIOS_DEBUG, "Memory configured in single-channel mode.\n");
MCHBAR32(DCC_MCHBAR) &= ~DCC_INTERLEAVED;
break;
case CHANNEL_MODE_DUAL_ASYNC:
printk(BIOS_DEBUG, "Memory configured in dual-channel assymetric mode.\n");
MCHBAR32(DCC_MCHBAR) &= ~DCC_INTERLEAVED;
break;
case CHANNEL_MODE_DUAL_INTERLEAVED:
printk(BIOS_DEBUG, "Memory configured in dual-channel interleaved mode.\n");
MCHBAR32(DCC_MCHBAR) &= ~(DCC_NO_CHANXOR | (1 << 9));
MCHBAR32(DCC_MCHBAR) |= DCC_INTERLEAVED;
break;
}
printk(BIOS_SPEW, "Memory map:\n"
"TOM = %5uMB\n"
"TOLUD = %5uMB\n"
"TOUUD = %5uMB\n"
"REMAP:\t base = %5uMB\n"
"\t limit = %5uMB\n",
TOM, TOLUD, TOUUD, REMAPbase, REMAPlimit);
}
static void prejedec_memory_map(const dimminfo_t *const dimms, channel_mode_t mode)
{
/* Never use dual-interleaved mode in pre-jedec config. */
if (CHANNEL_MODE_DUAL_INTERLEAVED == mode)
mode = CHANNEL_MODE_DUAL_ASYNC;
program_memory_map(dimms, mode, 1);
MCHBAR32(DCC_MCHBAR) |= DCC_NO_CHANXOR;
}
static void ddr3_select_clock_mux(const mem_clock_t ddr3clock,
const dimminfo_t *const dimms,
const stepping_t stepping)
{
const int clk1067 = (ddr3clock == MEM_CLOCK_1067MT);
const int cardF[] = { CHANNEL_IS_CARDF(dimms, 0), CHANNEL_IS_CARDF(dimms, 1) };
int ch;
if (stepping < STEPPING_B1)
die("Stepping <B1 unsupported in clock-multiplexer selection.\n");
FOR_EACH_POPULATED_CHANNEL(dimms, ch) {
int mixed = 0;
if ((1 == ch) && (!CHANNEL_IS_POPULATED(dimms, 0) || (cardF[0] != cardF[1])))
mixed = 4 << 11;
const unsigned int b = 0x14b0 + (ch * 0x0100);
MCHBAR32(b+0x1c) = (MCHBAR32(b+0x1c) & ~(7 << 11)) |
((( cardF[ch])?1:0) << 11) | mixed;
MCHBAR32(b+0x18) = (MCHBAR32(b+0x18) & ~(7 << 11)) | mixed;
MCHBAR32(b+0x14) = (MCHBAR32(b+0x14) & ~(7 << 11)) |
(((!clk1067 && !cardF[ch])?0:1) << 11) | mixed;
MCHBAR32(b+0x10) = (MCHBAR32(b+0x10) & ~(7 << 11)) |
((( clk1067 && !cardF[ch])?1:0) << 11) | mixed;
MCHBAR32(b+0x0c) = (MCHBAR32(b+0x0c) & ~(7 << 11)) |
((( cardF[ch])?3:2) << 11) | mixed;
MCHBAR32(b+0x08) = (MCHBAR32(b+0x08) & ~(7 << 11)) |
(2 << 11) | mixed;
MCHBAR32(b+0x04) = (MCHBAR32(b+0x04) & ~(7 << 11)) |
(((!clk1067 && !cardF[ch])?2:3) << 11) | mixed;
MCHBAR32(b+0x00) = (MCHBAR32(b+0x00) & ~(7 << 11)) |
((( clk1067 && !cardF[ch])?3:2) << 11) | mixed;
}
}
static void ddr3_write_io_init(const mem_clock_t ddr3clock,
const dimminfo_t *const dimms,
const stepping_t stepping,
const int sff)
{
const int a1step = stepping >= STEPPING_CONVERSION_A1;
const int cardF[] = { CHANNEL_IS_CARDF(dimms, 0), CHANNEL_IS_CARDF(dimms, 1) };
int ch;
if (stepping < STEPPING_B1)
die("Stepping <B1 unsupported in write i/o initialization.\n");
if (sff)
die("SFF platform unsupported in write i/o initialization.\n");
static const u32 ddr3_667_800_by_stepping_ddr3_and_card[][2][2][4] = {
{ /* Stepping B3 and below */
{ /* 667 MHz */
{ 0xa3255008, 0x26888209, 0x26288208, 0x6188040f },
{ 0x7524240b, 0xa5255608, 0x232b8508, 0x5528040f },
},
{ /* 800 MHz */
{ 0xa6255308, 0x26888209, 0x212b7508, 0x6188040f },
{ 0x7524240b, 0xa6255708, 0x132b7508, 0x5528040f },
},
},
{ /* Conversion stepping A1 and above */
{ /* 667 MHz */
{ 0xc5257208, 0x26888209, 0x26288208, 0x6188040f },
{ 0x7524240b, 0xc5257608, 0x232b8508, 0x5528040f },
},
{ /* 800 MHz */
{ 0xb6256308, 0x26888209, 0x212b7508, 0x6188040f },
{ 0x7524240b, 0xb6256708, 0x132b7508, 0x5528040f },
}
}};
static const u32 ddr3_1067_by_channel_and_card[][2][4] = {
{ /* Channel A */
{ 0xb2254708, 0x002b7408, 0x132b8008, 0x7228060f },
{ 0xb0255008, 0xa4254108, 0x4528b409, 0x9428230f },
},
{ /* Channel B */
{ 0xa4254208, 0x022b6108, 0x132b8208, 0x9228210f },
{ 0x6024140b, 0x92244408, 0x252ba409, 0x9328360c },
},
};
FOR_EACH_POPULATED_CHANNEL(dimms, ch) {
if ((1 == ch) && CHANNEL_IS_POPULATED(dimms, 0) && (cardF[0] == cardF[1]))
/* Only write if second channel population differs. */
continue;
const u32 *const data = (ddr3clock != MEM_CLOCK_1067MT)
? ddr3_667_800_by_stepping_ddr3_and_card[a1step][2 - ddr3clock][cardF[ch]]
: ddr3_1067_by_channel_and_card[ch][cardF[ch]];
MCHBAR32(CxWRTy_MCHBAR(ch, 0)) = data[0];
MCHBAR32(CxWRTy_MCHBAR(ch, 1)) = data[1];
MCHBAR32(CxWRTy_MCHBAR(ch, 2)) = data[2];
MCHBAR32(CxWRTy_MCHBAR(ch, 3)) = data[3];
}
MCHBAR32(0x1490) = 0x00e70067;
MCHBAR32(0x1494) = 0x000d8000;
MCHBAR32(0x1590) = 0x00e70067;
MCHBAR32(0x1594) = 0x000d8000;
}
static void ddr3_read_io_init(const mem_clock_t ddr3clock,
const dimminfo_t *const dimms,
const int sff)
{
int ch;
FOR_EACH_POPULATED_CHANNEL(dimms, ch) {
u32 addr, tmp;
const unsigned int base = 0x14b0 + (ch * 0x0100);
for (addr = base + 0x1c; addr >= base; addr -= 4) {
tmp = MCHBAR32(addr);
tmp &= ~((3 << 25) | (1 << 8) | (7 << 16) | (0xf << 20) | (1 << 27));
tmp |= (1 << 27);
switch (ddr3clock) {
case MEM_CLOCK_667MT:
tmp |= (1 << 16) | (4 << 20);
break;
case MEM_CLOCK_800MT:
tmp |= (2 << 16) | (3 << 20);
break;
case MEM_CLOCK_1067MT:
if (!sff)
tmp |= (2 << 16) | (1 << 20);
else
tmp |= (2 << 16) | (2 << 20);
break;
default:
die("Wrong clock");
}
MCHBAR32(addr) = tmp;
}
}
}
static void memory_io_init(const mem_clock_t ddr3clock,
const dimminfo_t *const dimms,
const stepping_t stepping,
const int sff)
{
u32 tmp;
if (stepping < STEPPING_B1)
die("Stepping <B1 unsupported in "
"system-memory i/o initialization.\n");
tmp = MCHBAR32(0x1400);
tmp &= ~(3<<13);
tmp |= (1<<9) | (1<<13);
MCHBAR32(0x1400) = tmp;
tmp = MCHBAR32(0x140c);
tmp &= ~(0xff | (1<<11) | (1<<12) |
(1<<16) | (1<<18) | (1<<27) | (0xf<<28));
tmp |= (1<<7) | (1<<11) | (1<<16);
switch (ddr3clock) {
case MEM_CLOCK_667MT:
tmp |= 9 << 28;
break;
case MEM_CLOCK_800MT:
tmp |= 7 << 28;
break;
case MEM_CLOCK_1067MT:
tmp |= 8 << 28;
break;
}
MCHBAR32(0x140c) = tmp;
MCHBAR32(0x1440) &= ~1;
tmp = MCHBAR32(0x1414);
tmp &= ~((1<<20) | (7<<11) | (0xf << 24) | (0xf << 16));
tmp |= (3<<11);
switch (ddr3clock) {
case MEM_CLOCK_667MT:
tmp |= (2 << 24) | (10 << 16);
break;
case MEM_CLOCK_800MT:
tmp |= (3 << 24) | (7 << 16);
break;
case MEM_CLOCK_1067MT:
tmp |= (4 << 24) | (4 << 16);
break;
}
MCHBAR32(0x1414) = tmp;
MCHBAR32(0x1418) &= ~((1<<3) | (1<<11) | (1<<19) | (1<<27));
MCHBAR32(0x141c) &= ~((1<<3) | (1<<11) | (1<<19) | (1<<27));
MCHBAR32(0x1428) |= 1<<14;
tmp = MCHBAR32(0x142c);
tmp &= ~((0xf << 8) | (0x7 << 20) | 0xf | (0xf << 24));
tmp |= (0x3 << 20) | (5 << 24);
switch (ddr3clock) {
case MEM_CLOCK_667MT:
tmp |= (2 << 8) | 0xc;
break;
case MEM_CLOCK_800MT:
tmp |= (3 << 8) | 0xa;
break;
case MEM_CLOCK_1067MT:
tmp |= (4 << 8) | 0x7;
break;
}
MCHBAR32(0x142c) = tmp;
tmp = MCHBAR32(0x400);
tmp &= ~((3 << 4) | (3 << 16) | (3 << 30));
tmp |= (2 << 4) | (2 << 16);
MCHBAR32(0x400) = tmp;
MCHBAR32(0x404) &= ~(0xf << 20);
MCHBAR32(0x40c) &= ~(1 << 6);
tmp = MCHBAR32(0x410);
tmp &= ~(7 << 28);
tmp |= 2 << 28;
MCHBAR32(0x410) = tmp;
tmp = MCHBAR32(0x41c);
tmp &= ~0x77;
tmp |= 0x11;
MCHBAR32(0x41c) = tmp;
ddr3_select_clock_mux(ddr3clock, dimms, stepping);
ddr3_write_io_init(ddr3clock, dimms, stepping, sff);
ddr3_read_io_init(ddr3clock, dimms, sff);
}
static void jedec_init(const timings_t *const timings,
const dimminfo_t *const dimms)
{
if ((timings->tWR < 5) || (timings->tWR > 12))
die("tWR value unsupported in Jedec initialization.\n");
/* Pre-jedec settings */
MCHBAR32(0x40) |= (1 << 1);
MCHBAR32(0x230) |= (3 << 1);
MCHBAR32(0x238) |= (3 << 24);
MCHBAR32(0x23c) |= (3 << 24);
/* Normal write pointer operation */
MCHBAR32(0x14f0) |= (1 << 9);
MCHBAR32(0x15f0) |= (1 << 9);
MCHBAR32(DCC_MCHBAR) = (MCHBAR32(DCC_MCHBAR) & ~DCC_CMD_MASK) | DCC_CMD_NOP;
u8 reg8 = pci_read_config8(PCI_DEV(0, 0, 0), 0xf0);
pci_write_config8(PCI_DEV(0, 0, 0), 0xf0, reg8 & ~(1 << 2));
reg8 = pci_read_config8(PCI_DEV(0, 0, 0), 0xf0);
pci_write_config8(PCI_DEV(0, 0, 0), 0xf0, reg8 | (1 << 2));
udelay(2);
/* 5 6 7 8 9 10 11 12 */
static const u8 wr_lut[] = { 1, 2, 3, 4, 5, 5, 6, 6 };
const int WL = ((timings->tWL - 5) & 7) << 6;
const int ODT_120OHMS = (1 << 9);
const int ODS_34OHMS = (1 << 4);
const int WR = (wr_lut[timings->tWR - 5] & 7) << 12;
const int DLL1 = 1 << 11;
const int CAS = ((timings->CAS - 4) & 7) << 7;
const int INTERLEAVED = 1 << 6;/* This is READ Burst Type == interleaved. */
int ch, r;
FOR_EACH_POPULATED_RANK(dimms, ch, r) {
/* We won't do this in dual-interleaved mode,
so don't care about the offset. */
const u32 rankaddr = raminit_get_rank_addr(ch, r);
printk(BIOS_DEBUG, "Performing Jedec initialization at address 0x%08x.\n", rankaddr);
MCHBAR32(DCC_MCHBAR) = (MCHBAR32(DCC_MCHBAR) & ~DCC_SET_EREG_MASK) | DCC_SET_EREGx(2);
read32(rankaddr | WL);
MCHBAR32(DCC_MCHBAR) = (MCHBAR32(DCC_MCHBAR) & ~DCC_SET_EREG_MASK) | DCC_SET_EREGx(3);
read32(rankaddr);
MCHBAR32(DCC_MCHBAR) = (MCHBAR32(DCC_MCHBAR) & ~DCC_SET_EREG_MASK) | DCC_SET_EREGx(1);
read32(rankaddr | ODT_120OHMS | ODS_34OHMS);
MCHBAR32(DCC_MCHBAR) = (MCHBAR32(DCC_MCHBAR) & ~DCC_CMD_MASK) | DCC_SET_MREG;
read32(rankaddr | WR | DLL1 | CAS | INTERLEAVED);
MCHBAR32(DCC_MCHBAR) = (MCHBAR32(DCC_MCHBAR) & ~DCC_CMD_MASK) | DCC_SET_MREG;
read32(rankaddr | WR | CAS | INTERLEAVED);
}
}
static void ddr3_calibrate_zq(void) {
udelay(2);
u32 tmp = MCHBAR32(DCC_MCHBAR);
tmp &= ~(7 << 16);
tmp |= (5 << 16); /* ZQ calibration mode */
MCHBAR32(DCC_MCHBAR) = tmp;
MCHBAR32(CxDRT6_MCHBAR(0)) |= (1 << 3);
MCHBAR32(CxDRT6_MCHBAR(1)) |= (1 << 3);
udelay(1);
MCHBAR32(CxDRT6_MCHBAR(0)) &= ~(1 << 3);
MCHBAR32(CxDRT6_MCHBAR(1)) &= ~(1 << 3);
MCHBAR32(DCC_MCHBAR) |= (7 << 16); /* Normal operation */
}
static void post_jedec_sequence(const int cores) {
const int quadcore = cores == 4;
MCHBAR32(0x0040) &= ~(1 << 1);
MCHBAR32(0x0230) &= ~(3 << 1);
MCHBAR32(0x0230) |= 1 << 15;
MCHBAR32(0x0230) &= ~(1 << 19);
MCHBAR32(0x1250) = 0x6c4;
MCHBAR32(0x1350) = 0x6c4;
MCHBAR32(0x1254) = 0x871a066d;
MCHBAR32(0x1354) = 0x871a066d;
MCHBAR32(0x0238) |= 1 << 26;
MCHBAR32(0x0238) &= ~(3 << 24);
MCHBAR32(0x0238) |= 1 << 23;
MCHBAR32(0x0238) = (MCHBAR32(0x238) & ~(7 << 20)) | (3 << 20);
MCHBAR32(0x0238) = (MCHBAR32(0x238) & ~(7 << 17)) | (6 << 17);
MCHBAR32(0x0238) = (MCHBAR32(0x238) & ~(7 << 14)) | (6 << 14);
MCHBAR32(0x0238) = (MCHBAR32(0x238) & ~(7 << 11)) | (6 << 11);
MCHBAR32(0x0238) = (MCHBAR32(0x238) & ~(7 << 8)) | (6 << 8);
MCHBAR32(0x023c) &= ~(3 << 24);
MCHBAR32(0x023c) &= ~(1 << 23);
MCHBAR32(0x023c) = (MCHBAR32(0x23c) & ~(7 << 20)) | (3 << 20);
MCHBAR32(0x023c) = (MCHBAR32(0x23c) & ~(7 << 17)) | (6 << 17);
MCHBAR32(0x023c) = (MCHBAR32(0x23c) & ~(7 << 14)) | (6 << 14);
MCHBAR32(0x023c) = (MCHBAR32(0x23c) & ~(7 << 11)) | (6 << 11);
MCHBAR32(0x023c) = (MCHBAR32(0x23c) & ~(7 << 8)) | (6 << 8);
if (quadcore) {
MCHBAR32(0xb14) |= (0xbfbf << 16);
}
}
static void dram_optimizations(const timings_t *const timings,
const dimminfo_t *const dimms)
{
int ch;
FOR_EACH_POPULATED_CHANNEL(dimms, ch) {
const unsigned int mchbar = CxDRC1_MCHBAR(ch);
u32 cxdrc1 = MCHBAR32(mchbar);
cxdrc1 &= ~CxDRC1_SSDS_MASK;
if (dimms[ch].ranks == 1)
cxdrc1 |= CxDRC1_SS;
else
cxdrc1 |= CxDRC1_DS;
MCHBAR32(mchbar) = cxdrc1;
}
}
u32 raminit_get_rank_addr(unsigned int channel, unsigned int rank)
{
if (!channel && !rank)
return 0; /* Address of first rank */
/* Read the bound of the previous rank. */
if (rank > 0) {
rank--;
} else {
rank = 3; /* Highest rank per channel */
channel--;
}
const u32 reg = MCHBAR32(CxDRBy_MCHBAR(channel, rank));
/* Bound is in 32MB. */
return ((reg & CxDRBy_BOUND_MASK(rank)) >> CxDRBy_BOUND_SHIFT(rank)) << 25;
}
void raminit_reset_readwrite_pointers(void) {
MCHBAR32(0x1234) |= (1 << 6);
MCHBAR32(0x1234) &= ~(1 << 6);
MCHBAR32(0x1334) |= (1 << 6);
MCHBAR32(0x1334) &= ~(1 << 6);
MCHBAR32(0x14f0) &= ~(1 << 9);
MCHBAR32(0x14f0) |= (1 << 9);
MCHBAR32(0x14f0) |= (1 << 10);
MCHBAR32(0x15f0) &= ~(1 << 9);
MCHBAR32(0x15f0) |= (1 << 9);
MCHBAR32(0x15f0) |= (1 << 10);
}
void raminit(sysinfo_t *const sysinfo, const int s3resume)
{
const dimminfo_t *const dimms = sysinfo->dimms;
const timings_t *const timings = &sysinfo->selected_timings;
const int sff = sysinfo->gfx_type == GMCH_GS45;
int ch;
u8 reg8;
/* Wait for some bit, maybe TXT clear. */
if (sysinfo->txt_enabled) {
while (!(read8(0xfed40000) & (1 << 7))) {}
}
/* Enable SMBUS. */
enable_smbus();
/* Collect information about DIMMs and find common settings. */
collect_dimm_config(sysinfo);
/* Check for bad warm boot. */
reset_on_bad_warmboot();
/***** From now on, program according to collected infos: *****/
/* Program DRAM type. */
switch (sysinfo->spd_type) {
case DDR2:
MCHBAR8(0x1434) |= (1 << 7);
break;
case DDR3:
MCHBAR8(0x1434) |= (3 << 0);
break;
}
/* Program system memory frequency. */
set_system_memory_frequency(timings);
/* Program IGD memory frequency. */
set_igd_memory_frequencies(sysinfo);
/* Configure DRAM control mode for populated channels. */
configure_dram_control_mode(timings, dimms);
/* Initialize RCOMP. */
rcomp_initialization(sysinfo->stepping, sff);
/* Power-up DRAM. */
dram_powerup(s3resume);
/* Program DRAM timings. */
dram_program_timings(timings);
/* Program number of banks. */
dram_program_banks(dimms);
/* Enable DRAM clock pairs for populated DIMMs. */
FOR_EACH_POPULATED_CHANNEL(dimms, ch)
MCHBAR32(CxDCLKDIS_MCHBAR(ch)) |= CxDCLKDIS_ENABLE;
/* Enable On-Die Termination. */
odt_setup(timings, sff);
/* Miscellaneous settings. */
misc_settings(timings, sysinfo->stepping);
/* Program clock crossing registers. */
clock_crossing_setup(timings->fsb_clock, timings->mem_clock, dimms);
/* Program egress VC1 timings. */
vc1_program_timings(timings->fsb_clock);
/* Perform system-memory i/o initialization. */
memory_io_init(timings->mem_clock, dimms, sysinfo->stepping, sff);
/* Initialize memory map with dummy values of 128MB per rank with a
page size of 4KB. This makes the JEDEC initialization code easier. */
prejedec_memory_map(dimms, timings->channel_mode);
if (!s3resume)
/* Perform JEDEC initialization of DIMMS. */
jedec_init(timings, dimms);
/* Some programming steps after JEDEC initialization. */
post_jedec_sequence(sysinfo->cores);
/* Announce normal operation, initialization completed. */
MCHBAR32(DCC_MCHBAR) |= (0x7 << 16) | (0x1 << 19);
reg8 = pci_read_config8(PCI_DEV(0, 0, 0), 0xf0);
pci_write_config8(PCI_DEV(0, 0, 0), 0xf0, reg8 | (1 << 2));
reg8 = pci_read_config8(PCI_DEV(0, 0, 0), 0xf0);
pci_write_config8(PCI_DEV(0, 0, 0), 0xf0, reg8 & ~(1 << 2));
/* Take a breath (the reader). */
/* Perform ZQ calibration for DDR3. */
ddr3_calibrate_zq();
/* Perform receive-enable calibration. */
raminit_receive_enable_calibration(timings, dimms);
/* Lend clock values from receive-enable calibration. */
MCHBAR32(0x1224) = (MCHBAR32(0x1224) & ~(0xf0)) |
((((MCHBAR32(0x121c) >> 7) - 1) & 0xf) << 4);
MCHBAR32(0x1324) = (MCHBAR32(0x1324) & ~(0xf0)) |
((((MCHBAR32(0x131c) >> 7) - 1) & 0xf) << 4);
/* Perform read/write training for high clock rate. */
if (timings->mem_clock == MEM_CLOCK_1067MT) {
raminit_read_training(dimms, s3resume);
raminit_write_training(timings->mem_clock, dimms, s3resume);
}
/* Program final memory map (with real values). */
program_memory_map(dimms, timings->channel_mode, 0);
/* Some last optimizations. */
dram_optimizations(timings, dimms);
/* Mark raminit beeing finished. :-) */
u8 tmp8 = pci_read_config8(PCI_DEV(0, 0x1f, 0), 0xa2) & ~(1 << 7);
pci_write_config8(PCI_DEV(0, 0x1f, 0), 0xa2, tmp8);
}
| 31.529511 | 108 | 0.635877 | [
"render"
] |
d60c4fec697de152768716e2fe200de6a09853c5 | 2,628 | h | C | locomotion_framework/utils/rbdl_utils/include/mwoibn/rbdl_utils/rbdl_utils.h | ADVRHumanoids/DrivingFramework | 34715c37bfe3c1f2bd92aeacecc12704a1a7820e | [
"Zlib"
] | 1 | 2019-12-02T07:10:42.000Z | 2019-12-02T07:10:42.000Z | locomotion_framework/utils/rbdl_utils/include/mwoibn/rbdl_utils/rbdl_utils.h | ADVRHumanoids/DrivingFramework | 34715c37bfe3c1f2bd92aeacecc12704a1a7820e | [
"Zlib"
] | null | null | null | locomotion_framework/utils/rbdl_utils/include/mwoibn/rbdl_utils/rbdl_utils.h | ADVRHumanoids/DrivingFramework | 34715c37bfe3c1f2bd92aeacecc12704a1a7820e | [
"Zlib"
] | 2 | 2020-10-22T19:06:44.000Z | 2021-06-07T03:32:52.000Z | #ifndef RBDL_UTILS_RBDL_UTILS_H
#define RBDL_UTILS_RBDL_UTILS_H
#include <rbdl/rbdl.h>
namespace mwoibn
{
namespace rbdl_utils
{
const std::string PACKAGE = "rbdl_utils";
//! Provides the SVD pseudoinverse for Eigen library
/**
* \param[in] a the matrix pseudoinverse is computed for
* \param[in] epsilon dafines numerical resultion of considered values, elements
*of a matrix below this value are considered zero in copmutation of an inverse
* \return a computed pseudoinverse
*
*/
static RigidBodyDynamics::Math::Quaternion
fromMatrix(const RigidBodyDynamics::Math::Matrix3d& rotation, double eps = 1e-4)
{
// std::cout << "new\n";
double trace = rotation(0,0) + rotation(1,1) + rotation(2,2);
if (trace > 0)
{
// std::cout << "w" << std::endl;
double s = 2.0 * sqrt(trace + 1.0);
return RigidBodyDynamics::Math::Quaternion(
(-rotation(2,1) + rotation(1,2)) / s,
(-rotation(0,2) + rotation(2,0)) / s,
(-rotation(1,0) + rotation(0,1)) / s, 0.25 * s);
}
if (rotation(0,0) > rotation(1,1) && rotation(0,0) > rotation(2,2))
{
// std::cout << "x" << std::endl;
double s = 2.0 * sqrt(1.0 + rotation(0,0) - rotation(1,1) - rotation(2,2));
return RigidBodyDynamics::Math::Quaternion(
0.25 * s, (-rotation(0,1) - rotation(1,0)) / s,
(-rotation(0,2) - rotation(2,0)) / s,
(-rotation(2,1) + rotation(1,2)) / s);
}
if (rotation(1,1) > rotation(2,2))
{
// std::cout << "y" << std::endl;
double s =
2.0 * sqrt(1.0 + rotation(1,1) - rotation(0,0) - rotation(2,2));
return RigidBodyDynamics::Math::Quaternion(
(-rotation(0,1) - rotation(1,0)) / s, 0.25 * s,
(-rotation(1,2) - rotation(2,1)) / s,
(-rotation(0,2) + rotation(2,0)) / s);
}
// std::cout << "z" << std::endl;
double s = 2.0 * sqrt(1.0 + rotation(2,2) - rotation(0,0) - rotation(1,1));
return RigidBodyDynamics::Math::Quaternion(
(-rotation(0,2) - rotation(2,0)) / s,
(-rotation(1,2) - rotation(2,1)) / s, 0.25 * s,
(-rotation(1,0) + rotation(0,1)) / s);
}
/** helping function to provide functinoality of calling functions through
* frames RBDL names */
inline unsigned int checkBody(std::string body_name,
RigidBodyDynamics::Model& model)
{
unsigned int body_id = model.GetBodyId(body_name.c_str());
if (body_id == std::numeric_limits<unsigned int>::max())
{
throw(std::invalid_argument("unknown body, " + body_name +
" couldn't find it in a RBDL model"));
}
return body_id;
}
} // namespace package
} // namespace library
#endif
| 29.863636 | 80 | 0.605023 | [
"model"
] |
d612b4f60b56bbf5b2bf584af804d643340614a4 | 2,118 | h | C | src/overlay/perfect/PerfectCC.h | uroni/multic | c0cd7e1fa0214d6d64b07826dd0ee3e9a36e4d59 | [
"Apache-2.0"
] | 2 | 2020-01-21T13:14:54.000Z | 2020-03-27T12:38:42.000Z | src/overlay/perfect/PerfectCC.h | uroni/multic | c0cd7e1fa0214d6d64b07826dd0ee3e9a36e4d59 | [
"Apache-2.0"
] | 1 | 2019-10-15T19:25:26.000Z | 2019-10-15T19:25:26.000Z | src/overlay/perfect/PerfectCC.h | uroni/multic | c0cd7e1fa0214d6d64b07826dd0ee3e9a36e4d59 | [
"Apache-2.0"
] | null | null | null | /*
* AimdCC.h
*
* Created on: 27.05.2010
* Author: Martin
*/
#ifndef PERFECTCC_H
#define PERFECTCC_H
#include "../basic/BasicCC.h"
class PerfectCC;
struct SRoute
{
SRoute(int pTimestep, int pId) : timestep(pTimestep), id(pId){}
SRoute(void){ timestep=0; id=0; }
int timestep;
int id;
};
struct SLimit
{
simtime_t upper;
simtime_t lower;
};
/**
* Perfect congestion control for testing purposes
*/
class PerfectCC : public BasicCC
{
public:
PerfectCC();
virtual ~PerfectCC();
virtual void initializeOverlay( int stage );
virtual void handleTimerEvent(cMessage* msg);
std::vector<int> getRoute(int source, int target, size_t msglen);
/**
* Update the manager latencies
*/
void updateLatency(SRtt pRtt, int source, int target);
simtime_t getNextTime(void);
virtual simtime_t getNextResetIncomingTime(void);
virtual bool hasCapacity(size_t msglen);
/**
* Function in the manager
*/
virtual bool hasCapacity(int source, size_t msglen);
protected:
virtual std::vector<int> getPathNodes(int target, int hops,size_t msglen, void **userdata);
virtual void handleLossEvent(const std::vector<int> &route, void *userdata);
virtual void handleAckEvent(const std::vector<int> &route, void *userdata);
/**
* Get the latency information the manager has
*/
SRtt getManagerLatency(int source, int target);
/**
* Calculate the perfect route
*/
std::vector<SRoute> getRouteInt(int hop, int source, int target, simtime_t curr_time, std::vector<int> nodes, size_t msglen);
/**
* Get the current rate of a node in a certain timestep
*/
unsigned int getRateOfNode(int timestep, int node);
/**
* Increment the current rate of a node
*/
void incrementRateOfNode(int timestep, int node, int rate);
static PerfectCC *manager;
//manager
cMessage *manager_step_timer;
simtime_t nextstep_time;
uppermatrix<SRtt> rtts;
std::map<int, std::vector<unsigned int> > rates;
std::vector< std::vector<SLimit> > limits;
int curr_simtime_step;
};
#endif /* PERFECTCC_H */
| 22.0625 | 127 | 0.68508 | [
"vector"
] |
d61a35f2aacc4b49d3bbd19e661d5655557ea401 | 8,842 | h | C | code/vendor/botan_sv/include/botan/rng.h | thorium-cfx/fivem | 587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c | [
"MIT"
] | 5,411 | 2017-04-14T08:57:56.000Z | 2022-03-30T19:35:15.000Z | code/vendor/botan_sv/include/botan/rng.h | big-rip/fivem-1 | c08af22110802e77816dfdde29df1662f8dea563 | [
"MIT"
] | 802 | 2017-04-21T14:18:36.000Z | 2022-03-31T21:20:48.000Z | code/vendor/botan_sv/include/botan/rng.h | big-rip/fivem-1 | c08af22110802e77816dfdde29df1662f8dea563 | [
"MIT"
] | 2,011 | 2017-04-14T09:44:15.000Z | 2022-03-31T15:40:39.000Z | /*
* Random Number Generator base classes
* (C) 1999-2009,2015,2016 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#ifndef BOTAN_RANDOM_NUMBER_GENERATOR_H_
#define BOTAN_RANDOM_NUMBER_GENERATOR_H_
#include <botan/secmem.h>
#include <botan/exceptn.h>
#include <botan/mutex.h>
#include <chrono>
#include <string>
namespace Botan {
class Entropy_Sources;
/**
* An interface to a cryptographic random number generator
*/
class BOTAN_PUBLIC_API(2,0) RandomNumberGenerator
{
public:
virtual ~RandomNumberGenerator() = default;
RandomNumberGenerator() = default;
/*
* Never copy a RNG, create a new one
*/
RandomNumberGenerator(const RandomNumberGenerator& rng) = delete;
RandomNumberGenerator& operator=(const RandomNumberGenerator& rng) = delete;
/**
* Randomize a byte array.
* @param output the byte array to hold the random output.
* @param length the length of the byte array output in bytes.
*/
virtual void randomize(uint8_t output[], size_t length) = 0;
/**
* Returns false if it is known that this RNG object is not able to accept
* externally provided inputs (via add_entropy, randomize_with_input, etc).
* In this case, any such provided inputs are ignored.
*
* If this function returns true, then inputs may or may not be accepted.
*/
virtual bool accepts_input() const = 0;
/**
* Incorporate some additional data into the RNG state. For
* example adding nonces or timestamps from a peer's protocol
* message can help hedge against VM state rollback attacks.
* A few RNG types do not accept any externally provided input,
* in which case this function is a no-op.
*
* @param input a byte array containg the entropy to be added
* @param length the length of the byte array in
*/
virtual void add_entropy(const uint8_t input[], size_t length) = 0;
/**
* Incorporate some additional data into the RNG state.
*/
template<typename T> void add_entropy_T(const T& t)
{
this->add_entropy(reinterpret_cast<const uint8_t*>(&t), sizeof(T));
}
/**
* Incorporate entropy into the RNG state then produce output.
* Some RNG types implement this using a single operation, default
* calls add_entropy + randomize in sequence.
*
* Use this to further bind the outputs to your current
* process/protocol state. For instance if generating a new key
* for use in a session, include a session ID or other such
* value. See NIST SP 800-90 A, B, C series for more ideas.
*
* @param output buffer to hold the random output
* @param output_len size of the output buffer in bytes
* @param input entropy buffer to incorporate
* @param input_len size of the input buffer in bytes
*/
virtual void randomize_with_input(uint8_t output[], size_t output_len,
const uint8_t input[], size_t input_len);
/**
* This calls `randomize_with_input` using some timestamps as extra input.
*
* For a stateful RNG using non-random but potentially unique data the
* extra input can help protect against problems with fork, VM state
* rollback, or other cases where somehow an RNG state is duplicated. If
* both of the duplicated RNG states later incorporate a timestamp (and the
* timestamps don't themselves repeat), their outputs will diverge.
*/
virtual void randomize_with_ts_input(uint8_t output[], size_t output_len);
/**
* @return the name of this RNG type
*/
virtual std::string name() const = 0;
/**
* Clear all internally held values of this RNG
* @post is_seeded() == false
*/
virtual void clear() = 0;
/**
* Check whether this RNG is seeded.
* @return true if this RNG was already seeded, false otherwise.
*/
virtual bool is_seeded() const = 0;
/**
* Poll provided sources for up to poll_bits bits of entropy
* or until the timeout expires. Returns estimate of the number
* of bits collected.
*/
virtual size_t reseed(Entropy_Sources& srcs,
size_t poll_bits = BOTAN_RNG_RESEED_POLL_BITS,
std::chrono::milliseconds poll_timeout = BOTAN_RNG_RESEED_DEFAULT_TIMEOUT);
/**
* Reseed by reading specified bits from the RNG
*/
virtual void reseed_from_rng(RandomNumberGenerator& rng,
size_t poll_bits = BOTAN_RNG_RESEED_POLL_BITS);
// Some utility functions built on the interface above:
/**
* Return a random vector
* @param bytes number of bytes in the result
* @return randomized vector of length bytes
*/
secure_vector<uint8_t> random_vec(size_t bytes)
{
secure_vector<uint8_t> output;
random_vec(output, bytes);
return output;
}
template<typename Alloc>
void random_vec(std::vector<uint8_t, Alloc>& v, size_t bytes)
{
v.resize(bytes);
this->randomize(v.data(), v.size());
}
/**
* Return a random byte
* @return random byte
*/
uint8_t next_byte()
{
uint8_t b;
this->randomize(&b, 1);
return b;
}
/**
* @return a random byte that is greater than zero
*/
uint8_t next_nonzero_byte()
{
uint8_t b = this->next_byte();
while(b == 0)
b = this->next_byte();
return b;
}
/**
* Create a seeded and active RNG object for general application use
* Added in 1.8.0
* Use AutoSeeded_RNG instead
*/
BOTAN_DEPRECATED("Use AutoSeeded_RNG")
static RandomNumberGenerator* make_rng();
};
/**
* Convenience typedef
*/
typedef RandomNumberGenerator RNG;
/**
* Hardware_RNG exists to tag hardware RNG types (PKCS11_RNG, TPM_RNG, RDRAND_RNG)
*/
class BOTAN_PUBLIC_API(2,0) Hardware_RNG : public RandomNumberGenerator
{
public:
virtual void clear() final override { /* no way to clear state of hardware RNG */ }
};
/**
* Null/stub RNG - fails if you try to use it for anything
* This is not generally useful except for in certain tests
*/
class BOTAN_PUBLIC_API(2,0) Null_RNG final : public RandomNumberGenerator
{
public:
bool is_seeded() const override { return false; }
bool accepts_input() const override { return false; }
void clear() override {}
void randomize(uint8_t[], size_t) override
{
throw PRNG_Unseeded("Null_RNG called");
}
void add_entropy(const uint8_t[], size_t) override {}
std::string name() const override { return "Null_RNG"; }
};
#if defined(BOTAN_TARGET_OS_HAS_THREADS)
/**
* Wraps access to a RNG in a mutex
* Note that most of the time it's much better to use a RNG per thread
* otherwise the RNG will act as an unnecessary contention point
*/
class BOTAN_PUBLIC_API(2,0) Serialized_RNG final : public RandomNumberGenerator
{
public:
void randomize(uint8_t out[], size_t len) override
{
lock_guard_type<mutex_type> lock(m_mutex);
m_rng->randomize(out, len);
}
bool accepts_input() const override
{
lock_guard_type<mutex_type> lock(m_mutex);
return m_rng->accepts_input();
}
bool is_seeded() const override
{
lock_guard_type<mutex_type> lock(m_mutex);
return m_rng->is_seeded();
}
void clear() override
{
lock_guard_type<mutex_type> lock(m_mutex);
m_rng->clear();
}
std::string name() const override
{
lock_guard_type<mutex_type> lock(m_mutex);
return m_rng->name();
}
size_t reseed(Entropy_Sources& src,
size_t poll_bits = BOTAN_RNG_RESEED_POLL_BITS,
std::chrono::milliseconds poll_timeout = BOTAN_RNG_RESEED_DEFAULT_TIMEOUT) override
{
lock_guard_type<mutex_type> lock(m_mutex);
return m_rng->reseed(src, poll_bits, poll_timeout);
}
void add_entropy(const uint8_t in[], size_t len) override
{
lock_guard_type<mutex_type> lock(m_mutex);
m_rng->add_entropy(in, len);
}
BOTAN_DEPRECATED("Use Serialized_RNG(new AutoSeeded_RNG)") Serialized_RNG();
explicit Serialized_RNG(RandomNumberGenerator* rng) : m_rng(rng) {}
private:
mutable mutex_type m_mutex;
std::unique_ptr<RandomNumberGenerator> m_rng;
};
#endif
}
#endif
| 30.701389 | 103 | 0.631305 | [
"object",
"vector"
] |
d61f41fbf6aacb13f1c21594ad68b66047488b42 | 5,138 | h | C | platform/darwin/src/MGLAbstractShapeSource.h | ckesc/mapbox-gl-native | 48744d51d8f460de3dc32ad4ef3e0ee12f80a149 | [
"BSL-1.0",
"Apache-2.0"
] | 3 | 2020-02-22T04:04:42.000Z | 2022-01-25T08:34:16.000Z | platform/darwin/src/MGLAbstractShapeSource.h | ckesc/mapbox-gl-native | 48744d51d8f460de3dc32ad4ef3e0ee12f80a149 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | platform/darwin/src/MGLAbstractShapeSource.h | ckesc/mapbox-gl-native | 48744d51d8f460de3dc32ad4ef3e0ee12f80a149 | [
"BSL-1.0",
"Apache-2.0"
] | 3 | 2019-04-10T03:37:12.000Z | 2019-05-28T08:59:00.000Z | #import "MGLSource.h"
/**
Options for `MGLShapeSource` objects.
*/
typedef NSString *MGLShapeSourceOption NS_STRING_ENUM;
/**
An `NSNumber` object containing a Boolean enabling or disabling clustering.
If the `shape` property contains point shapes, setting this option to
`YES` clusters the points by radius into groups. The default value is `NO`.
This attribute corresponds to the
<a href="https://www.mapbox.com/mapbox-gl-style-spec/#sources-geojson-cluster"><code>cluster</code></a>
source property in the Mapbox Style Specification.
This option only affects point features within a shape source.
*/
extern MGL_EXPORT const MGLShapeSourceOption MGLShapeSourceOptionClustered;
/**
An `NSNumber` object containing an integer; specifies the radius of each
cluster if clustering is enabled. A value of 512 produces a radius equal to
the width of a tile. The default value is 50.
*/
extern MGL_EXPORT const MGLShapeSourceOption MGLShapeSourceOptionClusterRadius;
/**
An `NSNumber` object containing an integer; specifies the maximum zoom level at
which to cluster points if clustering is enabled. Defaults to one zoom level
less than the value of `MGLShapeSourceOptionMaximumZoomLevel` so that, at the
maximum zoom level, the shapes are not clustered.
This attribute corresponds to the
<a href="https://www.mapbox.com/mapbox-gl-style-spec/#sources-geojson-clusterMaxZoom"><code>clusterMaxZoom</code></a>
source property in the Mapbox Style Specification.
*/
extern MGL_EXPORT const MGLShapeSourceOption MGLShapeSourceOptionMaximumZoomLevelForClustering;
/**
An `NSNumber` object containing an integer; specifies the minimum zoom level at
which to create vector tiles. The default value is 0.
This attribute corresponds to the
<a href="https://www.mapbox.com/mapbox-gl-style-spec/#sources-geojson-minzoom"><code>minzoom</code></a>
source property in the Mapbox Style Specification.
*/
extern MGL_EXPORT const MGLShapeSourceOption MGLShapeSourceOptionMinimumZoomLevel;
/**
An `NSNumber` object containing an integer; specifies the maximum zoom level at
which to create vector tiles. A greater value produces greater detail at high
zoom levels. The default value is 18.
This attribute corresponds to the
<a href="https://www.mapbox.com/mapbox-gl-style-spec/#sources-geojson-maxzoom"><code>maxzoom</code></a>
source property in the Mapbox Style Specification.
*/
extern MGL_EXPORT const MGLShapeSourceOption MGLShapeSourceOptionMaximumZoomLevel;
/**
An `NSNumber` object containing an integer; specifies the size of the tile
buffer on each side. A value of 0 produces no buffer. A value of 512 produces a
buffer as wide as the tile itself. Larger values produce fewer rendering
artifacts near tile edges and slower performance. The default value is 128.
This attribute corresponds to the
<a href="https://www.mapbox.com/mapbox-gl-style-spec/#sources-geojson-buffer"><code>buffer</code></a>
source property in the Mapbox Style Specification.
*/
extern MGL_EXPORT const MGLShapeSourceOption MGLShapeSourceOptionBuffer;
/**
An `NSNumber` object containing a double; specifies the Douglas-Peucker
simplification tolerance. A greater value produces simpler geometries and
improves performance. The default value is 0.375.
This attribute corresponds to the
<a href="https://www.mapbox.com/mapbox-gl-style-spec/#sources-geojson-tolerance"><code>tolerance</code></a>
source property in the Mapbox Style Specification.
*/
extern MGL_EXPORT const MGLShapeSourceOption MGLShapeSourceOptionSimplificationTolerance;
/**
An `NSNumber` object containing a Boolean value; specifies whether the shape of
an `MGLComputedShapeSource` should be wrapped to accomodate coordinates with
longitudes beyond −180 and 180. The default value is `NO`.
Setting this option to `YES` affects rendering performance.
This option is ignored when creating an instance of a class besides
`MGLComputedShapeSource`.
*/
extern MGL_EXPORT const MGLShapeSourceOption MGLShapeSourceOptionWrapsCoordinates;
/**
An `NSNumber` object containing a Boolean value; specifies whether the shape of
an `MGLComputedShapeSource` should be clipped at the edge of each tile. The
default value is `NO`.
Setting this option to `YES` affects rendering performance. Use this option to
clip `MGLPolyline`s and `MGLPolygon`s at tile boundaries without artifacts.
This option is ignored when creating an instance of a class besides
`MGLComputedShapeSource`.
*/
extern MGL_EXPORT const MGLShapeSourceOption MGLShapeSourceOptionClipsCoordinates;
/**
`MGLAbstractShapeSource` is an abstract base class for map content sources that
supply vector shapes to be shown on the map. A shape source is added to an
`MGLStyle` object along with an `MGLVectorStyleLayer` object. The vector style
layer defines the appearance of any content supplied by the shape source.
Do not create instances of this class directly, and do not create your own
subclasses of this class. Instead, create instances of `MGLShapeSource` or
`MGLComputedShapeSource`.
*/
MGL_EXPORT
@interface MGLAbstractShapeSource : MGLSource
@end
| 41.104 | 118 | 0.792721 | [
"object",
"shape",
"vector"
] |
d61f9115fcdd2a1f94ef5f79191a495c52c4e654 | 1,105 | h | C | CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/java/text/FieldPosition.h | chewaiwai/huaweicloud-sdk-c-obs | fbcd3dadd910c22af3a91aeb73ca0fee94d759fb | [
"Apache-2.0"
] | 22 | 2019-06-13T01:16:44.000Z | 2022-03-29T02:42:39.000Z | CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/java/text/FieldPosition.h | chewaiwai/huaweicloud-sdk-c-obs | fbcd3dadd910c22af3a91aeb73ca0fee94d759fb | [
"Apache-2.0"
] | 26 | 2019-09-20T06:46:05.000Z | 2022-03-11T08:07:14.000Z | CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/java/text/FieldPosition.h | chewaiwai/huaweicloud-sdk-c-obs | fbcd3dadd910c22af3a91aeb73ca0fee94d759fb | [
"Apache-2.0"
] | 14 | 2019-07-15T06:42:39.000Z | 2022-02-15T10:32:28.000Z |
// DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*-
#ifndef __java_text_FieldPosition__
#define __java_text_FieldPosition__
#pragma interface
#include <java/lang/Object.h>
extern "Java"
{
namespace java
{
namespace text
{
class FieldPosition;
class Format$Field;
}
}
}
class java::text::FieldPosition : public ::java::lang::Object
{
public:
FieldPosition(::java::text::Format$Field *);
FieldPosition(::java::text::Format$Field *, jint);
FieldPosition(jint);
virtual jint getField();
virtual ::java::text::Format$Field * getFieldAttribute();
virtual jint getBeginIndex();
virtual void setBeginIndex(jint);
virtual jint getEndIndex();
virtual void setEndIndex(jint);
virtual jboolean equals(::java::lang::Object *);
virtual jint hashCode();
virtual ::java::lang::String * toString();
private:
jint __attribute__((aligned(__alignof__( ::java::lang::Object)))) field_id;
jint begin;
jint end;
::java::text::Format$Field * field_attribute;
public:
static ::java::lang::Class class$;
};
#endif // __java_text_FieldPosition__
| 23.020833 | 77 | 0.695928 | [
"object"
] |
d623f7c42e518cf2db42c741107fff8c398284c6 | 1,397 | h | C | components/password_manager/core/browser/leak_detection/leak_detection_check.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | components/password_manager/core/browser/leak_detection/leak_detection_check.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | components/password_manager/core/browser/leak_detection/leak_detection_check.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_LEAK_DETECTION_LEAK_DETECTION_CHECK_H_
#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_LEAK_DETECTION_LEAK_DETECTION_CHECK_H_
#include <string>
#include "url/gurl.h"
namespace password_manager {
// The base class for requests for checking if {username, password} pair was
// leaked in the internet.
class LeakDetectionCheck {
public:
LeakDetectionCheck() = default;
virtual ~LeakDetectionCheck() = default;
// Not copyable or movable
LeakDetectionCheck(const LeakDetectionCheck&) = delete;
LeakDetectionCheck& operator=(const LeakDetectionCheck&) = delete;
LeakDetectionCheck(LeakDetectionCheck&&) = delete;
LeakDetectionCheck& operator=(LeakDetectionCheck&&) = delete;
// Starts checking |username| and |password| pair asynchronously.
// |url| is used later for presentation in the UI but not for actual business
// logic. The method should be called only once per lifetime of the object.
virtual void Start(const GURL& url,
std::u16string username,
std::u16string password) = 0;
};
} // namespace password_manager
#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_LEAK_DETECTION_LEAK_DETECTION_CHECK_H_
| 36.763158 | 90 | 0.767359 | [
"object"
] |
d628173dd691382f983f04c8261e31681fdb1916 | 101,232 | c | C | decompiled_scripts/appemail.c | gtapwn/GTA-V-Decompiled-Scripts | 43ed1f703af78ffb4e0263a88b9b9655f64d49c2 | [
"Unlicense"
] | null | null | null | decompiled_scripts/appemail.c | gtapwn/GTA-V-Decompiled-Scripts | 43ed1f703af78ffb4e0263a88b9b9655f64d49c2 | [
"Unlicense"
] | null | null | null | decompiled_scripts/appemail.c | gtapwn/GTA-V-Decompiled-Scripts | 43ed1f703af78ffb4e0263a88b9b9655f64d49c2 | [
"Unlicense"
] | 1 | 2021-02-06T16:12:31.000Z | 2021-02-06T16:12:31.000Z | #region Local Var
var uLocal_0 = 0;
var uLocal_1 = 0;
int iLocal_2 = 0;
int iLocal_3 = 0;
int iLocal_4 = 0;
int iLocal_5 = 0;
int iLocal_6 = 0;
int iLocal_7 = 0;
int iLocal_8 = 0;
int iLocal_9 = 0;
int iLocal_10 = 0;
int iLocal_11 = 0;
var uLocal_12 = 0;
var uLocal_13 = 0;
float fLocal_14 = 0f;
var uLocal_15 = 0;
var uLocal_16 = 0;
int iLocal_17 = 0;
int iLocal_18 = 0;
char* sLocal_19 = NULL;
var uLocal_20 = 0;
var uLocal_21 = 0;
float fLocal_22 = 0f;
var uLocal_23 = 0;
var uLocal_24 = 0;
var uLocal_25 = 0;
float fLocal_26 = 0f;
float fLocal_27 = 0f;
var uLocal_28 = 0;
int iLocal_29 = 0;
var uLocal_30 = 0;
var uLocal_31 = 0;
float fLocal_32 = 0f;
float fLocal_33 = 0f;
float fLocal_34 = 0f;
var uLocal_35 = 0;
var uLocal_36 = 0;
var uLocal_37 = 0;
var uLocal_38 = 0;
var uLocal_39 = 0;
int iLocal_40 = 0;
int iLocal_41 = 0;
int iLocal_42 = 0;
int iLocal_43 = 0;
var uLocal_44 = 0;
var uLocal_45 = 0;
var uLocal_46 = 0;
struct<3> Local_47 = { 0, 0, 0 } ;
struct<3> Local_50 = { 0, 0, 0 } ;
int iLocal_53 = 0;
int iLocal_54 = 0;
int iLocal_55 = 0;
int iLocal_56 = 0;
int iLocal_57 = 0;
int iLocal_58 = 0;
int iLocal_59 = 0;
int iLocal_60 = 0;
int iLocal_61 = 0;
int iLocal_62 = 0;
int iLocal_63 = 0;
int iLocal_64 = 0;
int iLocal_65 = 0;
int iLocal_66 = 0;
int iLocal_67 = 0;
int iLocal_68 = 0;
char* sLocal_69 = NULL;
float fLocal_70 = 0f;
int iLocal_71 = 0;
#endregion
void __EntryFunction__()
{
int iVar0;
iLocal_2 = 1;
iLocal_3 = 134;
iLocal_4 = 134;
iLocal_5 = 1;
iLocal_6 = 1;
iLocal_7 = 1;
iLocal_8 = 134;
iLocal_9 = 1;
iLocal_10 = 12;
iLocal_11 = 12;
fLocal_14 = 0.001f;
iLocal_17 = -1;
sLocal_19 = "NULL";
fLocal_22 = 0f;
fLocal_26 = -0.0375f;
fLocal_27 = 0.17f;
iLocal_29 = 3;
fLocal_32 = 80f;
fLocal_33 = 140f;
fLocal_34 = 180f;
iLocal_40 = 1;
iLocal_41 = 65;
iLocal_42 = 49;
iLocal_43 = 64;
iLocal_60 = -1;
iLocal_61 = -1;
fLocal_70 = 0f;
iLocal_71 = 1;
if (Global_76833)
{
SCRIPT::TERMINATE_THIS_THREAD();
}
MISC::NETWORK_SET_SCRIPT_IS_SAFE_FOR_NETWORK_GAME();
iLocal_55 = func_78();
HUD::REQUEST_ADDITIONAL_TEXT("email", 1);
while (!HUD::HAS_ADDITIONAL_TEXT_LOADED(1))
{
SYSTEM::WAIT(0);
}
Global_22038 = 0;
Global_22039 = 0;
Global_19681.f_1 = 8;
Global_22039 = 1;
Global_42810 = 1;
if (Global_19663)
{
func_77(0);
func_76(1);
func_75(0);
}
SYSTEM::SETTIMERB(0);
Local_47 = { Global_19634[Global_19626 /*3*/] };
Local_50 = { Local_47 };
Local_50.x = (Local_50.x - 10f);
Local_50.f_1 = (Local_50.f_1 + 20f);
while (true)
{
SYSTEM::WAIT(0);
if (Global_19681.f_1 != 9)
{
if (Global_22039 && !Global_22038)
{
func_73();
}
else if (Global_22038)
{
func_68();
}
if (!iLocal_56)
{
iLocal_56 = 1;
}
else if (Global_19663)
{
if (!iLocal_57)
{
iLocal_57 = 1;
func_66(Global_19662, iLocal_55);
func_65(Global_19662, "SET_HEADER", "EM_INBOX", 0, 0, 0, 0);
func_64(Global_19662, "DISPLAY_VIEW", 8f, -1082130432, -1082130432, -1082130432, -1082130432);
}
else
{
if (Global_42811)
{
Global_42811 = 0;
iLocal_58 = 1;
}
if (iLocal_58)
{
SYSTEM::SETTIMERA(0);
SYSTEM::SETTIMERB(0);
if (iLocal_60 == -1)
{
if (iLocal_71)
{
iLocal_71 = 0;
fLocal_70 = 0f;
}
func_64(Global_19662, "SET_DATA_SLOT_EMPTY", 8f, -1082130432, -1082130432, -1082130432, -1082130432);
iVar0 = func_66(Global_19662, iLocal_55);
func_65(Global_19662, "SET_HEADER", "EM_INBOX", 0, 0, 0, 0);
iLocal_59 = 0;
if (iVar0 > 0)
{
func_77(1);
}
else
{
func_77(0);
}
func_76(1);
func_75(0);
func_64(Global_19662, "DISPLAY_VIEW", 8f, fLocal_70, -1082130432, -1082130432, -1082130432);
}
else
{
func_64(Global_19662, "SET_DATA_SLOT_EMPTY", 21f, -1082130432, -1082130432, -1082130432, -1082130432);
SYSTEM::WAIT(0);
func_64(Global_19662, "DISPLAY_VIEW", 21f, -1082130432, -1082130432, -1082130432, -1082130432);
SYSTEM::WAIT(0);
func_76(1);
func_63();
if (iLocal_61 == -1)
{
func_61(iLocal_55, iLocal_60);
func_56(Global_19662, iLocal_55, iLocal_60);
Global_22065 = 0;
iLocal_68 = func_54(iLocal_55, iLocal_60);
if (iLocal_68)
{
sLocal_69 = func_51(iLocal_55, iLocal_60);
if (!func_50(37))
{
switch (func_48("AM_H_FLINK"))
{
case 2:
func_45("AM_H_FLINK", 2, 0, 1000, 10000, 7, 0, 0, 0);
break;
case 1:
func_44(37);
break;
}
}
else if (MISC::IS_PC_VERSION())
{
if (!MISC::IS_BIT_SET(Global_4271024, 17))
{
MISC::SET_BIT(&Global_4271024, 17);
func_43("AM_H_FLINK", -1);
}
}
func_75(1);
}
else
{
if (!func_50(38))
{
switch (func_48("AM_H_SCROLL"))
{
case 2:
func_45("AM_H_SCROLL", 2, 0, 1000, 10000, 7, 0, 0, 0);
break;
case 1:
func_44(38);
break;
}
}
func_75(0);
}
func_64(Global_19662, "DISPLAY_VIEW", 9f, -1082130432, -1082130432, -1082130432, -1082130432);
}
else
{
func_64(Global_19662, "SET_DATA_SLOT_EMPTY", 21f, -1082130432, -1082130432, -1082130432, -1082130432);
SYSTEM::WAIT(0);
func_64(Global_19662, "DISPLAY_VIEW", 21f, -1082130432, -1082130432, -1082130432, -1082130432);
SYSTEM::WAIT(0);
func_64(Global_19662, "SET_DATA_SLOT_EMPTY", 9f, -1082130432, -1082130432, -1082130432, -1082130432);
func_40(Global_19662, iLocal_55, iLocal_60);
func_64(Global_19662, "DISPLAY_VIEW", 9f, -1082130432, -1082130432, -1082130432, -1082130432);
}
}
iLocal_58 = 0;
}
else
{
func_17();
}
}
}
if (!iLocal_55 == func_78())
{
Global_42810 = 0;
func_4();
}
}
if (func_3())
{
Global_22038 = 0;
Global_22039 = 0;
Global_42810 = 0;
func_1(0);
SCRIPT::TERMINATE_THIS_THREAD();
}
}
}
void func_1(int iParam0)
{
if (func_2())
{
if (iParam0 == 1)
{
MOBILE::_CELL_CAM_SET_LEAN(true);
}
else if (Global_19681.f_1 > 3)
{
MOBILE::_CELL_CAM_SET_LEAN(false);
}
}
}
int func_2()
{
int iVar0;
int iVar1;
int iVar2;
if (Global_76833)
{
return 0;
}
iVar2 = 0;
iVar0 = CAM::_0x19CAFA3C87F7C2FF();
iVar1 = CAM::_0xEE778F8C7E1142E2(iVar0);
if (iVar1 == 4)
{
iVar2 = 1;
}
if (Global_4271302 || iVar2)
{
return 1;
}
return 1;
}
int func_3()
{
if (((Global_19681.f_1 == 1 || Global_19681.f_1 == 3) || Global_19681.f_1 == 0) || Global_19625 == 1)
{
Global_19668 = 1;
return 1;
}
return 0;
}
void func_4()
{
if (Global_52119 != -1)
{
GRAPHICS::SET_STREAMED_TEXTURE_DICT_AS_NO_LONGER_NEEDED(func_16(Global_52119));
Global_52119 = -1;
}
Global_42810 = 0;
if (Global_19681.f_1 > 4)
{
Global_19681.f_1 = 6;
func_5();
}
SCRIPT::TERMINATE_THIS_THREAD();
}
void func_5()
{
char cVar0[24];
if (Global_19664 == 1)
{
return;
}
if (Global_19681.f_1 < 4)
{
return;
}
while (!GRAPHICS::HAS_SCALEFORM_MOVIE_LOADED(Global_19662))
{
if (Global_76833)
{
return;
}
SYSTEM::WAIT(0);
}
switch (Global_19681.f_1)
{
case 6:
func_64(Global_19662, "SET_DATA_SLOT_EMPTY", 1f, -1082130432, -1082130432, -1082130432, -1082130432);
func_14(Global_8156);
if (Global_8156 == 1)
{
func_64(Global_19662, "DISPLAY_VIEW", 1f, SYSTEM::TO_FLOAT(Global_19685), -1082130432, -1082130432, -1082130432);
Global_19661 = Global_19685;
}
else
{
func_64(Global_19662, "DISPLAY_VIEW", 1f, SYSTEM::TO_FLOAT(Global_19686), -1082130432, -1082130432, -1082130432);
Global_19661 = Global_19686;
}
if (Global_19669)
{
func_13(Global_19662, "SET_SOFT_KEYS", 2f, 1f, 2f, -1f, -1f, "CELL_205", 0, 0, 0, 0);
func_13(Global_19662, "SET_SOFT_KEYS", 3f, 1f, 4f, -1f, -1f, "CELL_206", 0, 0, 0, 0);
}
else
{
func_13(Global_19662, "SET_SOFT_KEYS", 2f, 1f, 2f, -1f, -1f, 0, 0, 0, 0, 0);
func_13(Global_19662, "SET_SOFT_KEYS", 3f, 1f, 4f, -1f, -1f, 0, 0, 0, 0, 0);
}
if (Global_19866 == 0)
{
func_13(Global_19662, "SET_SOFT_KEYS", 1f, 0f, 1f, -1f, -1f, 0, 0, 0, 0, 0);
MISC::CLEAR_BIT(&Global_7551, 17);
}
else if (Global_76833)
{
func_13(Global_19662, "SET_SOFT_KEYS", 1f, 0f, 1f, -1f, -1f, 0, 0, 0, 0, 0);
MISC::CLEAR_BIT(&Global_7551, 17);
}
else
{
if (Global_19865 == 1)
{
if (Global_19669)
{
func_13(Global_19662, "SET_SOFT_KEYS", 1f, 1f, 20f, -1f, -1f, "CELL_225", 0, 0, 0, 0);
}
else
{
func_13(Global_19662, "SET_SOFT_KEYS", 1f, 1f, 20f, -1f, -1f, 0, 0, 0, 0, 0);
}
}
else if (Global_19669)
{
func_13(Global_19662, "SET_SOFT_KEYS", 1f, 1f, 3f, -1f, -1f, "CELL_225", 0, 0, 0, 0);
}
else
{
func_13(Global_19662, "SET_SOFT_KEYS", 1f, 1f, 3f, -1f, -1f, 0, 0, 0, 0, 0);
}
MISC::SET_BIT(&Global_7551, 17);
}
if (Global_76833)
{
func_11();
MISC::CLEAR_BIT(&Global_7553, 9);
func_64(Global_19662, "DISPLAY_VIEW", 1f, SYSTEM::TO_FLOAT(Global_19685), -1082130432, -1082130432, -1082130432);
}
break;
case 7:
break;
case 10:
func_64(Global_19662, "DISPLAY_VIEW", 4f, -1082130432, -1082130432, -1082130432, -1082130432);
func_13(Global_19662, "SET_SOFT_KEYS", 2f, 0f, 1f, -1f, -1f, 0, 0, 0, 0, 0);
func_13(Global_19662, "SET_SOFT_KEYS", 1f, 0f, 1f, -1f, -1f, 0, 0, 0, 0, 0);
MISC::CLEAR_BIT(&Global_7551, 17);
if (MISC::IS_BIT_SET(Global_7551, 20))
{
func_13(Global_19662, "SET_SOFT_KEYS", 3f, 0f, 1f, -1f, -1f, 0, 0, 0, 0, 0);
}
else if (Global_19669)
{
func_13(Global_19662, "SET_SOFT_KEYS", 3f, 1f, 6f, -1f, -1f, "CELL_202", 0, 0, 0, 0);
if (Global_19624)
{
func_13(Global_19662, "SET_SOFT_KEYS", 3f, 1f, 6f, -1f, -1f, 0, 0, 0, 0, 0);
}
}
else
{
func_13(Global_19662, "SET_SOFT_KEYS", 3f, 1f, 6f, -1f, -1f, 0, 0, 0, 0, 0);
}
break;
case 9:
if (Global_19680 == 1)
{
func_10();
func_64(Global_19662, "SET_THEME", SYSTEM::TO_FLOAT(Global_111858.f_14047[Global_19681 /*20*/].f_6), -1082130432, -1082130432, -1082130432, -1082130432);
if (Global_21018)
{
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(Global_19662, "SET_DATA_SLOT");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(4);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(0);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(2);
GRAPHICS::BEGIN_TEXT_COMMAND_SCALEFORM_STRING("CELL_CONDFON");
HUD::ADD_TEXT_COMPONENT_SUBSTRING_PLAYER_NAME(&Global_21020);
GRAPHICS::END_TEXT_COMMAND_SCALEFORM_STRING();
func_9("CELL_300");
func_9("CELL_217");
func_9("CELL_217");
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
}
else if (func_8(Global_6866, Global_19681) == 0)
{
func_13(Global_19662, "SET_DATA_SLOT", SYSTEM::TO_FLOAT(4), SYSTEM::TO_FLOAT(0), SYSTEM::TO_FLOAT(2), -1f, -1f, &(Global_117[Global_6866 /*10*/].f_4), "CELL_300", "CELL_217", "CELL_195", 0);
}
else
{
func_13(Global_19662, "SET_DATA_SLOT", SYSTEM::TO_FLOAT(4), SYSTEM::TO_FLOAT(0), SYSTEM::TO_FLOAT(2), -1f, -1f, &(Global_1848[Global_6866 /*29*/].f_3), &(Global_1848[Global_6866 /*29*/].f_7), "CELL_217", &(Global_1848[Global_6866 /*29*/].f_3), 0);
}
func_64(Global_19662, "DISPLAY_VIEW", 4f, -1082130432, -1082130432, -1082130432, -1082130432);
}
else if (Global_21005 == 4 || Global_21005 == 3)
{
func_64(Global_19662, "SET_THEME", SYSTEM::TO_FLOAT(Global_111858.f_14047[Global_19681 /*20*/].f_6), -1082130432, -1082130432, -1082130432, -1082130432);
func_10();
if (Global_21018)
{
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(Global_19662, "SET_DATA_SLOT");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(4);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(0);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(2);
GRAPHICS::BEGIN_TEXT_COMMAND_SCALEFORM_STRING("CELL_CONDFON");
HUD::ADD_TEXT_COMPONENT_SUBSTRING_PLAYER_NAME(&Global_21020);
GRAPHICS::END_TEXT_COMMAND_SCALEFORM_STRING();
func_9("CELL_300");
func_9("CELL_219");
func_9("CELL_219");
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
}
else
{
if (Global_21263)
{
StringCopy(&cVar0, "CELL_219", 24);
}
else
{
StringCopy(&cVar0, "CELL_211", 24);
}
if (func_8(Global_6866, Global_19681) == 0)
{
func_64(Global_19662, "SET_DATA_SLOT_EMPTY", 4f, -1082130432, -1082130432, -1082130432, -1082130432);
func_13(Global_19662, "SET_DATA_SLOT", SYSTEM::TO_FLOAT(4), SYSTEM::TO_FLOAT(0), SYSTEM::TO_FLOAT(3), -1f, -1f, &(Global_117[Global_6866 /*10*/].f_4), "CELL_300", &cVar0, "CELL_195", 0);
}
else
{
func_64(Global_19662, "SET_DATA_SLOT_EMPTY", 4f, -1082130432, -1082130432, -1082130432, -1082130432);
func_13(Global_19662, "SET_DATA_SLOT", SYSTEM::TO_FLOAT(4), SYSTEM::TO_FLOAT(0), SYSTEM::TO_FLOAT(3), -1f, -1f, &(Global_1848[Global_6866 /*29*/].f_3), &(Global_1848[Global_6866 /*29*/].f_7), &cVar0, &(Global_1848[Global_6866 /*29*/].f_3), 0);
}
}
func_64(Global_19662, "DISPLAY_VIEW", 4f, -1082130432, -1082130432, -1082130432, -1082130432);
}
func_6();
break;
default:
break;
}
}
void func_6()
{
if (GRAPHICS::HAS_SCALEFORM_MOVIE_LOADED(Global_19662))
{
func_7();
if (Global_19680 == 1)
{
if (Global_19669)
{
func_13(Global_19662, "SET_SOFT_KEYS", 2f, 1f, 5f, -1f, -1f, "CELL_203", 0, 0, 0, 0);
}
else
{
func_13(Global_19662, "SET_SOFT_KEYS", 2f, 1f, 5f, -1f, -1f, 0, 0, 0, 0, 0);
}
if (Global_21052)
{
func_13(Global_19662, "SET_SOFT_KEYS", 3f, 0f, 6f, -1f, -1f, 0, 0, 0, 0, 0);
}
else if (MISC::IS_BIT_SET(Global_7551, 20))
{
func_13(Global_19662, "SET_SOFT_KEYS", 3f, 0f, 1f, -1f, -1f, 0, 0, 0, 0, 0);
}
else if (Global_19669)
{
func_13(Global_19662, "SET_SOFT_KEYS", 3f, 1f, 6f, -1f, -1f, "CELL_204", 0, 0, 0, 0);
}
else
{
func_13(Global_19662, "SET_SOFT_KEYS", 3f, 1f, 6f, -1f, -1f, 0, 0, 0, 0, 0);
}
func_13(Global_19662, "SET_SOFT_KEYS", 1f, 0f, 1f, -1f, -1f, 0, 0, 0, 0, 0);
MISC::CLEAR_BIT(&Global_7551, 17);
}
else
{
func_13(Global_19662, "SET_SOFT_KEYS", 2f, 0f, 1f, -1f, -1f, 0, 0, 0, 0, 0);
func_13(Global_19662, "SET_SOFT_KEYS", 1f, 0f, 1f, -1f, -1f, 0, 0, 0, 0, 0);
MISC::CLEAR_BIT(&Global_7551, 17);
if (MISC::IS_BIT_SET(Global_7551, 20))
{
func_13(Global_19662, "SET_SOFT_KEYS", 3f, 0f, 1f, -1f, -1f, 0, 0, 0, 0, 0);
}
else if (Global_19669)
{
func_13(Global_19662, "SET_SOFT_KEYS", 3f, 1f, 6f, -1f, -1f, "CELL_202", 0, 0, 0, 0);
if (Global_19624)
{
func_13(Global_19662, "SET_SOFT_KEYS", 3f, 1f, 6f, -1f, -1f, 0, 0, 0, 0, 0);
}
}
else
{
func_13(Global_19662, "SET_SOFT_KEYS", 3f, 1f, 6f, -1f, -1f, 0, 0, 0, 0, 0);
}
}
}
}
void func_7()
{
if (Global_76833)
{
func_13(Global_19662, "SET_SOFT_KEYS", 1f, 0f, 9f, -1f, -1f, 0, 0, 0, 0, 0);
MISC::CLEAR_BIT(&Global_7551, 17);
}
}
int func_8(int iParam0, int iParam1)
{
if (iParam1 < 0 || iParam1 > 4)
{
return 0;
}
return Global_1848[iParam0 /*29*/].f_24[iParam1];
}
void func_9(char* sParam0)
{
GRAPHICS::BEGIN_TEXT_COMMAND_SCALEFORM_STRING(sParam0);
GRAPHICS::END_TEXT_COMMAND_SCALEFORM_STRING();
}
void func_10()
{
if (!ENTITY::IS_ENTITY_DEAD(PLAYER::PLAYER_PED_ID(), false))
{
if (Global_19681 == 0)
{
switch (Global_111858.f_14047[Global_19681 /*20*/].f_6)
{
case 1:
PLAYER::SET_PLAYER_RESET_FLAG_PREFER_REAR_SEATS(PLAYER::PLAYER_ID(), 0);
break;
case 2:
PLAYER::SET_PLAYER_RESET_FLAG_PREFER_REAR_SEATS(PLAYER::PLAYER_ID(), 1);
break;
case 3:
PLAYER::SET_PLAYER_RESET_FLAG_PREFER_REAR_SEATS(PLAYER::PLAYER_ID(), 2);
break;
case 4:
PLAYER::SET_PLAYER_RESET_FLAG_PREFER_REAR_SEATS(PLAYER::PLAYER_ID(), 3);
break;
case 5:
PLAYER::SET_PLAYER_RESET_FLAG_PREFER_REAR_SEATS(PLAYER::PLAYER_ID(), 4);
break;
case 6:
PLAYER::SET_PLAYER_RESET_FLAG_PREFER_REAR_SEATS(PLAYER::PLAYER_ID(), 5);
break;
case 7:
PLAYER::SET_PLAYER_RESET_FLAG_PREFER_REAR_SEATS(PLAYER::PLAYER_ID(), 6);
break;
default:
break;
}
}
if (Global_19681 == 1)
{
switch (Global_111858.f_14047[Global_19681 /*20*/].f_6)
{
case 1:
PLAYER::SET_PLAYER_RESET_FLAG_PREFER_REAR_SEATS(PLAYER::PLAYER_ID(), 6);
break;
case 2:
PLAYER::SET_PLAYER_RESET_FLAG_PREFER_REAR_SEATS(PLAYER::PLAYER_ID(), 0);
break;
case 3:
PLAYER::SET_PLAYER_RESET_FLAG_PREFER_REAR_SEATS(PLAYER::PLAYER_ID(), 1);
break;
case 4:
PLAYER::SET_PLAYER_RESET_FLAG_PREFER_REAR_SEATS(PLAYER::PLAYER_ID(), 2);
break;
case 5:
PLAYER::SET_PLAYER_RESET_FLAG_PREFER_REAR_SEATS(PLAYER::PLAYER_ID(), 3);
break;
case 6:
PLAYER::SET_PLAYER_RESET_FLAG_PREFER_REAR_SEATS(PLAYER::PLAYER_ID(), 4);
break;
case 7:
PLAYER::SET_PLAYER_RESET_FLAG_PREFER_REAR_SEATS(PLAYER::PLAYER_ID(), 5);
break;
default:
break;
}
}
if (Global_19681 == 2)
{
switch (Global_111858.f_14047[Global_19681 /*20*/].f_6)
{
case 1:
PLAYER::SET_PLAYER_RESET_FLAG_PREFER_REAR_SEATS(PLAYER::PLAYER_ID(), 5);
break;
case 2:
PLAYER::SET_PLAYER_RESET_FLAG_PREFER_REAR_SEATS(PLAYER::PLAYER_ID(), 6);
break;
case 3:
PLAYER::SET_PLAYER_RESET_FLAG_PREFER_REAR_SEATS(PLAYER::PLAYER_ID(), 1);
break;
case 4:
PLAYER::SET_PLAYER_RESET_FLAG_PREFER_REAR_SEATS(PLAYER::PLAYER_ID(), 0);
break;
case 5:
PLAYER::SET_PLAYER_RESET_FLAG_PREFER_REAR_SEATS(PLAYER::PLAYER_ID(), 2);
break;
case 6:
PLAYER::SET_PLAYER_RESET_FLAG_PREFER_REAR_SEATS(PLAYER::PLAYER_ID(), 3);
break;
case 7:
PLAYER::SET_PLAYER_RESET_FLAG_PREFER_REAR_SEATS(PLAYER::PLAYER_ID(), 4);
break;
default:
break;
}
}
if (Global_19681 == 3)
{
switch (Global_4271300)
{
case 1:
PLAYER::SET_PLAYER_RESET_FLAG_PREFER_REAR_SEATS(PLAYER::PLAYER_ID(), 0);
break;
case 2:
PLAYER::SET_PLAYER_RESET_FLAG_PREFER_REAR_SEATS(PLAYER::PLAYER_ID(), 1);
break;
case 3:
PLAYER::SET_PLAYER_RESET_FLAG_PREFER_REAR_SEATS(PLAYER::PLAYER_ID(), 2);
break;
case 4:
PLAYER::SET_PLAYER_RESET_FLAG_PREFER_REAR_SEATS(PLAYER::PLAYER_ID(), 3);
break;
case 5:
PLAYER::SET_PLAYER_RESET_FLAG_PREFER_REAR_SEATS(PLAYER::PLAYER_ID(), 4);
break;
case 6:
PLAYER::SET_PLAYER_RESET_FLAG_PREFER_REAR_SEATS(PLAYER::PLAYER_ID(), 5);
break;
case 7:
PLAYER::SET_PLAYER_RESET_FLAG_PREFER_REAR_SEATS(PLAYER::PLAYER_ID(), 6);
break;
default:
break;
}
}
}
}
void func_11()
{
if (Global_76833)
{
if (func_12() == 0)
{
return;
}
func_13(Global_19662, "SET_SOFT_KEYS", 1f, 1f, 9f, -1f, -1f, 0, 0, 0, 0, 0);
MISC::SET_BIT(&Global_7551, 17);
}
}
int func_12()
{
return 0;
}
void func_13(int iParam0, char* sParam1, float fParam2, float fParam3, float fParam4, float fParam5, float fParam6, char* sParam7, char* sParam8, char* sParam9, char* sParam10, char* sParam11)
{
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(iParam0, sParam1);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(SYSTEM::ROUND(fParam2));
if (fParam3 != -1f)
{
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(SYSTEM::ROUND(fParam3));
}
if (fParam4 != -1f)
{
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(SYSTEM::ROUND(fParam4));
}
if (fParam5 != -1f)
{
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(SYSTEM::ROUND(fParam5));
}
if (fParam6 != -1f)
{
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(SYSTEM::ROUND(fParam6));
}
if (!MISC::IS_STRING_NULL_OR_EMPTY(sParam7))
{
func_9(sParam7);
}
if (!MISC::IS_STRING_NULL_OR_EMPTY(sParam8))
{
func_9(sParam8);
}
if (!MISC::IS_STRING_NULL_OR_EMPTY(sParam9))
{
func_9(sParam9);
}
if (!MISC::IS_STRING_NULL_OR_EMPTY(sParam10))
{
func_9(sParam10);
}
if (!MISC::IS_STRING_NULL_OR_EMPTY(sParam11))
{
func_9(sParam11);
}
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
}
void func_14(int iParam0)
{
int iVar0;
int iVar1;
int iVar2;
int iVar3;
int iVar4;
int iVar5;
int iVar6;
int iVar7;
int iVar8;
int iVar9;
Global_22073 = 0;
Global_8156 = iParam0;
iVar0 = 0;
while (iVar0 < 9)
{
Global_8120[iVar0] = 0;
iVar0++;
}
iVar0 = 0;
while (iVar0 < 9)
{
iVar1 = 0;
if (func_15(14))
{
while (iVar1 < 34)
{
if (iParam0 == Global_7558[iVar1 /*15*/].f_11)
{
if (iVar0 == Global_7558[iVar1 /*15*/].f_4)
{
if (Global_8120[iVar0] == 0)
{
Global_8084[iVar0] = iVar1;
if (iVar1 == 3)
{
if (MISC::IS_BIT_SET(Global_7552, 3))
{
iVar2 = 42;
Global_19868 = 1;
}
else
{
iVar2 = 255;
Global_19868 = 0;
}
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(Global_19662, "SET_DATA_SLOT");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(1);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(iVar0);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(Global_7558[iVar1 /*15*/].f_10);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(0);
func_9(&(Global_7558[iVar1 /*15*/]));
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(iVar2);
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
}
if (Global_2462245)
{
if (iVar1 == 14)
{
func_13(Global_19662, "SET_DATA_SLOT", SYSTEM::TO_FLOAT(1), SYSTEM::TO_FLOAT(iVar0), SYSTEM::TO_FLOAT(Global_7558[iVar1 /*15*/].f_10), SYSTEM::TO_FLOAT(Global_22068), -1f, &(Global_7558[iVar1 /*15*/]), 0, 0, 0, 0);
}
}
Global_8120[iVar0] = 1;
}
}
}
iVar1++;
}
}
else
{
while (iVar1 < 34)
{
if (iParam0 == Global_7558[iVar1 /*15*/].f_11)
{
if (iVar0 == Global_7558[iVar1 /*15*/].f_4)
{
if (Global_8120[iVar0] == 0)
{
Global_8084[iVar0] = iVar1;
if (iVar1 == 1)
{
iVar3 = 0;
while (iVar3 < 35)
{
if (Global_111858.f_14137[iVar3 /*104*/].f_24 != 0)
{
if (Global_111858.f_14137[iVar3 /*104*/].f_28 == 0)
{
if (Global_111858.f_14137[iVar3 /*104*/].f_99[Global_19681] == 1)
{
Global_22073++;
}
}
}
iVar3++;
}
func_13(Global_19662, "SET_DATA_SLOT", SYSTEM::TO_FLOAT(1), SYSTEM::TO_FLOAT(iVar0), SYSTEM::TO_FLOAT(Global_7558[iVar1 /*15*/].f_10), SYSTEM::TO_FLOAT(Global_22073), -1f, &(Global_7558[iVar1 /*15*/]), 0, 0, 0, 0);
}
else if (iVar1 == 7)
{
if (Global_76833)
{
iVar4 = 0;
iVar4 = Global_4269758;
iVar5 = 0;
while (iVar5 < 12)
{
if (Global_4269759[iVar5 /*104*/].f_24 != 0)
{
if (Global_4269759[iVar5 /*104*/].f_28 == 0)
{
if (Global_4269759[iVar5 /*104*/].f_99[Global_19681] == 1)
{
iVar4++;
}
}
}
iVar5++;
}
func_13(Global_19662, "SET_DATA_SLOT", SYSTEM::TO_FLOAT(1), SYSTEM::TO_FLOAT(iVar0), SYSTEM::TO_FLOAT(Global_7558[iVar1 /*15*/].f_10), SYSTEM::TO_FLOAT(iVar4), -1f, &(Global_7558[iVar1 /*15*/]), 0, 0, 0, 0);
}
else
{
switch (Global_19681)
{
case 0:
iVar6 = Global_42812;
break;
case 1:
iVar6 = Global_42813;
break;
case 2:
iVar6 = Global_42814;
break;
default:
break;
}
func_13(Global_19662, "SET_DATA_SLOT", SYSTEM::TO_FLOAT(1), SYSTEM::TO_FLOAT(iVar0), SYSTEM::TO_FLOAT(Global_7558[iVar1 /*15*/].f_10), SYSTEM::TO_FLOAT(iVar6), -1f, &(Global_7558[iVar1 /*15*/]), 0, 0, 0, 0);
}
}
else if (iVar1 == 14)
{
func_13(Global_19662, "SET_DATA_SLOT", SYSTEM::TO_FLOAT(1), SYSTEM::TO_FLOAT(iVar0), SYSTEM::TO_FLOAT(Global_7558[iVar1 /*15*/].f_10), SYSTEM::TO_FLOAT(Global_22068), -1f, &(Global_7558[iVar1 /*15*/]), 0, 0, 0, 0);
}
else if (iVar1 == 20)
{
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(Global_19662, "SET_DATA_SLOT");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(1);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(iVar0);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(Global_7558[iVar1 /*15*/].f_10);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(0);
func_9(&(Global_7558[iVar1 /*15*/]));
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(Global_7557);
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
}
else if (iVar1 == 2)
{
if (MISC::IS_BIT_SET(Global_7552, 6))
{
iVar7 = 42;
}
else
{
iVar7 = 255;
}
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(Global_19662, "SET_DATA_SLOT");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(1);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(iVar0);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(Global_7558[iVar1 /*15*/].f_10);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(0);
func_9(&(Global_7558[iVar1 /*15*/]));
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(iVar7);
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
}
else if (iVar1 == 3)
{
if (MISC::IS_BIT_SET(Global_7552, 3))
{
iVar8 = 42;
Global_19868 = 1;
}
else
{
iVar8 = 255;
Global_19868 = 0;
}
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(Global_19662, "SET_DATA_SLOT");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(1);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(iVar0);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(Global_7558[iVar1 /*15*/].f_10);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(0);
func_9(&(Global_7558[iVar1 /*15*/]));
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(iVar8);
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
}
else if (iVar1 == 8)
{
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(Global_19662, "SET_DATA_SLOT");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(1);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(iVar0);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(Global_7558[iVar1 /*15*/].f_10);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(0);
func_9(&(Global_7558[iVar1 /*15*/]));
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(42);
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
}
else if ((iVar1 == 23 && MISC::ARE_STRINGS_EQUAL(&(Global_7558[iVar1 /*15*/]), "CELL_BENWEB")) && MISC::IS_BIT_SET(Global_7552, 6))
{
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(Global_19662, "SET_DATA_SLOT");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(1);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(iVar0);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(Global_7558[iVar1 /*15*/].f_10);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(0);
func_9(&(Global_7558[iVar1 /*15*/]));
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(42);
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
}
else if (Global_7558[iVar1 /*15*/].f_10 == 57 && iVar1 == 23)
{
iVar9 = 0;
iVar9 = Global_1627252.f_1;
func_13(Global_19662, "SET_DATA_SLOT", SYSTEM::TO_FLOAT(1), SYSTEM::TO_FLOAT(iVar0), SYSTEM::TO_FLOAT(Global_7558[iVar1 /*15*/].f_10), SYSTEM::TO_FLOAT(iVar9), -1f, &(Global_7558[iVar1 /*15*/]), 0, 0, 0, 0);
}
else
{
func_13(Global_19662, "SET_DATA_SLOT", SYSTEM::TO_FLOAT(1), SYSTEM::TO_FLOAT(iVar0), SYSTEM::TO_FLOAT(Global_7558[iVar1 /*15*/].f_10), SYSTEM::TO_FLOAT(0), -1f, &(Global_7558[iVar1 /*15*/]), 0, 0, 0, 0);
}
Global_8120[iVar0] = 1;
}
}
}
iVar1++;
}
}
iVar0++;
}
}
bool func_15(int iParam0)
{
return Global_41631 == iParam0;
}
char* func_16(int iParam0)
{
switch (iParam0)
{
case 0:
return "Epsilon_Cars";
case 1:
return "Epsilon_Cars";
case 2:
return "Epsilon_Cars";
case 3:
return "Epsilon_Cars";
case 4:
return "Epsilon_Cars";
case 5:
return "Epsilon_Cars";
case 6:
return "Epsilon_Cars";
case 12:
return "Assassinations";
case 13:
return "Assassinations";
case 14:
return "Assassinations";
case 15:
return "Assassinations";
case 64:
return "BSPBadHacker";
case 65:
return "BPDGoodHacker";
case 66:
return "BPSMedHacker";
case 75:
return "email_quarry_bail_bond";
case 76:
return "email_abandonedfarm_bail_bond";
case 77:
return "email_mountain_bail_bond";
case 78:
return "email_hobocamp_bail_bond";
case 80:
return "email_quarry_bail_bond";
case 81:
return "email_abandonedfarm_bail_bond";
case 82:
return "email_mountain_bail_bond";
case 83:
return "email_hobocamp_bail_bond";
case 205:
return "hush_foxymama21";
case 209:
return "hush_alterego";
case 212:
return "hush_michael";
case 238:
return "hush_trevor";
default:
}
return "NULL";
}
void func_17()
{
bool bVar0;
if (Global_22065)
{
iLocal_60 = 0;
fLocal_70 = SYSTEM::TO_FLOAT(iLocal_60);
if (func_39(iLocal_55) == 0)
{
iLocal_60 = -1;
}
if (!iLocal_60 == -1)
{
Global_19681.f_1 = 8;
iLocal_58 = 1;
SYSTEM::SETTIMERB(0);
func_37();
}
return;
}
if (func_36())
{
return;
}
if (Global_22038)
{
return;
}
if (!iLocal_64)
{
if (PAD::IS_CONTROL_JUST_PRESSED(2, 172) || PAD::IS_CONTROL_JUST_PRESSED(2, 181))
{
iLocal_64 = 1;
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(Global_19662, "SET_INPUT_EVENT");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(1);
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
AUDIO::PLAY_SOUND_FRONTEND(-1, "Menu_Navigate", &Global_19670, true);
SYSTEM::SETTIMERA(0);
iLocal_71 = 1;
}
}
else if (PAD::IS_CONTROL_PRESSED(2, 172) || PAD::IS_CONTROL_PRESSED(2, 181))
{
if (SYSTEM::TIMERA() > 100 && iLocal_60 != -1)
{
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(Global_19662, "SET_INPUT_EVENT");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(1);
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
SYSTEM::SETTIMERA(0);
iLocal_71 = 1;
}
}
else
{
iLocal_64 = 0;
}
if (!iLocal_65)
{
if (PAD::IS_CONTROL_JUST_PRESSED(2, 173) || PAD::IS_CONTROL_JUST_PRESSED(2, 180))
{
iLocal_65 = 1;
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(Global_19662, "SET_INPUT_EVENT");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(3);
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
AUDIO::PLAY_SOUND_FRONTEND(-1, "Menu_Navigate", &Global_19670, true);
SYSTEM::SETTIMERB(0);
iLocal_71 = 1;
}
}
else if (PAD::IS_CONTROL_PRESSED(2, 173) || PAD::IS_CONTROL_PRESSED(2, 180))
{
if (SYSTEM::TIMERB() > 100 && iLocal_60 != -1)
{
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(Global_19662, "SET_INPUT_EVENT");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(3);
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
SYSTEM::SETTIMERB(0);
iLocal_71 = 1;
}
}
else
{
iLocal_65 = 0;
}
if (!iLocal_66)
{
if (PAD::IS_CONTROL_PRESSED(2, 174))
{
iLocal_66 = 1;
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(Global_19662, "SET_INPUT_EVENT");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(4);
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
AUDIO::PLAY_SOUND_FRONTEND(-1, "Menu_Navigate", &Global_19670, true);
}
}
else if (!PAD::IS_CONTROL_PRESSED(2, 174))
{
iLocal_66 = 0;
}
if (!iLocal_67)
{
if (PAD::IS_CONTROL_PRESSED(2, 175))
{
iLocal_67 = 1;
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(Global_19662, "SET_INPUT_EVENT");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(2);
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
AUDIO::PLAY_SOUND_FRONTEND(-1, "Menu_Navigate", &Global_19670, true);
}
}
else if (!PAD::IS_CONTROL_PRESSED(2, 175))
{
iLocal_67 = 0;
}
if (!iLocal_63)
{
if (PAD::IS_CONTROL_PRESSED(2, 176) && SYSTEM::TIMERB() > 100)
{
if (iLocal_60 == -1)
{
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(Global_19662, "GET_CURRENT_SELECTION");
iLocal_53 = GRAPHICS::END_SCALEFORM_MOVIE_METHOD_RETURN_VALUE();
while (!GRAPHICS::IS_SCALEFORM_MOVIE_METHOD_RETURN_VALUE_READY(iLocal_53))
{
SYSTEM::WAIT(0);
}
iLocal_54 = GRAPHICS::GET_SCALEFORM_MOVIE_METHOD_RETURN_VALUE_INT(iLocal_53);
iLocal_60 = iLocal_54;
if (func_39(iLocal_55) == 0)
{
iLocal_60 = -1;
}
if (!iLocal_60 == -1)
{
if (iLocal_71 == 1)
{
fLocal_70 = SYSTEM::TO_FLOAT(iLocal_60);
iLocal_71 = 0;
}
Global_19681.f_1 = 8;
iLocal_58 = 1;
SYSTEM::SETTIMERB(0);
func_37();
}
}
else if (iLocal_61 == -1)
{
if (func_34(iLocal_55, iLocal_60) && !iLocal_59)
{
iLocal_61 = 0;
iLocal_58 = 1;
SYSTEM::SETTIMERB(0);
func_37();
}
}
else
{
iLocal_61 = 0;
func_22(iLocal_55, iLocal_60, iLocal_61);
iLocal_59 = 1;
iLocal_61 = -1;
iLocal_58 = 1;
func_37();
SYSTEM::SETTIMERB(0);
}
iLocal_63 = 1;
}
}
else
{
iLocal_63 = 0;
}
if (SYSTEM::TIMERB() > 100)
{
if (PAD::IS_CONTROL_PRESSED(2, 177))
{
bVar0 = false;
if (iLocal_62 == 0)
{
if (!iLocal_60 == -1)
{
if (iLocal_61 == -1)
{
iLocal_60 = SYSTEM::ROUND(fLocal_70);
iLocal_68 = 0;
SYSTEM::SETTIMERB(0);
bVar0 = true;
func_21();
}
else
{
SYSTEM::SETTIMERB(0);
iLocal_61 = -1;
func_21();
}
iLocal_58 = 1;
}
else
{
if (func_48("AM_H_FLINK") == 0)
{
func_44(37);
}
if (func_48("AM_H_SCROLL") == 0)
{
func_44(38);
}
if (Global_22039 == 0 && !Global_22038)
{
func_21();
Global_22038 = 1;
Global_42810 = 0;
}
}
iLocal_62 = 1;
}
if (bVar0)
{
iLocal_60 = -1;
}
}
else
{
iLocal_62 = 0;
}
}
if (PAD::IS_CONTROL_PRESSED(2, 179))
{
if (iLocal_68)
{
if (func_48("AM_H_FLINK") == 0)
{
func_44(37);
}
if (func_48("AM_H_SCROLL") == 0)
{
func_44(38);
}
StringCopy(&Global_74014, sLocal_69, 64);
func_18(7, 0, 0);
iLocal_68 = 0;
func_37();
}
}
}
int func_18(int iParam0, bool bParam1, int iParam2)
{
bool bVar0;
bool bVar1;
bool bVar2;
Global_74143 = iParam0;
bVar0 = iParam2 == true;
bVar1 = iParam2 == 2;
bVar2 = iParam2 == 3;
switch (Global_74143)
{
case 3:
Global_74141 = 0;
break;
case 4:
Global_74141 = 3;
break;
}
if (SCRIPT::_GET_NUMBER_OF_REFERENCES_OF_SCRIPT_WITH_NAME_HASH(joaat("appsecuroserv")) > 0)
{
if (bVar0)
{
}
return 0;
}
if (SCRIPT::_GET_NUMBER_OF_REFERENCES_OF_SCRIPT_WITH_NAME_HASH(joaat("appbikerbusiness")) > 0)
{
if (bVar1)
{
}
return 0;
}
if (SCRIPT::_GET_NUMBER_OF_REFERENCES_OF_SCRIPT_WITH_NAME_HASH(joaat("appimportexport")) > 0)
{
if (bVar2)
{
}
return 0;
}
if (SCRIPT::_GET_NUMBER_OF_REFERENCES_OF_SCRIPT_WITH_NAME_HASH(joaat("appinternet")) > 0)
{
if ((bVar0 || bVar1) || bVar2)
{
}
return 0;
}
if (Global_76833 && func_20())
{
return 0;
}
if (!Global_76833 && func_19())
{
return 0;
}
if (bVar0)
{
if (!SCRIPT::HAS_SCRIPT_LOADED("appSecuroServ"))
{
SCRIPT::REQUEST_SCRIPT("appSecuroServ");
if (bParam1)
{
return 0;
}
}
while (!SCRIPT::HAS_SCRIPT_LOADED("appSecuroServ"))
{
SYSTEM::WAIT(0);
}
SYSTEM::START_NEW_SCRIPT("appSecuroServ", 4592);
SCRIPT::SET_SCRIPT_AS_NO_LONGER_NEEDED("appSecuroServ");
return 1;
}
if (bVar1)
{
if (!SCRIPT::HAS_SCRIPT_LOADED("appBikerBusiness"))
{
SCRIPT::REQUEST_SCRIPT("appBikerBusiness");
if (bParam1)
{
return 0;
}
}
while (!SCRIPT::HAS_SCRIPT_LOADED("appBikerBusiness"))
{
SYSTEM::WAIT(0);
}
SYSTEM::START_NEW_SCRIPT("appBikerBusiness", 4592);
SCRIPT::SET_SCRIPT_AS_NO_LONGER_NEEDED("appBikerBusiness");
return 1;
}
if (bVar2)
{
if (!SCRIPT::HAS_SCRIPT_LOADED("appImportExport"))
{
SCRIPT::REQUEST_SCRIPT("appImportExport");
if (bParam1)
{
return 0;
}
}
while (!SCRIPT::HAS_SCRIPT_LOADED("appImportExport"))
{
SYSTEM::WAIT(0);
}
SYSTEM::START_NEW_SCRIPT("appImportExport", 4592);
SCRIPT::SET_SCRIPT_AS_NO_LONGER_NEEDED("appImportExport");
return 1;
}
if (!SCRIPT::HAS_SCRIPT_LOADED("appInternet"))
{
SCRIPT::REQUEST_SCRIPT("appInternet");
if (bParam1)
{
return 0;
}
}
while (!SCRIPT::HAS_SCRIPT_LOADED("appInternet"))
{
SYSTEM::WAIT(0);
}
SYSTEM::START_NEW_SCRIPT("appInternet", 4592);
SCRIPT::SET_SCRIPT_AS_NO_LONGER_NEEDED("appInternet");
return 1;
}
var func_19()
{
return Global_74031;
}
var func_20()
{
return Global_1664241;
}
void func_21()
{
if (!ENTITY::IS_ENTITY_DEAD(PLAYER::PLAYER_PED_ID(), false))
{
AUDIO::PLAY_SOUND_FRONTEND(-1, "Menu_Back", &Global_19670, true);
}
}
void func_22(int iParam0, int iParam1, int iParam2)
{
int iVar0;
int iVar1;
int iVar2;
int iVar3;
int iVar4;
int iVar5;
iVar0 = -1;
switch (iParam0)
{
case 0:
iVar0 = 0;
break;
case 1:
iVar0 = 1;
break;
case 2:
iVar0 = 2;
break;
}
if (iVar0 < -1 && iVar0 > 3)
{
return;
}
iVar1 = ((Global_51758[iVar0 /*120*/] - 1) - iParam1);
while (iVar1 >= 16)
{
iVar1 = (iVar1 - 16);
}
iVar2 = iVar1;
iVar3 = Global_51758[iVar0 /*120*/].f_18[iVar2];
iVar4 = Global_51758[iVar0 /*120*/].f_1[iVar2];
if (((iVar4 < 0 || iVar3 < 0) || !iVar4 < 9) || !iVar3 < 122)
{
return;
}
iVar5 = Global_46145[iVar3 /*46*/].f_32[iVar4];
if (Global_42820[iVar5 /*12*/].f_4 == 0)
{
return;
}
Global_51758[iVar0 /*120*/].f_35[iVar2] = 1;
Global_51758[iVar0 /*120*/].f_52[iVar2] = iParam2;
func_23(iVar3, iParam2);
}
void func_23(int iParam0, int iParam1)
{
int iVar0;
int iVar1;
int iVar2;
bool bVar3;
int iVar4;
int iVar5;
int iVar6;
int iVar7;
if (!Global_46145[iParam0 /*46*/] && !Global_46145[iParam0 /*46*/].f_1)
{
return;
}
iVar0 = (Global_46145[iParam0 /*46*/].f_42 - 1);
if (iVar0 < 0)
{
return;
}
iVar1 = Global_46145[iParam0 /*46*/].f_32[iVar0];
if (!iParam1 < Global_42820[iVar1 /*12*/].f_4)
{
return;
}
iVar2 = Global_42820[iVar1 /*12*/].f_5[iParam1 /*4*/].f_1;
bVar3 = false;
if (Global_46145[iParam0 /*46*/].f_31 < (Global_46145[iParam0 /*46*/].f_30 - 1))
{
iVar4 = Global_46145[iParam0 /*46*/].f_8[Global_46145[iParam0 /*46*/].f_31];
if (iVar2 == iVar4)
{
bVar3 = true;
}
}
if (!bVar3)
{
if (iVar2 > -1)
{
func_33(iParam0, iVar2);
iVar5 = Global_46145[iParam0 /*46*/].f_2;
iVar6 = 0;
iVar7 = Global_42820[iVar2 /*12*/].f_2;
iVar6 = 0;
while (iVar6 < iVar5)
{
if (!iVar6 == iVar7)
{
func_27(Global_46145[iParam0 /*46*/].f_3[iVar6], iParam0, 0, 0, 0);
}
iVar6++;
}
}
}
if (Global_42820[iVar1 /*12*/].f_5[iParam1 /*4*/].f_3 > -1)
{
func_24(Global_42820[iVar1 /*12*/].f_5[iParam1 /*4*/].f_3, 0);
}
if (Global_42820[iVar1 /*12*/].f_5[iParam1 /*4*/].f_2)
{
Global_46145[iParam0 /*46*/].f_1 = 1;
}
else if (iVar2 > -1)
{
Global_46145[iParam0 /*46*/].f_45 = Global_42820[iVar2 /*12*/].f_10;
Global_46145[iParam0 /*46*/].f_43 = Global_42820[iVar2 /*12*/].f_11;
}
else
{
Global_46145[iParam0 /*46*/].f_45 = 0;
}
if (Global_46145[iParam0 /*46*/].f_43 < 30000)
{
Global_46145[iParam0 /*46*/].f_43 = 30000;
}
}
void func_24(int iParam0, bool bParam1)
{
Global_42811 = 1;
if (!Global_46145[iParam0 /*46*/] && !Global_46145[iParam0 /*46*/].f_1)
{
Global_46145[iParam0 /*46*/] = 1;
func_26(iParam0, bParam1);
}
else
{
func_25(iParam0);
func_24(iParam0, bParam1);
}
}
void func_25(int iParam0)
{
Global_46145[iParam0 /*46*/] = 0;
Global_46145[iParam0 /*46*/].f_31 = 0;
Global_46145[iParam0 /*46*/].f_42 = 0;
Global_46145[iParam0 /*46*/].f_45 = 0;
Global_46145[iParam0 /*46*/].f_43 = 0;
Global_46145[iParam0 /*46*/].f_1 = 0;
}
void func_26(int iParam0, bool bParam1)
{
int iVar0;
int iVar1;
int iVar2;
int iVar3;
if (!Global_46145[iParam0 /*46*/] && !Global_46145[iParam0 /*46*/].f_1)
{
return;
}
if (Global_46145[iParam0 /*46*/].f_31 == Global_46145[iParam0 /*46*/].f_30)
{
iVar0 = (Global_46145[iParam0 /*46*/].f_42 - 1);
if (iVar0 < 0)
{
return;
}
if (Global_42820[Global_46145[iParam0 /*46*/].f_32[iVar0] /*12*/].f_4 == 0)
{
Global_46145[iParam0 /*46*/].f_1 = 1;
}
return;
}
if (Global_46145[iParam0 /*46*/].f_1)
{
return;
}
iVar1 = Global_46145[iParam0 /*46*/].f_8[Global_46145[iParam0 /*46*/].f_31];
Global_46145[iParam0 /*46*/].f_31++;
func_33(iParam0, iVar1);
Global_46145[iParam0 /*46*/].f_45 = Global_42820[iVar1 /*12*/].f_10;
Global_46145[iParam0 /*46*/].f_43 = Global_42820[iVar1 /*12*/].f_11;
iVar2 = Global_46145[iParam0 /*46*/].f_2;
func_27(Global_42820[iVar1 /*12*/].f_3, iParam0, 0, 0, bParam1);
iVar3 = 0;
while (iVar3 < iVar2)
{
if (Global_46145[iParam0 /*46*/].f_3[iVar3] != Global_42820[iVar1 /*12*/].f_2 && Global_46145[iParam0 /*46*/].f_3[iVar3] != Global_42820[iVar1 /*12*/].f_3)
{
func_27(Global_46145[iParam0 /*46*/].f_3[iVar3], iParam0, 0, 0, bParam1);
}
iVar3++;
}
if (Global_46145[iParam0 /*46*/].f_31 == Global_46145[iParam0 /*46*/].f_30)
{
if (Global_42820[Global_46145[iParam0 /*46*/].f_32[(Global_46145[iParam0 /*46*/].f_42 - 1)] /*12*/].f_4 == 0)
{
Global_46145[iParam0 /*46*/].f_1 = 1;
return;
}
}
}
void func_27(int iParam0, int iParam1, bool bParam2, bool bParam3, bool bParam4)
{
int iVar0;
int iVar1;
int iVar2;
struct<16> Var3;
int iVar19;
int iVar20;
bool bVar21;
bool bVar22;
int iVar23;
int iVar24;
int iVar25;
int iVar26;
if (!iParam0 < 3)
{
return;
}
iVar0 = -1;
StringCopy(&Var3, "UNSET", 64);
if (!bParam2)
{
iVar19 = (Global_46145[iParam1 /*46*/].f_42 - 1);
if (iVar19 < 0)
{
return;
}
iVar20 = Global_46145[iParam1 /*46*/].f_32[iVar19];
iVar2 = iVar20;
Var3 = { func_32(Global_42820[iVar20 /*12*/].f_1) };
if (Global_42820[iVar20 /*12*/].f_2 == iParam0 && !Global_42820[iVar20 /*12*/].f_3 == iParam0)
{
return;
}
iVar1 = Global_42820[iVar20 /*12*/].f_2;
iVar0 = Global_51758[iParam0 /*120*/];
bVar21 = false;
while (iVar0 >= 16)
{
iVar0 = (iVar0 - 16);
bVar21 = true;
}
if (bVar21)
{
if (!Global_51758[iParam0 /*120*/].f_69[iVar0])
{
switch (iParam0)
{
case 0:
Global_42812 = (Global_42812 - 1);
if (Global_42812 < 0)
{
Global_42812 = 0;
}
break;
case 1:
Global_42813 = (Global_42813 - 1);
if (Global_42813 < 0)
{
Global_42813 = 0;
}
break;
case 2:
Global_42814 = (Global_42814 - 1);
if (Global_42814 < 0)
{
Global_42814 = 0;
}
break;
}
}
}
Global_51758[iParam0 /*120*/].f_18[iVar0] = iParam1;
Global_51758[iParam0 /*120*/].f_1[iVar0] = iVar19;
Global_51758[iParam0 /*120*/].f_35[iVar0] = 0;
Global_51758[iParam0 /*120*/].f_86[iVar0] = 0;
Global_51758[iParam0 /*120*/].f_69[iVar0] = 0;
Global_51758[iParam0 /*120*/]++;
}
else
{
iVar0 = Global_51758[iParam0 /*120*/];
bVar22 = false;
while (iVar0 >= 16)
{
iVar0 = (iVar0 - 16);
bVar22 = true;
}
if (bVar22)
{
if (!Global_51758[iParam0 /*120*/].f_69[iVar0])
{
switch (iParam0)
{
case 0:
Global_42812 = (Global_42812 - 1);
if (Global_42812 < 0)
{
Global_42812 = 0;
}
break;
case 1:
Global_42813 = (Global_42813 - 1);
if (Global_42813 < 0)
{
Global_42813 = 0;
}
break;
case 2:
Global_42814 = (Global_42814 - 1);
if (Global_42814 < 0)
{
Global_42814 = 0;
}
break;
}
}
}
iVar23 = -1;
iVar24 = 0;
iVar24 = 0;
while (iVar24 < 7)
{
if (Global_52120[iVar24 /*203*/].f_1 == iParam1 && Global_52120[iVar24 /*203*/].f_9 > 0)
{
iVar23 = iVar24;
}
iVar24++;
}
if (iVar23 == -1)
{
return;
}
Global_51758[iParam0 /*120*/].f_18[iVar0] = Global_52120[iVar23 /*203*/].f_1;
Global_51758[iParam0 /*120*/].f_1[iVar0] = (Global_52120[iVar23 /*203*/].f_9 - 1);
Global_51758[iParam0 /*120*/].f_35[iVar0] = 0;
Global_51758[iParam0 /*120*/].f_86[iVar0] = 1;
Global_51758[iParam0 /*120*/].f_69[iVar0] = 0;
Global_51758[iParam0 /*120*/]++;
iVar25 = Global_51758[iParam0 /*120*/].f_1[iVar0];
iVar26 = Global_52120[iVar23 /*203*/].f_10[iVar25 /*48*/];
iVar2 = iVar26;
iVar1 = Global_42820[iVar26 /*12*/].f_2;
if (Global_52120[iVar23 /*203*/].f_10[(Global_52120[iVar23 /*203*/].f_9 - 1) /*48*/].f_1)
{
MemCopy(&Var3, {Global_52120[iVar23 /*203*/].f_10[(Global_52120[iVar23 /*203*/].f_9 - 1) /*48*/].f_2}, 16);
}
else
{
Var3 = { func_32(Global_42820[iVar26 /*12*/].f_1) };
}
}
if (!bParam4)
{
if (!Global_51758[iParam0 /*120*/].f_69[iVar0] && !bParam3)
{
switch (iParam0)
{
case 0:
func_28(0, iVar1, iVar2, &Var3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
break;
case 1:
if (iVar2 == 249)
{
func_28(1, iVar1, iVar2, "PW_FEED_EM_1", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
else
{
func_28(1, iVar1, iVar2, &Var3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
break;
case 2:
func_28(2, iVar1, iVar2, &Var3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
break;
}
}
}
}
void func_28(int iParam0, int iParam1, int iParam2, char* sParam3, char* sParam4, char* sParam5, char* sParam6, char* sParam7, char* sParam8, char* sParam9, char* sParam10, char* sParam11, char* sParam12, char* sParam13)
{
int iVar0;
bool bVar1;
char cVar2[64];
if (CUTSCENE::IS_CUTSCENE_PLAYING())
{
return;
}
iVar0 = func_78();
bVar1 = false;
StringCopy(&cVar2, func_31(iParam1, &bVar1), 64);
if (iVar0 == iParam0)
{
switch (iParam2)
{
case 72:
HUD::BEGIN_TEXT_COMMAND_THEFEED_POST("PROPR_INCEMAIL1");
break;
case 73:
HUD::BEGIN_TEXT_COMMAND_THEFEED_POST("PROPR_INCEMAIL3");
break;
case 74:
HUD::BEGIN_TEXT_COMMAND_THEFEED_POST("PROPR_INCEMAIL2");
break;
default:
HUD::BEGIN_TEXT_COMMAND_THEFEED_POST(sParam3);
if (!MISC::IS_STRING_NULL_OR_EMPTY(sParam4))
{
HUD::ADD_TEXT_COMPONENT_SUBSTRING_TEXT_LABEL(sParam4);
}
if (!MISC::IS_STRING_NULL_OR_EMPTY(sParam5))
{
HUD::ADD_TEXT_COMPONENT_SUBSTRING_TEXT_LABEL(sParam5);
}
if (!MISC::IS_STRING_NULL_OR_EMPTY(sParam6))
{
HUD::ADD_TEXT_COMPONENT_SUBSTRING_TEXT_LABEL(sParam6);
}
if (!MISC::IS_STRING_NULL_OR_EMPTY(sParam7))
{
HUD::ADD_TEXT_COMPONENT_SUBSTRING_TEXT_LABEL(sParam7);
}
if (!MISC::IS_STRING_NULL_OR_EMPTY(sParam8))
{
HUD::ADD_TEXT_COMPONENT_SUBSTRING_TEXT_LABEL(sParam8);
}
if (!MISC::IS_STRING_NULL_OR_EMPTY(sParam9))
{
HUD::ADD_TEXT_COMPONENT_SUBSTRING_TEXT_LABEL(sParam9);
}
if (!MISC::IS_STRING_NULL_OR_EMPTY(sParam10))
{
HUD::ADD_TEXT_COMPONENT_SUBSTRING_TEXT_LABEL(sParam10);
}
if (!MISC::IS_STRING_NULL_OR_EMPTY(sParam11))
{
HUD::ADD_TEXT_COMPONENT_SUBSTRING_TEXT_LABEL(sParam11);
}
if (!MISC::IS_STRING_NULL_OR_EMPTY(sParam12))
{
HUD::ADD_TEXT_COMPONENT_SUBSTRING_TEXT_LABEL(sParam12);
}
if (!MISC::IS_STRING_NULL_OR_EMPTY(sParam13))
{
HUD::ADD_TEXT_COMPONENT_SUBSTRING_TEXT_LABEL(sParam13);
}
break;
}
if (bVar1)
{
func_29(HUD::END_TEXT_COMMAND_THEFEED_POST_MESSAGETEXT(&cVar2, &cVar2, false, 2, HUD::_GET_LABEL_TEXT(func_30(iParam1)), 0));
}
else
{
func_29(HUD::END_TEXT_COMMAND_THEFEED_POST_MESSAGETEXT("CHAR_DEFAULT", "CHAR_DEFAULT", false, 2, HUD::_GET_LABEL_TEXT(func_30(iParam1)), 0));
}
switch (Global_19681)
{
case 0:
StringCopy(&Global_19670, "Phone_SoundSet_Michael", 24);
Global_42812++;
if (Global_42812 > 16)
{
Global_42812 = 16;
}
break;
case 2:
StringCopy(&Global_19670, "Phone_SoundSet_Trevor", 24);
Global_42814++;
if (Global_42814 > 16)
{
Global_42814 = 16;
}
break;
case 1:
StringCopy(&Global_19670, "Phone_SoundSet_Franklin", 24);
Global_42813++;
if (Global_42813 > 16)
{
Global_42813 = 16;
}
break;
default:
StringCopy(&Global_19670, "Phone_SoundSet_Default", 24);
break;
}
AUDIO::PLAY_SOUND_FRONTEND(-1, "Notification", &Global_19670, true);
}
}
void func_29(int iParam0)
{
Global_42815[Global_42819] = iParam0;
Global_22063 = 1;
Global_22062 = iParam0;
Global_42819++;
if (Global_42819 == 3)
{
Global_42819 = 0;
}
}
char* func_30(int iParam0)
{
switch (iParam0)
{
case 0:
return "EMSTR_0";
case 3:
return "EMSTR_3";
case 1:
return "EMSTR_6";
case 2:
return "EMSTR_9";
case 4:
return "EMSTR_12";
case 5:
return "EMSTR_29";
case 6:
return "EMSTR_36";
case 7:
return "EMSTR_39";
case 8:
return "EMSTR_52";
case 9:
return "EMSTR_55";
case 10:
return "EMSTR_58";
case 11:
return "EMSTR_78";
case 12:
return "EMSTR_81";
case 13:
return "EMSTR_84";
case 14:
return "EMSTR_87";
case 15:
return "EMSTR_106";
case 16:
return "EMSTR_114";
case 17:
return "EMSTR_142";
case 18:
return "EMSTR_145";
case 19:
return "EMSTR_152";
case 20:
return "EMSTR_157";
case 21:
return "EMSTR_163";
case 22:
return "EMSTR_182";
case 23:
return "EMSTR_187";
case 24:
return "EMSTR_190";
case 25:
return "EMSTR_206";
case 26:
return "EMSTR_219";
case 27:
return "EMSTR_226";
case 28:
return "EMSTR_233";
case 29:
return "EMSTR_242";
case 30:
return "EMSTR_249";
case 31:
return "EMSTR_262";
case 32:
return "EMSTR_269";
case 33:
return "EMSTR_319";
case 34:
return "EMSTR_340";
case 35:
return "EMSTR_348";
case 36:
return "EMSTR_182";
case 37:
return "EMSTR_357";
case 38:
return "EMSTR_360";
case 39:
return "EMSTR_369";
case 40:
return "EMSTR_376";
case 41:
return "EMSTR_379";
case 42:
return "EMSTR_382";
case 43:
return "EMSTR_384";
case 44:
return "EMSTR_387";
case 45:
return "EMSTR_390";
case 46:
return "EMSTR_393";
case 47:
return "EMSTR_396";
case 48:
return "EMSTR_399";
case 49:
return "EMSTR_402";
case 50:
return "EMSTR_405";
case 51:
return "EMSTR_408";
case 52:
return "EMSTR_411";
case 53:
return "EMSTR_414";
case 54:
return "EMSTR_465";
case 55:
return "EMSTR_468";
case 56:
return "EMSTR_489";
case 57:
return "EMSTR_492";
case 58:
return "EMSTR_495";
case 59:
return "EMSTR_498";
case 60:
return "EMSTR_501";
case 61:
return "EMSTR_504";
case 62:
return "EMSTR_507";
case 63:
return "EMSTR_640";
case 64:
return "EMSTR_643";
case 65:
return "EMSTR_652";
default:
}
return "NULL";
}
char* func_31(int iParam0, int iParam1)
{
*iParam1 = 1;
switch (iParam0)
{
case 0:
return HUD::_GET_LABEL_TEXT(&(Global_1848[0 /*29*/].f_7));
case 1:
return HUD::_GET_LABEL_TEXT(&(Global_1848[1 /*29*/].f_7));
case 2:
return HUD::_GET_LABEL_TEXT(&(Global_1848[2 /*29*/].f_7));
case 7:
return HUD::_GET_LABEL_TEXT(&(Global_1848[12 /*29*/].f_7));
case 4:
return HUD::_GET_LABEL_TEXT(&(Global_1848[60 /*29*/].f_7));
case 6:
return HUD::_GET_LABEL_TEXT(&(Global_1848[62 /*29*/].f_7));
case 3:
return HUD::_GET_LABEL_TEXT(&(Global_1848[14 /*29*/].f_7));
case 16:
return HUD::_GET_LABEL_TEXT(&(Global_1848[97 /*29*/].f_7));
case 19:
return HUD::_GET_LABEL_TEXT(&(Global_1848[99 /*29*/].f_7));
case 15:
return HUD::_GET_LABEL_TEXT(&(Global_1848[96 /*29*/].f_7));
case 63:
return "CHAR_CARSITE2";
case 64:
return "CHAR_BOATSITE";
case 8:
return "CHAR_BANK_MAZE";
case 9:
return "CHAR_BANK_FLEECA";
case 10:
return "CHAR_BANK_BOL";
case 21:
return "CHAR_MINOTAUR";
case 25:
return HUD::_GET_LABEL_TEXT(&(Global_1848[15 /*29*/].f_7));
case 26:
return HUD::_GET_LABEL_TEXT(&(Global_1848[30 /*29*/].f_7));
case 27:
return HUD::_GET_LABEL_TEXT(&(Global_1848[17 /*29*/].f_7));
case 29:
return HUD::_GET_LABEL_TEXT(&(Global_1848[20 /*29*/].f_7));
case 30:
return HUD::_GET_LABEL_TEXT(&(Global_1848[43 /*29*/].f_7));
case 31:
return HUD::_GET_LABEL_TEXT(&(Global_1848[44 /*29*/].f_7));
case 32:
return HUD::_GET_LABEL_TEXT(&(Global_1848[19 /*29*/].f_7));
case 34:
return HUD::_GET_LABEL_TEXT(&(Global_1848[40 /*29*/].f_7));
case 36:
return HUD::_GET_LABEL_TEXT("CELL_E_381");
case 38:
return HUD::_GET_LABEL_TEXT(&(Global_1848[64 /*29*/].f_7));
case 5:
return "CHAR_EPSILON";
case 13:
return "CHAR_MILSITE";
case 11:
return "CHAR_CARSITE";
case 14:
return "CHAR_BOATSITE";
case 12:
return "CHAR_PLANESITE";
case 24:
return "CHAR_DR_FRIEDLANDER";
case 55:
return "CHAR_CARSITE2";
case 54:
return "CHAR_BIKESITE";
case 39:
return HUD::_GET_LABEL_TEXT(&(Global_1848[122 /*29*/].f_7));
case 40:
return HUD::_GET_LABEL_TEXT(&(Global_1848[125 /*29*/].f_7));
case 41:
return HUD::_GET_LABEL_TEXT(&(Global_1848[113 /*29*/].f_7));
case 42:
return HUD::_GET_LABEL_TEXT(&(Global_1848[126 /*29*/].f_7));
case 43:
return HUD::_GET_LABEL_TEXT(&(Global_1848[127 /*29*/].f_7));
case 44:
return HUD::_GET_LABEL_TEXT(&(Global_1848[124 /*29*/].f_7));
case 45:
return HUD::_GET_LABEL_TEXT(&(Global_1848[114 /*29*/].f_7));
case 46:
return HUD::_GET_LABEL_TEXT(&(Global_1848[115 /*29*/].f_7));
case 47:
return HUD::_GET_LABEL_TEXT(&(Global_1848[116 /*29*/].f_7));
case 48:
return HUD::_GET_LABEL_TEXT(&(Global_1848[123 /*29*/].f_7));
case 49:
return HUD::_GET_LABEL_TEXT(&(Global_1848[117 /*29*/].f_7));
case 50:
return HUD::_GET_LABEL_TEXT(&(Global_1848[118 /*29*/].f_7));
case 51:
return HUD::_GET_LABEL_TEXT(&(Global_1848[119 /*29*/].f_7));
case 52:
return HUD::_GET_LABEL_TEXT(&(Global_1848[120 /*29*/].f_7));
case 53:
return HUD::_GET_LABEL_TEXT(&(Global_1848[121 /*29*/].f_7));
default:
}
*iParam1 = 0;
return "ERROR!";
}
struct<16> func_32(int iParam0)
{
struct<16> Var0;
struct<16> Var16;
if (iParam0 > -1)
{
StringCopy(&Var0, "EMSTR_", 64);
StringIntConCat(&Var0, iParam0, 64);
return Var0;
}
StringCopy(&Var16, "FAIL", 64);
return Var16;
}
int func_33(int iParam0, int iParam1)
{
if (Global_46145[iParam0 /*46*/].f_42 >= 9)
{
return 0;
}
Global_46145[iParam0 /*46*/].f_32[Global_46145[iParam0 /*46*/].f_42] = iParam1;
Global_46145[iParam0 /*46*/].f_42++;
return 1;
}
int func_34(int iParam0, int iParam1)
{
int iVar0;
int iVar1;
int iVar2;
int iVar3;
int iVar4;
int iVar5;
iVar0 = -1;
switch (iParam0)
{
case 0:
iVar0 = 0;
break;
case 1:
iVar0 = 1;
break;
case 2:
iVar0 = 2;
break;
}
if (iVar0 == -1)
{
return 0;
}
iVar1 = ((Global_51758[iVar0 /*120*/] - 1) - iParam1);
while (iVar1 >= 16)
{
iVar1 = (iVar1 - 16);
}
iVar2 = iVar1;
if (!Global_51758[iVar0 /*120*/].f_86[iVar2])
{
iVar3 = Global_51758[iVar0 /*120*/].f_18[iVar2];
iVar4 = Global_51758[iVar0 /*120*/].f_1[iVar2];
iVar5 = Global_46145[iVar3 /*46*/].f_32[iVar4];
if (Global_42820[iVar5 /*12*/].f_4 == 0)
{
return 0;
}
if (Global_51758[iVar0 /*120*/].f_35[iVar2] == 1)
{
return 0;
}
if (!func_35(iVar0, iVar2))
{
return 0;
}
return 1;
}
return 0;
}
int func_35(int iParam0, int iParam1)
{
int iVar0;
int iVar1;
int iVar2;
if (!iParam0 < 3)
{
return 0;
}
iVar0 = Global_51758[iParam0 /*120*/].f_1[iParam1];
iVar1 = Global_51758[iParam0 /*120*/].f_18[iParam1];
if (!(Global_46145[iVar1 /*46*/] && !Global_46145[iVar1 /*46*/].f_1))
{
return 0;
}
if (!iVar0 == (Global_46145[iVar1 /*46*/].f_42 - 1))
{
return 0;
}
iVar2 = Global_46145[iVar1 /*46*/].f_32[(Global_46145[iVar1 /*46*/].f_42 - 1)];
if (Global_42820[iVar2 /*12*/].f_4 > 0)
{
return 1;
}
return 0;
}
bool func_36()
{
return Global_74030;
}
void func_37()
{
if (!ENTITY::IS_ENTITY_DEAD(PLAYER::PLAYER_PED_ID(), false))
{
AUDIO::PLAY_SOUND_FRONTEND(-1, "Menu_Accept", &Global_19670, true);
func_38();
}
}
void func_38()
{
if (func_2())
{
MOBILE::_CELL_CAM_MOVE_FINGER(5);
}
}
int func_39(int iParam0)
{
int iVar0;
iVar0 = -1;
switch (iParam0)
{
case 0:
iVar0 = 0;
break;
case 1:
iVar0 = 1;
break;
case 2:
iVar0 = 2;
break;
}
return Global_51758[iVar0 /*120*/];
}
void func_40(int iParam0, int iParam1, int iParam2)
{
int iVar0;
int iVar1;
int iVar2;
int iVar3;
int iVar4;
int iVar5;
int iVar6;
int iVar7;
int iVar8;
struct<16> Var9;
struct<16> Var25;
iVar0 = -1;
switch (iParam1)
{
case 0:
iVar0 = 0;
break;
case 1:
iVar0 = 1;
break;
case 2:
iVar0 = 2;
break;
}
if (iVar0 == -1)
{
return;
}
iVar1 = ((Global_51758[iVar0 /*120*/] - 1) - iParam2);
while (iVar1 >= 16)
{
iVar1 = (iVar1 - 16);
}
iVar2 = iVar1;
if (!Global_51758[iVar0 /*120*/].f_86[iVar2])
{
iVar3 = Global_51758[iVar0 /*120*/].f_18[iVar2];
iVar4 = Global_51758[iVar0 /*120*/].f_1[iVar2];
iVar5 = Global_46145[iVar3 /*46*/].f_32[iVar4];
if (Global_42820[iVar5 /*12*/].f_4 == 0)
{
return;
}
iVar6 = 0;
iVar7 = Global_42820[iVar5 /*12*/].f_4;
if (iVar7 > 1)
{
iVar7 = 1;
}
iVar6 = 0;
while (iVar6 < iVar7)
{
iVar8 = Global_42820[iVar5 /*12*/].f_5[iVar6 /*4*/].f_1;
Var9 = { func_32(Global_42820[iVar8 /*12*/].f_1) };
Var25 = { func_32(Global_42820[iVar8 /*12*/].f_1) };
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(iParam0, "SET_DATA_SLOT");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(9);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(0);
func_9("");
func_9("");
func_9("EM_RESPONSE_NEW");
func_9(&Var25);
func_9(func_42(Global_42820[iVar8 /*12*/].f_2));
func_41(iVar8, Global_42820[iVar8 /*12*/].f_2);
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
iVar6++;
}
}
}
void func_41(int iParam0, int iParam1)
{
int iVar0;
iVar0 = iParam0;
switch (iVar0)
{
case 55:
case 57:
case 58:
case 59:
case 62:
case 63:
case 40:
case 41:
case 42:
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_TEXTURE_NAME_STRING("EmailAds_Elitas_Travel");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_BOOL(true);
return;
case 37:
case 38:
case 39:
case 60:
case 61:
case 56:
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_TEXTURE_NAME_STRING("EmailAds_Dock_Tease");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_BOOL(true);
return;
case 34:
case 35:
case 36:
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_TEXTURE_NAME_STRING("EmailAds_Warstock");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_BOOL(true);
return;
case 31:
case 32:
case 33:
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_TEXTURE_NAME_STRING("EmailAds_Legendary_Motorsport");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_BOOL(true);
return;
default:
}
switch (iParam1)
{
case 13:
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_TEXTURE_NAME_STRING("EmailAds_Warstock");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_BOOL(true);
return;
case 15:
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_TEXTURE_NAME_STRING("EmailAds_LS_Customs");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_BOOL(true);
return;
case 19:
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_TEXTURE_NAME_STRING("EmailAds_LS_Tourist_Info");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_BOOL(true);
return;
default:
}
}
char* func_42(int iParam0)
{
switch (iParam0)
{
case 0:
return "EMSTR_2";
case 3:
return "EMSTR_5";
case 1:
return "EMSTR_8";
case 2:
return "EMSTR_11";
case 4:
return "EMSTR_14";
case 5:
return "EMSTR_31";
case 6:
return "EMSTR_38";
case 7:
return "EMSTR_41";
case 8:
return "EMSTR_54";
case 9:
return "EMSTR_57";
case 10:
return "EMSTR_60";
case 11:
return "EMSTR_80";
case 12:
return "EMSTR_83";
case 13:
return "EMSTR_86";
case 14:
return "EMSTR_89";
case 15:
return "EMSTR_106";
case 16:
return "EMSTR_116";
case 17:
return "EMSTR_144";
case 18:
return "EMSTR_147";
case 19:
return "EMSTR_154";
case 20:
return "EMSTR_159";
case 21:
return "EMSTR_165";
case 22:
return "EMSTR_184";
case 23:
return "EMSTR_189";
case 24:
return "EMSTR_192";
case 25:
return "EMSTR_208";
case 26:
return "EMSTR_221";
case 27:
return "EMSTR_228";
case 28:
return "EMSTR_235";
case 29:
return "EMSTR_244";
case 30:
return "EMSTR_251";
case 31:
return "EMSTR_264";
case 32:
return "EMSTR_271";
case 33:
return "EMSTR_321";
case 34:
return "EMSTR_342";
case 35:
return "EMSTR_350";
case 36:
return "EMSTR_354";
case 37:
return "EMSTR_359";
case 38:
return "EMSTR_362";
case 39:
return "EMSTR_371";
case 40:
return "EMSTR_378";
case 41:
return "EMSTR_381";
case 42:
return "EMSTR_382";
case 43:
return "EMSTR_386";
case 44:
return "EMSTR_389";
case 45:
return "EMSTR_392";
case 46:
return "EMSTR_395";
case 47:
return "EMSTR_398";
case 48:
return "EMSTR_401";
case 49:
return "EMSTR_404";
case 50:
return "EMSTR_407";
case 51:
return "EMSTR_410";
case 52:
return "EMSTR_413";
case 53:
return "EMSTR_416";
case 54:
return "EMSTR_467";
case 55:
return "EMSTR_470";
case 56:
return "EMSTR_491";
case 57:
return "EMSTR_494";
case 58:
return "EMSTR_497";
case 59:
return "EMSTR_500";
case 60:
return "EMSTR_503";
case 61:
return "EMSTR_506";
case 62:
return "EMSTR_509";
case 63:
return "EMSTR_642";
case 64:
return "EMSTR_645";
case 65:
return "EMSTR_654";
default:
}
return "NULL";
}
void func_43(char* sParam0, int iParam1)
{
HUD::BEGIN_TEXT_COMMAND_DISPLAY_HELP(sParam0);
HUD::END_TEXT_COMMAND_DISPLAY_HELP(0, false, true, iParam1);
}
void func_44(int iParam0)
{
int iVar0;
int iVar1;
iVar0 = iParam0;
iVar1 = 0;
while (iVar0 > 31)
{
iVar0 = (iVar0 - 32);
iVar1++;
}
if (iVar1 < 3)
{
MISC::SET_BIT(&(Global_111858.f_20406.f_150[iVar1]), iVar0);
}
}
void func_45(char* sParam0, int iParam1, int iParam2, int iParam3, int iParam4, int iParam5, int iParam6, int iParam7, int iParam8)
{
func_46(sParam0, "", iParam1, iParam2, iParam3, iParam4, iParam5, iParam6, iParam7, iParam8);
}
void func_46(char* sParam0, char* sParam1, var uParam2, int iParam3, int iParam4, int iParam5, int iParam6, int iParam7, int iParam8, var uParam9)
{
int iVar0;
if (MISC::ARE_STRINGS_EQUAL(sParam0, ""))
{
return;
}
if (iParam3 < 0)
{
return;
}
if (iParam5 < 500 && iParam5 != -1)
{
return;
}
if (iParam4 < 0 && iParam4 != -1)
{
return;
}
if (iParam6 < 1 || iParam6 > 7)
{
return;
}
if (iParam7 == 235)
{
return;
}
if (iParam8 == 235)
{
return;
}
iVar0 = 0;
while (iVar0 < Global_111858.f_20406.f_145)
{
if (MISC::ARE_STRINGS_EQUAL(&(Global_111858.f_20406[iVar0 /*16*/]), sParam0))
{
return;
}
iVar0++;
}
if (Global_111858.f_20406.f_145 < 9)
{
StringCopy(&(Global_111858.f_20406[Global_111858.f_20406.f_145 /*16*/]), sParam0, 16);
StringCopy(&(Global_111858.f_20406[Global_111858.f_20406.f_145 /*16*/].f_4), sParam1, 16);
Global_111858.f_20406[Global_111858.f_20406.f_145 /*16*/].f_8 = (MISC::GET_GAME_TIMER() + iParam3);
Global_111858.f_20406[Global_111858.f_20406.f_145 /*16*/].f_9 = iParam5;
Global_111858.f_20406[Global_111858.f_20406.f_145 /*16*/].f_11 = iParam6;
Global_111858.f_20406[Global_111858.f_20406.f_145 /*16*/].f_12 = uParam2;
Global_111858.f_20406[Global_111858.f_20406.f_145 /*16*/].f_13 = iParam7;
Global_111858.f_20406[Global_111858.f_20406.f_145 /*16*/].f_14 = iParam8;
Global_111858.f_20406[Global_111858.f_20406.f_145 /*16*/].f_15 = uParam9;
if (iParam4 != -1)
{
Global_111858.f_20406[Global_111858.f_20406.f_145 /*16*/].f_10 = ((MISC::GET_GAME_TIMER() + iParam3) + iParam4);
}
else
{
Global_111858.f_20406[Global_111858.f_20406.f_145 /*16*/].f_10 = -1;
}
Global_111858.f_20406.f_145++;
func_47();
}
}
void func_47()
{
int iVar0;
iVar0 = 0;
while (iVar0 < 3)
{
Global_111858.f_20406.f_146[iVar0] = 0;
iVar0++;
}
iVar0 = 0;
while (iVar0 < Global_111858.f_20406.f_145)
{
if (MISC::IS_BIT_SET(Global_111858.f_20406[iVar0 /*16*/].f_11, 0))
{
if (Global_111858.f_20406[iVar0 /*16*/].f_12 > Global_111858.f_20406.f_146[0])
{
Global_111858.f_20406.f_146[0] = Global_111858.f_20406[iVar0 /*16*/].f_12;
}
}
if (MISC::IS_BIT_SET(Global_111858.f_20406[iVar0 /*16*/].f_11, 1))
{
if (Global_111858.f_20406[iVar0 /*16*/].f_12 > Global_111858.f_20406.f_146[1])
{
Global_111858.f_20406.f_146[1] = Global_111858.f_20406[iVar0 /*16*/].f_12;
}
}
if (MISC::IS_BIT_SET(Global_111858.f_20406[iVar0 /*16*/].f_11, 2))
{
if (Global_111858.f_20406[iVar0 /*16*/].f_12 > Global_111858.f_20406.f_146[2])
{
Global_111858.f_20406.f_146[2] = Global_111858.f_20406[iVar0 /*16*/].f_12;
}
}
iVar0++;
}
}
int func_48(char* sParam0)
{
if (MISC::ARE_STRINGS_EQUAL(sParam0, &Global_110501))
{
return 1;
}
if (func_49(sParam0))
{
return 0;
}
return 2;
}
int func_49(char* sParam0)
{
int iVar0;
iVar0 = 0;
while (iVar0 < Global_111858.f_20406.f_145)
{
if (MISC::ARE_STRINGS_EQUAL(sParam0, &(Global_111858.f_20406[iVar0 /*16*/])))
{
return 1;
}
iVar0++;
}
return 0;
}
int func_50(int iParam0)
{
int iVar0;
int iVar1;
iVar0 = iParam0;
iVar1 = 0;
while (iVar0 > 31)
{
iVar0 = (iVar0 - 32);
iVar1++;
}
if (iVar1 < 3)
{
return MISC::IS_BIT_SET(Global_111858.f_20406.f_150[iVar1], iVar0);
}
return 0;
}
char* func_51(int iParam0, int iParam1)
{
int iVar0;
var uVar1;
int iVar2;
int iVar3;
int iVar4;
int iVar5;
bool bVar6;
int iVar7;
int iVar8;
iVar0 = -1;
switch (iParam0)
{
case 0:
iVar0 = 0;
break;
case 1:
iVar0 = 1;
break;
case 2:
iVar0 = 2;
break;
}
if (iVar0 == -1)
{
return "";
}
iVar4 = func_53(iVar0, iParam1, &iVar2, &iVar3, &uVar1);
uVar1 = uVar1;
iVar5 = -1;
bVar6 = Global_51758[iVar0 /*120*/].f_86[iVar4];
if (!bVar6)
{
iVar5 = Global_46145[iVar2 /*46*/].f_32[iVar3];
}
else
{
iVar7 = -1;
iVar8 = 0;
iVar8 = 0;
while (iVar8 < 7)
{
if (Global_52120[iVar8 /*203*/].f_1 == iVar2)
{
iVar7 = iVar8;
}
iVar8++;
}
iVar5 = Global_52120[iVar7 /*203*/].f_10[iVar3 /*48*/];
}
return func_52(iVar5);
}
char* func_52(int iParam0)
{
switch (iParam0)
{
case 7:
return "WWW_EPSILONPROGRAM_COM_S_MAKEDONATION";
case 8:
return "WWW_EPSILONPROGRAM_COM_S_MAKEDONATION";
case 9:
return "WWW_EPSILONPROGRAM_COM_S_STORE";
case 10:
return "WWW_EPSILONPROGRAM_COM";
case 11:
return "WWW_EPSILONPROGRAM_COM";
case 16:
return "WWW_EPSILONPROGRAM_COM";
case 17:
return "WWW_MAZE_D_BANK_COM";
case 18:
return "WWW_FLEECA_COM";
case 19:
return "WWW_MAZE_D_BANK_COM";
case 20:
return "WWW_MAZE_D_BANK_COM";
case 21:
return "WWW_MAZE_D_BANK_COM";
case 22:
return "WWW_MAZE_D_BANK_COM";
case 23:
return "WWW_THEBANKOFLIBERTY_COM";
case 24:
return "WWW_FLEECA_COM";
case 25:
return "WWW_FLEECA_COM";
case 26:
return "WWW_FLEECA_COM";
case 27:
return "WWW_FLEECA_COM";
case 28:
return "WWW_THEBANKOFLIBERTY_COM";
case 29:
return "WWW_THEBANKOFLIBERTY_COM";
case 30:
return "WWW_THEBANKOFLIBERTY_COM";
case 43:
return "WWW_LCN_D_EXCHANGE_COM";
case 47:
return "WWW_AMMUNATION_NET";
case 48:
return "WWW_AMMUNATION_NET";
case 49:
return "WWW_AMMUNATION_NET";
case 50:
return "WWW_AMMUNATION_NET";
case 51:
return "WWW_AMMUNATION_NET";
case 52:
return "WWW_AMMUNATION_NET";
case 53:
return "WWW_AMMUNATION_NET";
case 54:
return "WWW_AMMUNATION_NET";
case 55:
return "WWW_ELITASTRAVEL_COM";
case 56:
return "WWW_DOCKTEASE_COM";
case 57:
return "WWW_ELITASTRAVEL_COM";
case 58:
return "WWW_ELITASTRAVEL_COM";
case 59:
return "WWW_ELITASTRAVEL_COM";
case 60:
return "WWW_DOCKTEASE_COM";
case 61:
return "WWW_DOCKTEASE_COM";
case 62:
return "WWW_ELITASTRAVEL_COM";
case 63:
return "WWW_ELITASTRAVEL_COM";
case 68:
return "WWW_AMMUNATION_NET";
case 84:
return "WWW_EPSILONPROGRAM_COM_S_TRACT";
case 155:
return "WWW_LEGENDARYMOTORSPORT_NET";
case 156:
return "WWW_LEGENDARYMOTORSPORT_NET";
case 157:
return "WWW_LEGENDARYMOTORSPORT_NET";
case 181:
return "WWW_EPSILONPROGRAM_COM_S_MAKEDONATION";
case 194:
return "WWW_HUSHSMUSH_COM";
case 195:
return "WWW_HUSHSMUSH_COM";
case 196:
return "WWW_HUSHSMUSH_COM";
case 197:
return "WWW_HUSHSMUSH_COM";
case 198:
return "WWW_HUSHSMUSH_COM";
case 244:
return "WWW_MYDIVINEWITHIN_COM";
case 245:
return "WWW_THECHILDRENOFTHEMOUNTAIN_COM";
case 246:
return "WWW_THECHILDRENOFTHEMOUNTAIN_COM";
case 270:
return "WWW_AMMUNATION_NET";
case 271:
return "WWW_AMMUNATION_NET";
case 272:
return "WWW_AMMUNATION_NET";
case 273:
return "WWW_AMMUNATION_NET";
case 274:
return "WWW_AMMUNATION_NET";
case 275:
return "WWW_AMMUNATION_NET";
case 276:
return "WWW_AMMUNATION_NET";
default:
}
return "NULL";
}
int func_53(int iParam0, int iParam1, var uParam2, var uParam3, var uParam4)
{
int iVar0;
int iVar1;
iVar0 = ((Global_51758[iParam0 /*120*/] - 1) - iParam1);
while (iVar0 >= 16)
{
iVar0 = (iVar0 - 16);
}
iVar1 = iVar0;
*uParam2 = Global_51758[iParam0 /*120*/].f_18[iVar1];
*uParam3 = Global_51758[iParam0 /*120*/].f_1[iVar1];
*uParam4 = Global_51758[iParam0 /*120*/].f_35[iVar1];
return iVar1;
}
int func_54(int iParam0, int iParam1)
{
int iVar0;
int iVar1;
int iVar2;
var uVar3;
int iVar4;
int iVar5;
bool bVar6;
int iVar7;
int iVar8;
iVar0 = -1;
switch (iParam0)
{
case 0:
iVar0 = 0;
break;
case 1:
iVar0 = 1;
break;
case 2:
iVar0 = 2;
break;
}
if (iVar0 == -1)
{
return 0;
}
iVar4 = func_53(iVar0, iParam1, &iVar1, &iVar2, &uVar3);
uVar3 = uVar3;
iVar5 = -1;
bVar6 = Global_51758[iVar0 /*120*/].f_86[iVar4];
if (!bVar6)
{
iVar5 = Global_46145[iVar1 /*46*/].f_32[iVar2];
}
else
{
iVar7 = -1;
iVar8 = 0;
iVar8 = 0;
while (iVar8 < 7)
{
if (Global_52120[iVar8 /*203*/].f_1 == iVar1)
{
iVar7 = iVar8;
}
iVar8++;
}
iVar5 = Global_52120[iVar7 /*203*/].f_10[iVar2 /*48*/];
}
return func_55(iVar5);
}
int func_55(int iParam0)
{
switch (iParam0)
{
case 7:
case 8:
case 9:
case 10:
case 11:
case 16:
case 17:
case 18:
case 19:
case 20:
case 21:
case 22:
case 23:
case 24:
case 25:
case 26:
case 27:
case 28:
case 29:
case 30:
case 43:
case 47:
case 48:
case 49:
case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57:
case 58:
case 59:
case 60:
case 61:
case 62:
case 63:
case 68:
case 84:
case 155:
case 156:
case 157:
case 181:
case 194:
case 195:
case 196:
case 197:
case 198:
case 244:
case 245:
case 246:
case 270:
case 271:
case 272:
case 273:
case 274:
case 275:
case 276:
return 1;
default:
}
return 0;
}
void func_56(int iParam0, int iParam1, int iParam2)
{
int iVar0;
bool bVar1;
int iVar2;
int iVar3;
int iVar4;
bool bVar5;
int iVar6;
struct<16> Var7;
struct<16> Var23;
int iVar39;
int iVar40;
int iVar41;
int iVar42;
int iVar43;
int iVar44;
int iVar45;
int iVar46;
struct<16> Var47;
struct<16> Var63;
bool bVar79;
int iVar80;
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(iParam0, "SET_DATA_SLOT_EMPTY");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(9);
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
iVar0 = -1;
switch (iParam1)
{
case 0:
iVar0 = 0;
break;
case 1:
iVar0 = 1;
break;
case 2:
iVar0 = 2;
break;
}
if (iVar0 == -1)
{
return;
}
iVar4 = func_53(iVar0, iParam2, &iVar2, &iVar3, &bVar1);
bVar5 = Global_51758[iVar0 /*120*/].f_86[iVar4];
if (!Global_51758[iVar0 /*120*/].f_69[iVar4])
{
func_60(-1);
}
Global_51758[iVar0 /*120*/].f_69[iVar4] = 1;
if (!bVar5)
{
iVar6 = Global_46145[iVar2 /*46*/].f_32[iVar3];
Var7 = { func_32(Global_42820[iVar6 /*12*/]) };
Var23 = { func_32(Global_42820[iVar6 /*12*/].f_1) };
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(iParam0, "SET_DATA_SLOT");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(9);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(0);
func_9(func_59(Global_42820[iVar6 /*12*/].f_3));
func_9(func_59(Global_42820[iVar6 /*12*/].f_2));
func_9(&Var7);
func_9(&Var23);
func_9(func_42(Global_42820[iVar6 /*12*/].f_2));
func_41(iVar6, Global_42820[iVar6 /*12*/].f_2);
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
if (Global_42820[iVar6 /*12*/].f_4 == 0)
{
func_77(0);
}
else if (bVar1 || !func_35(iVar0, iVar4))
{
func_77(0);
}
else
{
func_77(1);
}
if (Global_46145[iVar2 /*46*/].f_42 > 1)
{
iVar39 = iVar3;
iVar40 = (iVar3 - 1);
iVar41 = 0;
iVar41 = 0;
while (iVar41 < iVar39)
{
iVar6 = Global_46145[iVar2 /*46*/].f_32[iVar40];
Var7 = { func_32(Global_42820[iVar6 /*12*/]) };
Var23 = { func_32(Global_42820[iVar6 /*12*/].f_1) };
iVar42 = func_58(iParam1, Global_42820[iVar6 /*12*/].f_3);
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(iParam0, "SET_DATA_SLOT");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(9);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(iVar41 + 1);
func_9(func_59(iVar42));
func_9(func_59(Global_42820[iVar6 /*12*/].f_2));
func_9(&Var7);
func_9(&Var23);
func_9(func_42(Global_42820[iVar6 /*12*/].f_2));
func_41(iVar6, Global_42820[iVar6 /*12*/].f_2);
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
iVar40 = (iVar40 - 1);
iVar41++;
}
}
}
else
{
iVar43 = -1;
iVar44 = 0;
iVar44 = 0;
while (iVar44 < 7)
{
if (Global_52120[iVar44 /*203*/].f_1 == iVar2)
{
iVar43 = iVar44;
}
iVar44++;
}
if (iVar43 == -1)
{
return;
}
else
{
iVar45 = Global_52120[iVar43 /*203*/].f_10[iVar3 /*48*/];
iVar46 = Global_52120[iVar43 /*203*/].f_10[iVar3 /*48*/];
Var47 = { func_32(Global_42820[iVar45 /*12*/]) };
Var63 = { func_32(Global_42820[iVar45 /*12*/].f_1) };
if (Global_52120[iVar43 /*203*/].f_10[iVar3 /*48*/].f_1)
{
MemCopy(&Var63, {Global_52120[iVar43 /*203*/].f_10[iVar3 /*48*/].f_2}, 16);
}
if (Global_42820[iVar45 /*12*/].f_4 == 0)
{
func_77(0);
}
else if (bVar1)
{
func_77(0);
}
else
{
func_77(1);
}
bVar79 = false;
bVar79 = func_57(iParam0, Global_52120[iVar43 /*203*/].f_1, iVar3, iVar46);
if (!bVar79)
{
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(iParam0, "SET_DATA_SLOT");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(9);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(0);
func_9(func_59(Global_42820[iVar45 /*12*/].f_3));
func_9(func_59(Global_42820[iVar45 /*12*/].f_2));
func_9(&Var47);
if (Global_52120[iVar43 /*203*/].f_10[iVar3 /*48*/].f_6 > 0)
{
GRAPHICS::BEGIN_TEXT_COMMAND_SCALEFORM_STRING(&Var63);
iVar80 = 0;
iVar80 = 0;
while (iVar80 < Global_52120[iVar43 /*203*/].f_10[iVar3 /*48*/].f_6)
{
HUD::ADD_TEXT_COMPONENT_SUBSTRING_TEXT_LABEL(&(Global_52120[iVar43 /*203*/].f_10[iVar3 /*48*/].f_7[iVar80 /*4*/]));
iVar80++;
}
GRAPHICS::END_TEXT_COMMAND_SCALEFORM_STRING();
}
else
{
func_9(&Var63);
}
func_9(func_42(Global_42820[iVar45 /*12*/].f_2));
func_41(iVar45, Global_42820[iVar45 /*12*/].f_2);
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
}
}
}
}
int func_57(int iParam0, var uParam1, int iParam2, int iParam3)
{
int iVar0;
var uVar1;
int iVar2;
struct<16> Var3;
struct<8> Var19;
int iVar35;
int iVar36;
bool bVar37;
char* sVar38;
iVar0 = 0;
uVar1 = uParam1;
uVar1 = iParam2;
uVar1 = uVar1;
iVar2 = 0;
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(iParam0, "SET_DATA_SLOT_EMPTY");
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
Var3 = { func_32(Global_42820[iParam3 /*12*/]) };
switch (iParam3)
{
case 72:
StringCopy(&Var19, "PROPR_INCEMAIL1", 64);
break;
case 73:
StringCopy(&Var19, "PROPR_INCEMAIL3", 64);
break;
case 74:
StringCopy(&Var19, "PROPR_INCEMAIL2", 64);
break;
}
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(iParam0, "SET_DATA_SLOT");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(9);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(iVar2);
func_9(func_59(Global_42820[iParam3 /*12*/].f_3));
func_9(func_59(Global_42820[iParam3 /*12*/].f_2));
func_9(&Var3);
func_9(&Var19);
func_9(func_42(Global_42820[iParam3 /*12*/].f_2));
func_9("");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(0);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_BOOL(true);
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
iVar2++;
iVar35 = 0;
while (iVar35 < 16)
{
iVar36 = iVar35;
bVar37 = false;
switch (iParam3)
{
case 72:
if (Global_111858.f_24900[iVar36 /*4*/] == 0)
{
bVar37 = true;
}
break;
case 73:
if (Global_111858.f_24900[iVar36 /*4*/] == 1)
{
bVar37 = true;
}
break;
case 74:
if (Global_111858.f_24900[iVar36 /*4*/] == 2)
{
bVar37 = true;
}
break;
}
if (bVar37)
{
switch (iVar36)
{
case 0:
sVar38 = "ACCNA_TOWING";
break;
case 1:
sVar38 = "ACCNA_TAXI_LOT";
break;
case 2:
sVar38 = "ACCNA_ARMS";
break;
case 3:
sVar38 = "ACCNA_SONAR";
break;
case 4:
sVar38 = "ACCNA_CARMOD";
break;
case 5:
sVar38 = "ACCNA_VCINEMA";
break;
case 6:
sVar38 = "ACCNA_DCINEMA";
break;
case 7:
sVar38 = "ACCNA_MCINEMA";
break;
case 8:
sVar38 = "ACCNA_GOLF";
break;
case 9:
sVar38 = "ACCNA_CSCRAP";
break;
case 10:
sVar38 = "ACCNA_SMOKE";
break;
case 11:
sVar38 = "ACCNA_TEQUILA";
break;
case 12:
sVar38 = "ACCNA_PITCHERS";
break;
case 13:
sVar38 = "ACCNA_HEN";
break;
case 14:
sVar38 = "ACCNA_HOOKIES";
break;
case 15:
sVar38 = "ACCNA_STRP";
break;
}
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(iParam0, "SET_DATA_SLOT");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(9);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(iVar2);
GRAPHICS::BEGIN_TEXT_COMMAND_SCALEFORM_STRING("PROPR_INCEMAIL4");
HUD::ADD_TEXT_COMPONENT_SUBSTRING_TEXT_LABEL(sVar38);
HUD::ADD_TEXT_COMPONENT_INTEGER(Global_111858.f_24900[iVar36 /*4*/].f_3);
GRAPHICS::END_TEXT_COMMAND_SCALEFORM_STRING();
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
iVar2++;
iVar0 = 1;
}
iVar35++;
}
return iVar0;
}
int func_58(int iParam0, int iParam1)
{
if (iParam1 == 0)
{
if (iParam0 == 1)
{
return 1;
}
else if (iParam0 == 2)
{
return 2;
}
}
return iParam1;
}
char* func_59(int iParam0)
{
switch (iParam0)
{
case 0:
return "EMSTR_1";
case 3:
return "EMSTR_4";
case 1:
return "EMSTR_7";
case 2:
return "EMSTR_10";
case 4:
return "EMSTR_13";
case 5:
return "EMSTR_30";
case 6:
return "EMSTR_37";
case 7:
return "EMSTR_40";
case 8:
return "EMSTR_53";
case 9:
return "EMSTR_56";
case 10:
return "EMSTR_59";
case 11:
return "EMSTR_79";
case 12:
return "EMSTR_82";
case 13:
return "EMSTR_85";
case 14:
return "EMSTR_88";
case 15:
return "EMSTR_107";
case 16:
return "EMSTR_115";
case 17:
return "EMSTR_143";
case 18:
return "EMSTR_146";
case 19:
return "EMSTR_153";
case 20:
return "EMSTR_158";
case 21:
return "EMSTR_164";
case 22:
return "EMSTR_183";
case 23:
return "EMSTR_188";
case 24:
return "EMSTR_191";
case 25:
return "EMSTR_207";
case 26:
return "EMSTR_220";
case 27:
return "EMSTR_227";
case 28:
return "EMSTR_234";
case 29:
return "EMSTR_243";
case 30:
return "EMSTR_250";
case 31:
return "EMSTR_263";
case 32:
return "EMSTR_270";
case 33:
return "EMSTR_320";
case 34:
return "EMSTR_341";
case 35:
return "EMSTR_349";
case 36:
return "EMSTR_353";
case 37:
return "EMSTR_358";
case 38:
return "EMSTR_361";
case 39:
return "EMSTR_370";
case 40:
return "EMSTR_377";
case 41:
return "EMSTR_380";
case 42:
return "EMSTR_383";
case 43:
return "EMSTR_385";
case 44:
return "EMSTR_388";
case 45:
return "EMSTR_391";
case 46:
return "EMSTR_394";
case 47:
return "EMSTR_397";
case 48:
return "EMSTR_400";
case 49:
return "EMSTR_403";
case 50:
return "EMSTR_406";
case 51:
return "EMSTR_409";
case 52:
return "EMSTR_412";
case 53:
return "EMSTR_415";
case 54:
return "EMSTR_466";
case 55:
return "EMSTR_469";
case 56:
return "EMSTR_490";
case 57:
return "EMSTR_493";
case 58:
return "EMSTR_496";
case 59:
return "EMSTR_499";
case 60:
return "EMSTR_502";
case 61:
return "EMSTR_505";
case 62:
return "EMSTR_508";
case 63:
return "EMSTR_641";
case 64:
return "EMSTR_644";
case 65:
return "EMSTR_653";
default:
}
return "NULL";
}
void func_60(int iParam0)
{
switch (func_78())
{
case 0:
Global_42812 = (Global_42812 + iParam0);
if (Global_42812 < 0)
{
Global_42812 = 0;
}
break;
case 2:
Global_42814 = (Global_42814 + iParam0);
if (Global_42814 < 0)
{
Global_42814 = 0;
}
break;
case 1:
Global_42813 = (Global_42813 + iParam0);
if (Global_42813 < 0)
{
Global_42813 = 0;
}
break;
default:
break;
}
}
void func_61(int iParam0, int iParam1)
{
int iVar0;
int iVar1;
int iVar2;
int iVar3;
int iVar4;
int iVar5;
bool bVar6;
int iVar7;
int iVar8;
iVar0 = -1;
switch (iParam0)
{
case 0:
iVar0 = 0;
break;
case 1:
iVar0 = 1;
break;
case 2:
iVar0 = 2;
break;
}
if (iVar0 == -1)
{
return;
}
iVar1 = ((Global_51758[iVar0 /*120*/] - 1) - iParam1);
while (iVar1 >= 16)
{
iVar1 = (iVar1 - 16);
}
iVar2 = iVar1;
iVar3 = Global_51758[iVar0 /*120*/].f_18[iVar2];
iVar4 = Global_51758[iVar0 /*120*/].f_1[iVar2];
iVar5 = -1;
bVar6 = Global_51758[iVar0 /*120*/].f_86[iVar2];
if (!bVar6)
{
iVar5 = Global_46145[iVar3 /*46*/].f_32[iVar4];
}
else
{
iVar7 = -1;
iVar8 = 0;
iVar8 = 0;
while (iVar8 < 7)
{
if (Global_52120[iVar8 /*203*/].f_1 == iVar3)
{
iVar7 = iVar8;
}
iVar8++;
}
if (iVar7 == -1)
{
return;
}
iVar5 = Global_52120[iVar7 /*203*/].f_10[iVar4 /*48*/];
}
if (!func_62(iVar5))
{
return;
}
if (Global_52119 != -1)
{
GRAPHICS::SET_STREAMED_TEXTURE_DICT_AS_NO_LONGER_NEEDED(func_16(Global_52119));
}
Global_52119 = iVar5;
GRAPHICS::REQUEST_STREAMED_TEXTURE_DICT(func_16(iVar5), false);
while (!GRAPHICS::HAS_STREAMED_TEXTURE_DICT_LOADED(func_16(iVar5)))
{
SYSTEM::WAIT(100);
}
}
int func_62(int iParam0)
{
switch (iParam0)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 12:
case 13:
case 14:
case 15:
case 64:
case 65:
case 66:
case 75:
case 76:
case 77:
case 78:
case 80:
case 81:
case 82:
case 83:
case 205:
case 209:
case 212:
case 238:
return 1;
default:
}
return 0;
}
void func_63()
{
int iVar0;
iVar0 = 0;
iVar0 = 0;
while (iVar0 < 3)
{
if (Global_42815[iVar0] != -1)
{
HUD::THEFEED_REMOVE_ITEM(Global_42815[iVar0]);
Global_42815[iVar0] = -1;
}
iVar0++;
}
Global_42819 = 0;
}
void func_64(int iParam0, char* sParam1, float fParam2, float fParam3, float fParam4, float fParam5, float fParam6)
{
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(iParam0, sParam1);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(SYSTEM::ROUND(fParam2));
if (fParam3 != -1f)
{
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(SYSTEM::ROUND(fParam3));
}
if (fParam4 != -1f)
{
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(SYSTEM::ROUND(fParam4));
}
if (fParam5 != -1f)
{
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(SYSTEM::ROUND(fParam5));
}
if (fParam6 != -1f)
{
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(SYSTEM::ROUND(fParam6));
}
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
}
void func_65(int iParam0, char* sParam1, char* sParam2, char* sParam3, char* sParam4, char* sParam5, char* sParam6)
{
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(iParam0, sParam1);
func_9(sParam2);
if (!MISC::IS_STRING_NULL_OR_EMPTY(sParam3))
{
func_9(sParam3);
}
if (!MISC::IS_STRING_NULL_OR_EMPTY(sParam4))
{
func_9(sParam4);
}
if (!MISC::IS_STRING_NULL_OR_EMPTY(sParam5))
{
func_9(sParam5);
}
if (!MISC::IS_STRING_NULL_OR_EMPTY(sParam6))
{
func_9(sParam6);
}
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
}
int func_66(int iParam0, int iParam1)
{
int iVar0;
int iVar1;
int iVar2;
int iVar3;
int iVar4;
int iVar5;
int iVar6;
int iVar7;
char* sVar8;
int iVar12;
int iVar13;
int iVar14;
int iVar15;
int iVar16;
int iVar17;
struct<16> Var18;
func_67(iParam1);
iVar0 = -1;
switch (iParam1)
{
case 0:
iVar0 = 0;
break;
case 1:
iVar0 = 1;
break;
case 2:
iVar0 = 2;
break;
}
if (iVar0 == -1)
{
return 0;
}
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(iParam0, "SET_DATA_SLOT_EMPTY");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(8);
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
if (Global_51758[iVar0 /*120*/] < 1)
{
return 0;
}
iVar1 = (Global_51758[iVar0 /*120*/] - 1);
while (iVar1 >= 16)
{
iVar1 = (iVar1 - 16);
}
iVar2 = Global_51758[iVar0 /*120*/];
if (iVar2 > 16)
{
iVar2 = 16;
}
if (iVar1 < 0 || iVar1 > 15)
{
return 0;
}
iVar3 = 0;
iVar3 = 0;
while (iVar3 < iVar2)
{
if (!Global_51758[iVar0 /*120*/].f_86[iVar1])
{
iVar4 = Global_51758[iVar0 /*120*/].f_18[iVar1];
iVar5 = Global_51758[iVar0 /*120*/].f_1[iVar1];
iVar6 = Global_46145[iVar4 /*46*/].f_32[iVar5];
iVar7 = 0;
if (Global_51758[iVar0 /*120*/].f_69[iVar1])
{
iVar7 = 1;
}
if (iVar7 == 1)
{
if (Global_42820[iVar6 /*12*/].f_4 > 0)
{
if (Global_51758[iVar0 /*120*/].f_35[iVar1] == 0)
{
iVar7 = 2;
}
}
}
MemCopy(&sVar8, {func_32(Global_42820[iVar6 /*12*/])}, 4);
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(iParam0, "SET_DATA_SLOT");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(8);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(iVar3);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(iVar7);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(0);
func_9(func_59(Global_42820[iVar6 /*12*/].f_2));
func_9(&sVar8);
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
}
else
{
iVar12 = Global_51758[iVar0 /*120*/].f_18[iVar1];
iVar13 = -1;
iVar14 = 0;
iVar14 = 0;
while (iVar14 < 7)
{
if (Global_52120[iVar14 /*203*/].f_1 == iVar12)
{
iVar13 = iVar14;
}
iVar14++;
}
if (iVar13 == -1)
{
return 1;
}
else
{
iVar15 = Global_51758[iVar0 /*120*/].f_1[iVar1];
iVar16 = 0;
if (Global_51758[iVar0 /*120*/].f_69[iVar1])
{
iVar16 = 1;
}
iVar17 = Global_52120[iVar13 /*203*/].f_10[iVar15 /*48*/];
if (iVar16 == 1)
{
if (Global_42820[iVar17 /*12*/].f_4 > 0)
{
if (Global_51758[iVar0 /*120*/].f_35[iVar1] == 0)
{
iVar16 = 2;
}
}
}
Var18 = { func_32(Global_42820[iVar17 /*12*/]) };
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(iParam0, "SET_DATA_SLOT");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(8);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(iVar3);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(iVar16);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(0);
func_9(func_59(Global_42820[iVar17 /*12*/].f_2));
func_9(&Var18);
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
}
}
iVar1 = (iVar1 - 1);
if (iVar1 < 0)
{
iVar1 = 15;
}
iVar3++;
}
return iVar2;
}
void func_67(int iParam0)
{
int iVar0;
int iVar1;
int iVar2;
int iVar3;
struct<104> Var4;
int iVar124;
bool bVar125;
int iVar126;
int iVar127;
int iVar128;
int iVar129;
iVar0 = -1;
switch (iParam0)
{
case 0:
iVar0 = 0;
break;
case 1:
iVar0 = 1;
break;
case 2:
iVar0 = 2;
break;
}
if (iVar0 == -1)
{
return;
}
if (Global_51758[iVar0 /*120*/] < 1)
{
return;
}
iVar1 = (Global_51758[iVar0 /*120*/] - 1);
while (iVar1 >= 16)
{
iVar1 = (iVar1 - 16);
}
iVar2 = Global_51758[iVar0 /*120*/];
if (iVar2 > 16)
{
iVar2 = 16;
}
if (iVar1 < 0 || iVar1 > 15)
{
return;
}
iVar3 = (iVar1 - (iVar2 - 1));
if (iVar3 < 0)
{
iVar3 = (16 + iVar3);
}
Var4.f_1 = 16;
Var4.f_18 = 16;
Var4.f_35 = 16;
Var4.f_52 = 16;
Var4.f_69 = 16;
Var4.f_86 = 16;
Var4.f_103 = 16;
iVar124 = 0;
while (iVar124 < iVar2)
{
bVar125 = true;
if (Global_51758[iVar0 /*120*/].f_103[iVar3])
{
bVar125 = false;
}
if (Global_51758[iVar0 /*120*/].f_86[iVar3])
{
iVar126 = Global_51758[iVar0 /*120*/].f_18[iVar3];
iVar127 = -1;
iVar128 = 0;
iVar128 = 0;
while (iVar128 < 7)
{
if (Global_52120[iVar128 /*203*/].f_1 == iVar126)
{
iVar127 = iVar128;
}
iVar128++;
}
if (iVar127 == -1)
{
bVar125 = false;
}
}
if (bVar125)
{
iVar129 = Var4;
Var4.f_1[iVar129] = Global_51758[iVar0 /*120*/].f_1[iVar3];
Var4.f_18[iVar129] = Global_51758[iVar0 /*120*/].f_18[iVar3];
Var4.f_35[iVar129] = Global_51758[iVar0 /*120*/].f_35[iVar3];
Var4.f_52[iVar129] = Global_51758[iVar0 /*120*/].f_52[iVar3];
Var4.f_69[iVar129] = Global_51758[iVar0 /*120*/].f_69[iVar3];
Var4.f_86[iVar129] = Global_51758[iVar0 /*120*/].f_86[iVar3];
Var4++;
}
iVar3++;
if (iVar3 == 16)
{
iVar3 = 0;
}
iVar124++;
}
Global_51758[iVar0 /*120*/] = Var4;
iVar124 = 0;
while (iVar124 < 16)
{
Global_51758[iVar0 /*120*/].f_103[iVar124] = 0;
Global_51758[iVar0 /*120*/].f_1[iVar124] = Var4.f_1[iVar124];
Global_51758[iVar0 /*120*/].f_18[iVar124] = Var4.f_18[iVar124];
Global_51758[iVar0 /*120*/].f_35[iVar124] = Var4.f_35[iVar124];
Global_51758[iVar0 /*120*/].f_52[iVar124] = Var4.f_52[iVar124];
Global_51758[iVar0 /*120*/].f_69[iVar124] = Var4.f_69[iVar124];
Global_51758[iVar0 /*120*/].f_86[iVar124] = Var4.f_86[iVar124];
iVar124++;
}
}
void func_68()
{
float fVar0;
fVar0 = func_69(Local_50, Local_47, -90f, 0f, 90f, Global_19641, 350f, 0);
if (Global_8355 == 0)
{
MOBILE::SET_MOBILE_PHONE_SCALE((500f + (75f * (1f - fVar0))));
}
if (fVar0 >= 1f)
{
Global_22038 = 0;
func_1(0);
func_4();
iLocal_18 = 0;
}
}
float func_69(struct<3> Param0, struct<3> Param3, struct<3> Param6, struct<3> Param9, float fParam12, bool bParam13)
{
struct<2> Var0;
float fVar3;
float fVar4;
float fVar5;
if (Global_4271303 == 0)
{
if (MISC::IS_BIT_SET(Global_7551, 14) && Global_19681.f_1 < 4)
{
MOBILE::GET_MOBILE_PHONE_POSITION(&Var0);
if (Global_19634[Global_19626 /*3*/].f_1 == Var0.f_1)
{
Global_4271303 = 1;
}
}
}
if (func_72() && Global_4271303 == 0)
{
return 2f;
}
if (iLocal_18 == 0)
{
iLocal_18 = MISC::GET_GAME_TIMER();
}
fVar3 = func_71((SYSTEM::TO_FLOAT((MISC::GET_GAME_TIMER() - iLocal_18)) / fParam12), 0f, 1f);
if (fVar3 < 1f)
{
fVar4 = fVar3;
if (bParam13)
{
fVar4 = (fVar4 - 1f);
fVar5 = 0.670158f;
fVar4 = (((fVar4 * fVar4) * (((fVar5 + 1f) * fVar4) + fVar5)) + 1f);
}
else
{
fVar4 = SYSTEM::SIN((fVar3 * 90f));
}
Global_19609 = { func_70(Param0, Param3, fVar4) };
Global_19612 = { func_70(Param6, Param9, fVar4) };
}
else
{
Global_19609 = { Param3 };
Global_19612 = { Param9 };
}
MOBILE::SET_MOBILE_PHONE_POSITION(Global_19609);
MOBILE::SET_MOBILE_PHONE_ROTATION(Global_19612, 0);
return fVar3;
}
Vector3 func_70(struct<3> Param0, struct<3> Param3, float fParam6)
{
return Param0 + Param3 - Param0 * Vector(fParam6, fParam6, fParam6);
}
float func_71(float fParam0, float fParam1, float fParam2)
{
if (fParam0 > fParam2)
{
return fParam2;
}
else if (fParam0 < fParam1)
{
return fParam1;
}
return fParam0;
}
int func_72()
{
int iVar0;
int iVar1;
int iVar2;
int iVar3;
if (!ENTITY::IS_ENTITY_DEAD(PLAYER::PLAYER_PED_ID(), false))
{
if (Global_19681.f_1 == 10 || Global_19681.f_1 == 9)
{
if (Global_19624 == 0)
{
if (Global_6866 != 128)
{
if (!PED::IS_PED_IN_ANY_VEHICLE(PLAYER::PLAYER_PED_ID(), false))
{
if (Global_21005 != 2)
{
}
}
}
}
}
if (func_15(14))
{
return 0;
}
if (PED::IS_PED_IN_COVER(PLAYER::PLAYER_PED_ID(), false))
{
return 0;
}
if (PED::IS_PED_IN_ANY_VEHICLE(PLAYER::PLAYER_PED_ID(), false))
{
if (!CAM::_IS_IN_VEHICLE_CAM_DISABLED())
{
if (ENTITY::IS_ENTITY_IN_WATER(PED::GET_VEHICLE_PED_IS_IN(PLAYER::PLAYER_PED_ID(), false)))
{
return 0;
}
}
}
if (((PED::IS_PED_SWIMMING(PLAYER::PLAYER_PED_ID()) || PED::IS_PED_SWIMMING_UNDER_WATER(PLAYER::PLAYER_PED_ID())) || PLAYER::IS_PLAYER_CLIMBING(PLAYER::PLAYER_ID())) || (PED::IS_PED_HANGING_ON_TO_VEHICLE(PLAYER::PLAYER_PED_ID()) && !(MISC::IS_BIT_SET(Global_4456448.f_37, 17) && (NETWORK::NETWORK_IS_ACTIVITY_SESSION() || Global_1655232))))
{
return 0;
}
if (Global_110906)
{
return 0;
}
}
if (Global_76833)
{
return 0;
}
iVar2 = 0;
iVar0 = CAM::_0x19CAFA3C87F7C2FF();
iVar1 = CAM::_0xEE778F8C7E1142E2(iVar0);
if (iVar1 == 4 && (iVar0 == 0 || CAM::_IS_IN_VEHICLE_CAM_DISABLED()))
{
iVar2 = 1;
if (!ENTITY::IS_ENTITY_DEAD(PLAYER::PLAYER_PED_ID(), false))
{
if (PED::IS_PED_IN_ANY_VEHICLE(PLAYER::PLAYER_PED_ID(), false))
{
iVar3 = PED::GET_VEHICLE_PED_IS_IN(PLAYER::PLAYER_PED_ID(), false);
if ((((((((VEHICLE::IS_THIS_MODEL_A_BIKE(ENTITY::GET_ENTITY_MODEL(iVar3)) || VEHICLE::IS_THIS_MODEL_A_BICYCLE(ENTITY::GET_ENTITY_MODEL(iVar3))) || VEHICLE::IS_THIS_MODEL_A_QUADBIKE(ENTITY::GET_ENTITY_MODEL(iVar3))) || ENTITY::GET_ENTITY_MODEL(iVar3) == joaat("seashark")) || ENTITY::GET_ENTITY_MODEL(iVar3) == joaat("seashark2")) || ENTITY::GET_ENTITY_MODEL(iVar3) == joaat("rhino")) || ENTITY::GET_ENTITY_MODEL(iVar3) == joaat("submersible")) || ENTITY::GET_ENTITY_MODEL(iVar3) == joaat("submersible2")) || ENTITY::GET_ENTITY_MODEL(iVar3) == joaat("toro"))
{
iVar2 = 0;
}
}
}
}
if (Global_4271302 || iVar2 == 1)
{
if (SCRIPT::_GET_NUMBER_OF_REFERENCES_OF_SCRIPT_WITH_NAME_HASH(joaat("apptrackify")) > 0 || Global_111858.f_14047.f_89)
{
if (SCRIPT::_GET_NUMBER_OF_REFERENCES_OF_SCRIPT_WITH_NAME_HASH(joaat("michael2")) > 0)
{
return 1;
}
else
{
return 0;
}
}
else
{
return 1;
}
}
return 0;
}
void func_73()
{
float fVar0;
fVar0 = func_69(Local_47, Local_50, Global_19641, -90f, 0f, 90f, 350f, 0);
if (Global_8355 == 0)
{
if (MISC::IS_PC_VERSION())
{
if (!func_74())
{
MOBILE::SET_MOBILE_PHONE_SCALE((500f + (75f * fVar0)));
}
}
else
{
MOBILE::SET_MOBILE_PHONE_SCALE((500f + (75f * fVar0)));
}
}
if (fVar0 >= 1f)
{
func_1(1);
Global_22039 = 0;
iLocal_18 = 0;
}
}
int func_74()
{
int iVar0;
int iVar1;
iVar0 = CAM::_0x19CAFA3C87F7C2FF();
iVar1 = CAM::_0xEE778F8C7E1142E2(iVar0);
if (iVar1 == 4)
{
return 1;
}
return 0;
}
void func_75(bool bParam0)
{
var uVar0;
var uVar1;
var uVar2;
var uVar3;
if (MISC::IS_XBOX360_VERSION() || MISC::IS_DURANGO_VERSION())
{
HUD::GET_HUD_COLOUR(9, &uVar0, &uVar1, &uVar2, &uVar3);
}
else
{
HUD::GET_HUD_COLOUR(126, &uVar0, &uVar1, &uVar2, &uVar3);
}
if (bParam0)
{
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(Global_19662, "SET_SOFT_KEYS");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(1);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_BOOL(true);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(16);
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
}
else
{
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(Global_19662, "SET_SOFT_KEYS");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(1);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_BOOL(false);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(16);
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
}
}
void func_76(bool bParam0)
{
var uVar0;
var uVar1;
var uVar2;
var uVar3;
if (MISC::IS_XBOX360_VERSION() || MISC::IS_DURANGO_VERSION())
{
HUD::GET_HUD_COLOUR(6, &uVar0, &uVar1, &uVar2, &uVar3);
}
else
{
HUD::GET_HUD_COLOUR(6, &uVar0, &uVar1, &uVar2, &uVar3);
}
if (bParam0)
{
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(Global_19662, "SET_SOFT_KEYS");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(3);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_BOOL(true);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(4);
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
}
else
{
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(Global_19662, "SET_SOFT_KEYS");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(3);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_BOOL(false);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(4);
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
}
}
void func_77(bool bParam0)
{
var uVar0;
var uVar1;
var uVar2;
var uVar3;
if (MISC::IS_XBOX360_VERSION() || MISC::IS_DURANGO_VERSION())
{
HUD::GET_HUD_COLOUR(18, &uVar0, &uVar1, &uVar2, &uVar3);
}
else
{
HUD::GET_HUD_COLOUR(9, &uVar0, &uVar1, &uVar2, &uVar3);
}
if (bParam0)
{
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(Global_19662, "SET_SOFT_KEYS");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(2);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_BOOL(true);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(2);
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
}
else
{
GRAPHICS::BEGIN_SCALEFORM_MOVIE_METHOD(Global_19662, "SET_SOFT_KEYS");
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(2);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_BOOL(false);
GRAPHICS::SCALEFORM_MOVIE_METHOD_ADD_PARAM_INT(2);
GRAPHICS::END_SCALEFORM_MOVIE_METHOD();
}
}
int func_78()
{
func_79();
return Global_111858.f_2359.f_539.f_4321;
}
void func_79()
{
int iVar0;
if (ENTITY::DOES_ENTITY_EXIST(PLAYER::PLAYER_PED_ID()))
{
if (func_82(Global_111858.f_2359.f_539.f_4321) != ENTITY::GET_ENTITY_MODEL(PLAYER::PLAYER_PED_ID()))
{
iVar0 = func_81(PLAYER::PLAYER_PED_ID());
if (func_80(iVar0) && (!func_15(14) || Global_110809))
{
if (Global_111858.f_2359.f_539.f_4321 != iVar0 && func_80(Global_111858.f_2359.f_539.f_4321))
{
Global_111858.f_2359.f_539.f_4322 = Global_111858.f_2359.f_539.f_4321;
}
Global_111858.f_2359.f_539.f_4323 = iVar0;
Global_111858.f_2359.f_539.f_4321 = iVar0;
return;
}
}
else
{
if (Global_111858.f_2359.f_539.f_4321 != 145)
{
Global_111858.f_2359.f_539.f_4323 = Global_111858.f_2359.f_539.f_4321;
}
return;
}
}
Global_111858.f_2359.f_539.f_4321 = 145;
}
bool func_80(int iParam0)
{
return iParam0 < 3;
}
int func_81(int iParam0)
{
int iVar0;
int iVar1;
if (ENTITY::DOES_ENTITY_EXIST(iParam0))
{
iVar1 = ENTITY::GET_ENTITY_MODEL(iParam0);
iVar0 = 0;
while (iVar0 <= 2)
{
if (func_82(iVar0) == iVar1)
{
return iVar0;
}
iVar0++;
}
}
return 145;
}
int func_82(int iParam0)
{
if (func_80(iParam0))
{
return func_83(iParam0);
}
else if (iParam0 != 145)
{
}
return 0;
}
var func_83(int iParam0)
{
return Global_1848[iParam0 /*29*/];
}
| 20.344051 | 561 | 0.620426 | [
"vector"
] |
d62fb12530b2443150c3eaf1a7fc1be8526141be | 20,005 | c | C | Sys/FatFs/samples/stm32/main.c | mosxuqian/CodeCollection | 40622739f7fcb7326ee85db3bf5ecf1148c3aa08 | [
"Apache-2.0"
] | 1 | 2021-10-09T03:31:49.000Z | 2021-10-09T03:31:49.000Z | Sys/FatFs/samples/stm32/main.c | zzilla/CodeCollection | 40622739f7fcb7326ee85db3bf5ecf1148c3aa08 | [
"Apache-2.0"
] | null | null | null | Sys/FatFs/samples/stm32/main.c | zzilla/CodeCollection | 40622739f7fcb7326ee85db3bf5ecf1148c3aa08 | [
"Apache-2.0"
] | 4 | 2017-05-20T02:52:51.000Z | 2019-04-03T01:01:47.000Z | /*----------------------------------------------------------------------*/
/* FAT file system sample project for FatFs (C)ChaN, 2014 */
/*----------------------------------------------------------------------*/
#include <string.h>
#include "STM32F100.h"
#include "uart_32f1.h"
#include "rtc_32f1.h"
#include "xprintf.h"
#include "ff.h"
#include "diskio.h"
extern void disk_timerproc (void);
DWORD AccSize; /* Work register for fs command */
WORD AccFiles, AccDirs;
FILINFO Finfo;
#if _USE_LFN
char Lfname[512];
#endif
char Line[256]; /* Console input buffer */
BYTE Buff[4096] __attribute__ ((aligned (4))) ; /* Working buffer */
FATFS FatFs; /* File system object for each logical drive */
FIL File[2]; /* File objects */
DIR Dir; /* Directory object */
volatile UINT Timer;
/*---------------------------------------------*/
/* 1kHz timer process */
/*---------------------------------------------*/
void SysTick_Handler (void)
{
static uint16_t led;
Timer++; /* Increment performance counter */
if (++led >= 500) {
led = 0;
GPIOC_ODR ^= _BV(9)|_BV(8); /* Flip Green/Blue LED state */
}
disk_timerproc(); /* Disk timer process */
}
/*---------------------------------------------------------*/
/* User provided RTC function for FatFs module */
/*---------------------------------------------------------*/
/* This is a real time clock service to be called back */
/* from FatFs module. */
#if !_FS_NORTC && !_FS_READONLY
DWORD get_fattime (void)
{
RTCTIME rtc;
/* Get local time */
if (!rtc_gettime(&rtc)) return 0;
/* Pack date and time into a DWORD variable */
return ((DWORD)(rtc.year - 1980) << 25)
| ((DWORD)rtc.month << 21)
| ((DWORD)rtc.mday << 16)
| ((DWORD)rtc.hour << 11)
| ((DWORD)rtc.min << 5)
| ((DWORD)rtc.sec >> 1);
}
#endif
/*--------------------------------------------------------------------------*/
/* Monitor */
/*--------------------------------------------------------------------------*/
static
FRESULT scan_files (
char* path /* Pointer to the path name working buffer */
)
{
DIR dirs;
FRESULT res;
BYTE i;
char *fn;
if ((res = f_opendir(&dirs, path)) == FR_OK) {
i = strlen(path);
while (((res = f_readdir(&dirs, &Finfo)) == FR_OK) && Finfo.fname[0]) {
if (_FS_RPATH && Finfo.fname[0] == '.') continue;
#if _USE_LFN
fn = *Finfo.lfname ? Finfo.lfname : Finfo.fname;
#else
fn = Finfo.fname;
#endif
if (Finfo.fattrib & AM_DIR) {
AccDirs++;
*(path+i) = '/'; strcpy(path+i+1, fn);
res = scan_files(path);
*(path+i) = '\0';
if (res != FR_OK) break;
} else {
/* xprintf("%s/%s\n", path, fn); */
AccFiles++;
AccSize += Finfo.fsize;
}
}
}
return res;
}
static
void put_rc (FRESULT rc)
{
const char *str =
"OK\0" "DISK_ERR\0" "INT_ERR\0" "NOT_READY\0" "NO_FILE\0" "NO_PATH\0"
"INVALID_NAME\0" "DENIED\0" "EXIST\0" "INVALID_OBJECT\0" "WRITE_PROTECTED\0"
"INVALID_DRIVE\0" "NOT_ENABLED\0" "NO_FILE_SYSTEM\0" "MKFS_ABORTED\0" "TIMEOUT\0"
"LOCKED\0" "NOT_ENOUGH_CORE\0" "TOO_MANY_OPEN_FILES\0";
FRESULT i;
for (i = 0; i != rc && *str; i++) {
while (*str++) ;
}
xprintf("rc=%u FR_%s\n", (UINT)rc, str);
}
static
const char HelpMsg[] =
"[Disk contorls]\n"
" di <pd#> - Initialize disk\n"
" dd [<pd#> <lba>] - Dump a secrtor\n"
" ds <pd#> - Show disk status\n"
"[Buffer controls]\n"
" bd <ofs> - Dump working buffer\n"
" be <ofs> [<data>] ... - Edit working buffer\n"
" br <pd#> <lba> [<count>] - Read disk into working buffer\n"
" bw <pd#> <lba> [<count>] - Write working buffer into disk\n"
" bf <val> - Fill working buffer\n"
"[File system controls]\n"
" fi <ld#> [<mount>]- Force initialized the volume\n"
" fs [<path>] - Show volume status\n"
" fl [<path>] - Show a directory\n"
" fo <mode> <file> - Open a file\n"
" fc - Close the file\n"
" fe <ofs> - Move fp in normal seek\n"
" fd <len> - Read and dump the file\n"
" fr <len> - Read the file\n"
" fw <len> <val> - Write to the file\n"
" fn <org.name> <new.name> - Rename an object\n"
" fu <name> - Unlink an object\n"
" fv - Truncate the file at current fp\n"
" fk <name> - Create a directory\n"
" fa <atrr> <mask> <object name> - Change attribute of an object\n"
" ft <year> <month> <day> <hour> <min> <sec> <name> - Change timestamp of an object\n"
" fx <src.file> <dst.file> - Copy a file\n"
" fg <path> - Change current directory\n"
" fq - Show current directory\n"
" fb <name> - Set volume label\n"
" fm <ld#> <rule> <csize> - Create file system\n"
" fz [<len>] - Change/Show R/W length for fr/fw/fx command\n"
"[Misc commands]\n"
" md[b|h|w] <addr> [<count>] - Dump memory\n"
" mf <addr> <value> <count> - Fill memory\n"
" me[b|h|w] <addr> [<value> ...] - Edit memory\n"
" t [<year> <mon> <mday> <hour> <min> <sec>] - Set/Show RTC\n"
"\n";
int main (void)
{
char *ptr, *ptr2;
long p1, p2, p3;
BYTE res, b, drv = 0;
UINT s1, s2, cnt, blen = sizeof Buff;
static const BYTE ft[] = {0, 12, 16, 32};
static const char days[] = "Sun\0Mon\0Tue\0Wed\0Thu\0Fri\0Sat";
DWORD ofs = 0, sect = 0, blk[2];
FATFS *fs;
RTCTIME rtc;
/* Enable LED indicators on the STM32VL Discovery board */
__enable_peripheral(IOPCEN);
__gpio_conf_bit(GPIOC, 8, OUT_PP); /* PC8:Blue LED */
__gpio_conf_bit(GPIOC, 9, OUT_PP); /* PC9:Green LED */
GPIOC_BSRR = _BV(8); /* Blue LED on */
/* Enable SysTick timer as 1 ms interval timer */
SYST_RVR = 24000000 / 1000 - 1;
SYST_CVR = 24000000 / 1000 - 1;
SYST_CSR = 0x07;
/* Enable UART1 and attach it to xprintf module for console */
uart1_init(115200);
xdev_out(uart1_putc);
xdev_in(uart1_getc);
xputs("STM32F100 test monitor\n");
xputs(_USE_LFN ? "LFN Enabled" : "LFN Disabled");
xprintf(", Code page: %u\n", _CODE_PAGE);
/* Initiazlize RTC */
if (rtc_initialize()) {
rtc_gettime(&rtc);
xprintf("Current time is %u/%u/%u %2u:%02u:%02u.\n", rtc.year, rtc.month, rtc.mday, rtc.hour, rtc.min, rtc.sec);
} else {
xputs("RTC is not available.\n");
}
for (;;) {
xputc('>');
xgets(Line, sizeof Line);
ptr = Line;
switch (*ptr++) {
case '?' : /* Show Command List */
xputs(HelpMsg);
break;
case 'm' : /* Memory dump/fill/edit */
switch (*ptr++) {
case 'd' : /* md[b|h|w] <address> [<count>] - Dump memory */
switch (*ptr++) {
case 'w': p3 = DW_LONG; break;
case 'h': p3 = DW_SHORT; break;
default: p3 = DW_CHAR;
}
if (!xatoi(&ptr, &p1)) break;
if (!xatoi(&ptr, &p2)) p2 = 128 / p3;
for (ptr = (char*)p1; p2 >= 16 / p3; ptr += 16, p2 -= 16 / p3)
put_dump(ptr, (DWORD)ptr, 16 / p3, p3);
if (p2) put_dump((BYTE*)ptr, (UINT)ptr, p2, p3);
break;
case 'f' : /* mf <address> <value> <count> - Fill memory */
if (!xatoi(&ptr, &p1) || !xatoi(&ptr, &p2) || !xatoi(&ptr, &p3)) break;
while (p3--) {
*(BYTE*)p1 = (BYTE)p2;
p1++;
}
break;
case 'e' : /* me[b|h|w] <address> [<value> ...] - Edit memory */
switch (*ptr++) { /* Get data width */
case 'w': p3 = DW_LONG; break;
case 'h': p3 = DW_SHORT; break;
default: p3 = DW_CHAR;
}
if (!xatoi(&ptr, &p1)) break; /* Get start address */
if (xatoi(&ptr, &p2)) { /* 2nd parameter is given (direct mode) */
do {
switch (p3) {
case DW_LONG: *(DWORD*)p1 = (DWORD)p2; break;
case DW_SHORT: *(WORD*)p1 = (WORD)p2; break;
default: *(BYTE*)p1 = (BYTE)p2;
}
p1 += p3;
} while (xatoi(&ptr, &p2)); /* Get next value */
break;
}
for (;;) { /* 2nd parameter is not given (interactive mode) */
switch (p3) {
case DW_LONG: xprintf("%08X 0x%08X-", p1, *(DWORD*)p1); break;
case DW_SHORT: xprintf("%08X 0x%04X-", p1, *(WORD*)p1); break;
default: xprintf("%08X 0x%02X-", p1, *(BYTE*)p1);
}
ptr = Line; xgets(ptr, sizeof Line);
if (*ptr == '.') break;
if ((BYTE)*ptr >= ' ') {
if (!xatoi(&ptr, &p2)) continue;
switch (p3) {
case DW_LONG: *(DWORD*)p1 = (DWORD)p2; break;
case DW_SHORT: *(WORD*)p1 = (WORD)p2; break;
default: *(BYTE*)p1 = (BYTE)p2;
}
}
p1 += p3;
}
break;
}
break;
case 'd' : /* Disk I/O layer controls */
switch (*ptr++) {
case 'd' : /* dd [<pd#> <sect>] - Dump secrtor */
if (!xatoi(&ptr, &p1)) {
p1 = drv; p2 = sect;
} else {
if (!xatoi(&ptr, &p2)) break;
}
drv = (BYTE)p1; sect = p2;
res = disk_read(drv, Buff, sect, 1);
if (res) { xprintf("rc=%d\n", (WORD)res); break; }
xprintf("PD#:%u LBA:%lu\n", drv, sect++);
for (ptr=(char*)Buff, ofs = 0; ofs < 0x200; ptr += 16, ofs += 16)
put_dump((BYTE*)ptr, ofs, 16, DW_CHAR);
break;
case 'i' : /* di <pd#> - Initialize disk */
if (!xatoi(&ptr, &p1)) break;
xprintf("rc=%d\n", (WORD)disk_initialize((BYTE)p1));
break;
case 's' : /* ds <pd#> - Show disk status */
if (!xatoi(&ptr, &p1)) break;
if (disk_ioctl((BYTE)p1, GET_SECTOR_COUNT, &p2) == RES_OK)
{ xprintf("Drive size: %lu sectors\n", p2); }
if (disk_ioctl((BYTE)p1, GET_BLOCK_SIZE, &p2) == RES_OK)
{ xprintf("Block size: %lu sectors\n", p2); }
if (disk_ioctl((BYTE)p1, MMC_GET_TYPE, &b) == RES_OK)
{ xprintf("Media type: %u\n", b); }
if (disk_ioctl((BYTE)p1, MMC_GET_CSD, Buff) == RES_OK)
{ xputs("CSD:\n"); put_dump(Buff, 0, 16, DW_CHAR); }
if (disk_ioctl((BYTE)p1, MMC_GET_CID, Buff) == RES_OK)
{ xputs("CID:\n"); put_dump(Buff, 0, 16, DW_CHAR); }
if (disk_ioctl((BYTE)p1, MMC_GET_OCR, Buff) == RES_OK)
{ xputs("OCR:\n"); put_dump(Buff, 0, 4, DW_CHAR); }
if (disk_ioctl((BYTE)p1, MMC_GET_SDSTAT, Buff) == RES_OK) {
xputs("SD Status:\n");
for (s1 = 0; s1 < 64; s1 += 16) put_dump(Buff+s1, s1, 16, DW_CHAR);
}
break;
case 'c' : /* Disk ioctl */
switch (*ptr++) {
case 's' : /* dcs <pd#> - CTRL_SYNC */
if (!xatoi(&ptr, &p1)) break;
xprintf("rc=%d\n", disk_ioctl((BYTE)p1, CTRL_SYNC, 0));
break;
case 'e' : /* dce <pd#> <s.lba> <e.lba> - CTRL_TRIM */
if (!xatoi(&ptr, &p1) || !xatoi(&ptr, (long*)&blk[0]) || !xatoi(&ptr, (long*)&blk[1])) break;
xprintf("rc=%d\n", disk_ioctl((BYTE)p1, CTRL_TRIM, blk));
break;
}
break;
}
break;
case 'b' : /* Buffer controls */
switch (*ptr++) {
case 'd' : /* bd <ofs> - Dump R/W buffer */
if (!xatoi(&ptr, &p1)) break;
for (ptr=(char*)&Buff[p1], ofs = p1, cnt = 32; cnt; cnt--, ptr+=16, ofs+=16)
put_dump((BYTE*)ptr, ofs, 16, DW_CHAR);
break;
case 'e' : /* be <ofs> [<data>] ... - Edit R/W buffer */
if (!xatoi(&ptr, &p1)) break;
if (xatoi(&ptr, &p2)) {
do {
Buff[p1++] = (BYTE)p2;
} while (xatoi(&ptr, &p2));
break;
}
for (;;) {
xprintf("%04X %02X-", (WORD)(p1), (WORD)Buff[p1]);
xgets(Line, sizeof Line);
ptr = Line;
if (*ptr == '.') break;
if (*ptr < ' ') { p1++; continue; }
if (xatoi(&ptr, &p2))
Buff[p1++] = (BYTE)p2;
else
xputs("???\n");
}
break;
case 'r' : /* br <pd#> <lba> [<num>] - Read disk into R/W buffer */
if (!xatoi(&ptr, &p1) || !xatoi(&ptr, &p2)) break;
if (!xatoi(&ptr, &p3)) p3 = 1;
xprintf("rc=%u\n", (WORD)disk_read((BYTE)p1, Buff, p2, p3));
break;
case 'w' : /* bw <pd#> <lba> [<num>] - Write R/W buffer into disk */
if (!xatoi(&ptr, &p1) || !xatoi(&ptr, &p2)) break;
if (!xatoi(&ptr, &p3)) p3 = 1;
xprintf("rc=%u\n", (WORD)disk_write((BYTE)p1, Buff, p2, p3));
break;
case 'f' : /* bf <val> - Fill working buffer */
if (!xatoi(&ptr, &p1)) break;
memset(Buff, (BYTE)p1, sizeof Buff);
break;
}
break;
case 'f' : /* FatFS API controls */
switch (*ptr++) {
case 'i' : /* fi [<opt>]- Initialize logical drive */
if (!xatoi(&ptr, &p2)) p2 = 0;
put_rc(f_mount(&FatFs, "", (BYTE)p2));
break;
case 's' : /* fs [<path>] - Show volume status */
while (*ptr == ' ') ptr++;
res = f_getfree(ptr, (DWORD*)&p1, &fs);
if (res) { put_rc(res); break; }
xprintf("FAT type = FAT%u\nBytes/Cluster = %lu\nNumber of FATs = %u\n"
"Root DIR entries = %u\nSectors/FAT = %lu\nNumber of clusters = %lu\n"
"Volume start (lba) = %lu\nFAT start (lba) = %lu\nDIR start (lba,clustor) = %lu\nData start (lba) = %lu\n\n",
ft[fs->fs_type & 3], (DWORD)fs->csize * 512, fs->n_fats,
fs->n_rootdir, fs->fsize, (DWORD)fs->n_fatent - 2,
fs->volbase, fs->fatbase, fs->dirbase, fs->database);
#if _USE_LABEL
res = f_getlabel(ptr, (char*)Buff, (DWORD*)&p2);
if (res) { put_rc(res); break; }
xprintf(Buff[0] ? "Volume name is %s\n" : "No volume label\n", (char*)Buff);
xprintf("Volume S/N is %04X-%04X\n", (DWORD)p2 >> 16, (DWORD)p2 & 0xFFFF);
#endif
AccSize = AccFiles = AccDirs = 0;
xprintf("...");
res = scan_files(ptr);
if (res) { put_rc(res); break; }
xprintf("\r%u files, %lu bytes.\n%u folders.\n"
"%lu KiB total disk space.\n%lu KiB available.\n",
AccFiles, AccSize, AccDirs,
(fs->n_fatent - 2) * (fs->csize / 2), (DWORD)p1 * (fs->csize / 2)
);
break;
case 'l' : /* fl [<path>] - Directory listing */
while (*ptr == ' ') ptr++;
res = f_opendir(&Dir, ptr);
if (res) { put_rc(res); break; }
p1 = s1 = s2 = 0;
for(;;) {
res = f_readdir(&Dir, &Finfo);
if ((res != FR_OK) || !Finfo.fname[0]) break;
if (Finfo.fattrib & AM_DIR) {
s2++;
} else {
s1++; p1 += Finfo.fsize;
}
xprintf("%c%c%c%c%c %u/%02u/%02u %02u:%02u %9lu %-12s %s\n",
(Finfo.fattrib & AM_DIR) ? 'D' : '-',
(Finfo.fattrib & AM_RDO) ? 'R' : '-',
(Finfo.fattrib & AM_HID) ? 'H' : '-',
(Finfo.fattrib & AM_SYS) ? 'S' : '-',
(Finfo.fattrib & AM_ARC) ? 'A' : '-',
(Finfo.fdate >> 9) + 1980, (Finfo.fdate >> 5) & 15, Finfo.fdate & 31,
(Finfo.ftime >> 11), (Finfo.ftime >> 5) & 63,
Finfo.fsize, Finfo.fname,
#if _USE_LFN
Lfname);
#else
"");
#endif
}
xprintf("%4u File(s),%10lu bytes total\n%4u Dir(s)", s1, p1, s2);
res = f_getfree(ptr, (DWORD*)&p1, &fs);
if (res == FR_OK)
xprintf(", %10lu bytes free\n", p1 * fs->csize * 512);
else
put_rc(res);
break;
case 'o' : /* fo <mode> <file> - Open a file */
if (!xatoi(&ptr, &p1)) break;
while (*ptr == ' ') ptr++;
put_rc(f_open(&File[0], ptr, (BYTE)p1));
break;
case 'c' : /* fc - Close a file */
put_rc(f_close(&File[0]));
break;
case 'e' : /* fe - Seek file pointer */
if (!xatoi(&ptr, &p1)) break;
res = f_lseek(&File[0], p1);
put_rc(res);
if (res == FR_OK)
xprintf("fptr=%lu(0x%lX)\n", File[0].fptr, File[0].fptr);
break;
case 'd' : /* fd <len> - read and dump file from current fp */
if (!xatoi(&ptr, &p1)) break;
ofs = File[0].fptr;
while (p1) {
if ((UINT)p1 >= 16) { cnt = 16; p1 -= 16; }
else { cnt = p1; p1 = 0; }
res = f_read(&File[0], Buff, cnt, &cnt);
if (res != FR_OK) { put_rc(res); break; }
if (!cnt) break;
put_dump(Buff, ofs, cnt, DW_CHAR);
ofs += 16;
}
break;
case 'r' : /* fr <len> - read file */
if (!xatoi(&ptr, &p1)) break;
p2 = 0;
Timer = 0;
while (p1) {
if ((UINT)p1 >= blen) {
cnt = blen; p1 -= blen;
} else {
cnt = p1; p1 = 0;
}
res = f_read(&File[0], Buff, cnt, &s2);
if (res != FR_OK) { put_rc(res); break; }
p2 += s2;
if (cnt != s2) break;
}
xprintf("%lu bytes read with %lu kB/sec.\n", p2, Timer ? (p2 / Timer) : 0);
break;
case 'w' : /* fw <len> <val> - write file */
if (!xatoi(&ptr, &p1) || !xatoi(&ptr, &p2)) break;
memset(Buff, (BYTE)p2, blen);
p2 = 0;
Timer = 0;
while (p1) {
if ((UINT)p1 >= blen) {
cnt = blen; p1 -= blen;
} else {
cnt = p1; p1 = 0;
}
res = f_write(&File[0], Buff, cnt, &s2);
if (res != FR_OK) { put_rc(res); break; }
p2 += s2;
if (cnt != s2) break;
}
xprintf("%lu bytes written with %lu kB/sec.\n", p2, Timer ? (p2 / Timer) : 0);
break;
case 'n' : /* fn <org.name> <new.name> - Change name of an object */
while (*ptr == ' ') ptr++;
ptr2 = strchr(ptr, ' ');
if (!ptr2) break;
*ptr2++ = 0;
while (*ptr2 == ' ') ptr2++;
put_rc(f_rename(ptr, ptr2));
break;
case 'u' : /* fu <name> - Unlink an object */
while (*ptr == ' ') ptr++;
put_rc(f_unlink(ptr));
break;
case 'v' : /* fv - Truncate file */
put_rc(f_truncate(&File[0]));
break;
case 'k' : /* fk <name> - Create a directory */
while (*ptr == ' ') ptr++;
put_rc(f_mkdir(ptr));
break;
case 'a' : /* fa <atrr> <mask> <name> - Change attribute of an object */
if (!xatoi(&ptr, &p1) || !xatoi(&ptr, &p2)) break;
while (*ptr == ' ') ptr++;
put_rc(f_chmod(ptr, p1, p2));
break;
case 't' : /* ft <year> <month> <day> <hour> <min> <sec> <name> - Change timestamp of an object */
if (!xatoi(&ptr, &p1) || !xatoi(&ptr, &p2) || !xatoi(&ptr, &p3)) break;
Finfo.fdate = ((p1 - 1980) << 9) | ((p2 & 15) << 5) | (p3 & 31);
if (!xatoi(&ptr, &p1) || !xatoi(&ptr, &p2) || !xatoi(&ptr, &p3)) break;
Finfo.ftime = ((p1 & 31) << 11) | ((p2 & 63) << 5) | ((p3 >> 1) & 31);
put_rc(f_utime(ptr, &Finfo));
break;
case 'x' : /* fx <src.name> <dst.name> - Copy a file */
while (*ptr == ' ') ptr++;
ptr2 = strchr(ptr, ' ');
if (!ptr2) break;
*ptr2++ = 0;
while (*ptr2 == ' ') ptr2++;
xprintf("Opening \"%s\"", ptr);
res = f_open(&File[0], ptr, FA_OPEN_EXISTING | FA_READ);
xputc('\n');
if (res) {
put_rc(res);
break;
}
xprintf("Creating \"%s\"", ptr2);
res = f_open(&File[1], ptr2, FA_CREATE_ALWAYS | FA_WRITE);
xputc('\n');
if (res) {
put_rc(res);
f_close(&File[0]);
break;
}
xprintf("Copying file...");
Timer = 0;
p1 = 0;
for (;;) {
res = f_read(&File[0], Buff, blen, &s1);
if (res || s1 == 0) break; /* error or eof */
res = f_write(&File[1], Buff, s1, &s2);
p1 += s2;
if (res || s2 < s1) break; /* error or disk full */
}
xprintf("\n%lu bytes copied with %lu kB/sec.\n", p1, p1 / Timer);
f_close(&File[0]);
f_close(&File[1]);
break;
#if _FS_RPATH
case 'g' : /* fg <path> - Change current directory */
while (*ptr == ' ') ptr++;
put_rc(f_chdir(ptr));
break;
#if _FS_RPATH >= 2
case 'q' : /* fq - Show current dir path */
res = f_getcwd(Line, sizeof Line);
if (res)
put_rc(res);
else
xprintf("%s\n", Line);
break;
#endif
#endif
#if _USE_LABEL
case 'b' : /* fb <name> - Set volume label */
while (*ptr == ' ') ptr++;
put_rc(f_setlabel(ptr));
break;
#endif /* _USE_LABEL */
#if _USE_MKFS
case 'm' : /* fm <rule> <csize> - Create file system */
if (!xatoi(&ptr, &p2) || !xatoi(&ptr, &p3)) break;
xprintf("The volume will be formatted. Are you sure? (Y/n)=");
xgets(Line, sizeof Line);
if (Line[0] == 'Y')
put_rc(f_mkfs("", (BYTE)p2, (WORD)p3));
break;
#endif /* _USE_MKFS */
case 'z' : /* fz [<size>] - Change/Show R/W length for fr/fw/fx command */
if (xatoi(&ptr, &p1) && p1 >= 1 && p1 <= (long)sizeof Buff)
blen = p1;
xprintf("blen=%u\n", blen);
break;
}
break;
case 't' : /* t [<year> <mon> <mday> <hour> <min> <sec>] - Set/Show RTC */
if (xatoi(&ptr, &p1)) {
rtc.year = (WORD)p1;
xatoi(&ptr, &p1); rtc.month = (BYTE)p1;
xatoi(&ptr, &p1); rtc.mday = (BYTE)p1;
xatoi(&ptr, &p1); rtc.hour = (BYTE)p1;
xatoi(&ptr, &p1); rtc.min = (BYTE)p1;
if (!xatoi(&ptr, &p1)) break;
rtc.sec = (BYTE)p1;
rtc_settime(&rtc);
}
rtc_gettime(&rtc);
xprintf("%u/%u/%u %s %02u:%02u:%02u\n", rtc.year, rtc.month, rtc.mday, &days[rtc.wday*4], rtc.hour, rtc.min, rtc.sec);
break;
}
}
}
| 29.992504 | 121 | 0.517721 | [
"object"
] |
d630755138567545a5c819d217a876c02cda74f8 | 1,439 | h | C | src/editor/NewWoiceDialog.h | yuxshao/pxtone-qt | 2ff9e88a63730f576a2748c0a51f7fde3b161e3a | [
"MIT"
] | 54 | 2020-06-20T19:04:59.000Z | 2022-03-19T20:27:30.000Z | src/editor/NewWoiceDialog.h | yuxshao/pxtone-qt | 2ff9e88a63730f576a2748c0a51f7fde3b161e3a | [
"MIT"
] | 37 | 2020-06-18T15:06:01.000Z | 2022-03-21T06:22:04.000Z | src/editor/NewWoiceDialog.h | yuxshao/pxtone-qt | 2ff9e88a63730f576a2748c0a51f7fde3b161e3a | [
"MIT"
] | 8 | 2020-11-18T02:19:41.000Z | 2022-01-14T22:18:41.000Z | #ifndef NEWWOICEDIALOG_H
#define NEWWOICEDIALOG_H
#include <QDialog>
#include <QDirIterator>
#include <QFileDialog>
#include "PxtoneClient.h"
#include "audio/NotePreview.h"
namespace Ui {
class NewWoiceDialog;
}
extern AddWoice make_addWoice_from_path_exn(const QString &path,
const QString &name);
class Query;
class NewWoiceDialog : public QDialog {
Q_OBJECT
public:
explicit NewWoiceDialog(bool multi, const PxtoneClient *client,
QWidget *parent = nullptr);
~NewWoiceDialog();
std::vector<AddWoice> selectedWoices();
void inputMidi(const Input::Event::Event &);
private:
bool searchPart();
void searchAsync();
void previewWoice(const QString &path);
void selectWoices(const QStringList &files);
void setPreviewWoice(const QString &path);
const PxtoneClient *m_client;
QString m_last_search_dir;
QStringList m_last_search_files;
QFileDialog *m_browse_search_folder_dialog, *m_browse_woice_dialog;
QStringList m_search_results_paths;
std::unique_ptr<QDirIterator> m_last_search_dir_it;
std::unique_ptr<std::list<Query>> m_queries;
std::unique_ptr<NotePreview> m_note_preview;
std::shared_ptr<pxtnWoice> m_preview_woice;
std::map<int, std::unique_ptr<NotePreview>> m_record_note_preview;
QStringList::iterator m_search_file_it;
int m_last_search_num_files;
Ui::NewWoiceDialog *ui;
};
#endif // NEWWOICEDIALOG_H
| 27.673077 | 69 | 0.744267 | [
"vector"
] |
d63749f6d5569653aae8c4cd6f3d56c916f8f484 | 4,025 | h | C | client/components/ui/skin_toolbar_manager.h | zamorajavi/google-input-tools | fc9f11d80d957560f7accf85a5fc27dd23625f70 | [
"Apache-2.0"
] | 175 | 2015-01-01T12:40:33.000Z | 2019-05-24T22:33:59.000Z | client/components/ui/skin_toolbar_manager.h | zamorajavi/google-input-tools | fc9f11d80d957560f7accf85a5fc27dd23625f70 | [
"Apache-2.0"
] | 11 | 2015-01-19T16:30:56.000Z | 2018-04-25T01:06:52.000Z | client/components/ui/skin_toolbar_manager.h | zamorajavi/google-input-tools | fc9f11d80d957560f7accf85a5fc27dd23625f70 | [
"Apache-2.0"
] | 97 | 2015-01-19T15:35:29.000Z | 2019-05-15T05:48:02.000Z | /*
Copyright 2014 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef GOOPY_COMPONENTS_UI_SKIN_TOOLBAR_MANAGER_H_
#define GOOPY_COMPONENTS_UI_SKIN_TOOLBAR_MANAGER_H_
#include <string>
#include <vector>
#include "base/basictypes.h"
#include "base/scoped_ptr.h"
#include "components/ui/skin_ui_component_utils.h"
namespace google {
namespace protobuf {
template <class T> class RepeatedPtrField;
} // namespace protobuf
} // namespace google
namespace ggadget {
class MenuInterface;
} // namespace ggadget
namespace ipc {
namespace proto {
class CommandList;
class ComponentInfo;
class VariableArray;
} // namespace proto
} // namespace ipc
namespace ime_goopy {
namespace skin {
class Skin;
class ToolbarElement;
} // namespace skin
namespace components {
// A class for managing the toolbar element.
class ToolbarManager {
public:
typedef google::protobuf::RepeatedPtrField<ipc::proto::CommandList>
CommandLists;
typedef google::protobuf::RepeatedPtrField<ipc::proto::ComponentInfo>
ComponentInfos;
// A delegate interface.
// The creator of toolbar manager should implement this interface.
class Delegate : public SkinCommandCallbackInterface {
public:
virtual int GetIcid() const = 0;
virtual void SelectInputMethod(uint32 input_method_id) = 0;
virtual void ExecuteCommand(int owner, int icid, const std::string& id) = 0;
virtual void ConstructIMEMenu(ggadget::MenuInterface* menu_interface) = 0;
virtual bool IsToolbarFloating() = 0;
virtual bool IsToolbarMini() = 0;
virtual bool IsToolbarSemiTransparency() = 0;
virtual bool SetToolbarCollapsed(bool is_collapsed) = 0;
virtual bool IsToolbarCollapsed() = 0;
virtual bool SetToolbarPanelPos(int32 toolbar_panel_pos_x,
int32 toolbar_panel_pos_y) = 0;
virtual bool GetToolbarPanelPos(int32* toolbar_panel_pos_x,
int32* toolbar_panel_pos_y) = 0;
};
ToolbarManager(Delegate* delegate,
skin::Skin* skin);
~ToolbarManager();
bool Initialize();
// Sets/Resets all the command lists of toolbar element.
// This method is called by ui component when command lists changed and
// need to be updated in toolbar.
void SetCommandLists(const CommandLists& command_lists);
// Sets/Resets the input_method_list of toolbar element.
void SetInputMethodList(const ComponentInfos& input_method_list);
// Sets/Resets the active_input_method of toolbar element.
void SetActiveInputMethod(
const ipc::proto::ComponentInfo& active_input_method);
// Sets and gets whether or not the toolbar is visible.
void SetVisible(bool visible);
bool IsVisible() const;
// Adds Ime related command_list to menu.
void AddImeCommandListToMenuInterface(
ggadget::MenuInterface* menu_interface);
// Updates the view of toolbar element.
void UpdateToolbarView();
private:
// Some util class and helper managers to support the implement of
// toolbar_manager.
class ToolbarUtils;
class PanelManager;
class ToolbarElementManager;
class ImeSelectionManager;
class ImeMenuManager;
scoped_ptr<ImeSelectionManager> ime_selection_manager_;
scoped_ptr<ImeMenuManager> ime_menu_manager_;
scoped_ptr<ToolbarElementManager> toolbar_element_manager_;
scoped_ptr<PanelManager> panel_manager_;
DISALLOW_COPY_AND_ASSIGN(ToolbarManager);
};
} // namespace components
} // namespace ime_goopy
#endif // GOOPY_COMPONENTS_UI_SKIN_TOOLBAR_MANAGER_H_
| 30.961538 | 80 | 0.750311 | [
"vector"
] |
d6380d6b32c01489ad6a0bed4815f0b9f7226022 | 2,866 | h | C | SDKs/imgui/backends/imgui_impl_win32.h | VampireVol/GameEnginePractice-2021 | 1d1a7178a90cc611cdbf6778c96c7bd9a289c9f5 | [
"MIT"
] | null | null | null | SDKs/imgui/backends/imgui_impl_win32.h | VampireVol/GameEnginePractice-2021 | 1d1a7178a90cc611cdbf6778c96c7bd9a289c9f5 | [
"MIT"
] | null | null | null | SDKs/imgui/backends/imgui_impl_win32.h | VampireVol/GameEnginePractice-2021 | 1d1a7178a90cc611cdbf6778c96c7bd9a289c9f5 | [
"MIT"
] | null | null | null | // dear imgui: Platform Backend for Windows (standard windows API for 32 and 64 bits applications)
// This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..)
// Implemented features:
// [X] Platform: Clipboard support (for Win32 this is actually part of core dear imgui)
// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
// [X] Platform: Keyboard arrays indexed using VK_* Virtual Key Codes, e.g. ImGui::IsKeyPressed(VK_SPACE).
// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs
#pragma once
#include "imgui.h" // IMGUI_IMPL_API
//#include "windows.h"
IMGUI_IMPL_API bool ImGui_ImplWin32_Init(void* hwnd);
IMGUI_IMPL_API void ImGui_ImplWin32_Shutdown();
IMGUI_IMPL_API void ImGui_ImplWin32_NewFrame();
// Win32 message handler your application need to call.
// - Intentionally commented out in a '#if 0' block to avoid dragging dependencies on <windows.h> from this helper.
// - You should COPY the line below into your .cpp code to forward declare the function and then you can call it.
#if 0
extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
#endif
// DPI-related helpers (optional)
// - Use to enable DPI awareness without having to create an application manifest.
// - Your own app may already do this via a manifest or explicit calls. This is mostly useful for our examples/ apps.
// - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), etc.
// but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at runtime,
// neither we want to require the user to have. So we dynamically select and load those functions to avoid dependencies.
IMGUI_IMPL_API void ImGui_ImplWin32_EnableDpiAwareness();
IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd); // HWND hwnd
IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor); // HMONITOR monitor
// Transparency related helpers (optional) [experimental]
// - Use to enable alpha compositing transparency with the desktop.
// - Use together with e.g. clearing your framebuffer with zero-alpha.
IMGUI_IMPL_API void ImGui_ImplWin32_EnableAlphaCompositing(void* hwnd); // HWND hwnd
| 65.136364 | 142 | 0.768318 | [
"shape"
] |
d639d5989a82b3f0c180c5c91c868f2f42eceb87 | 3,567 | h | C | PlugIns/OctreeSceneManager/include/OgreOctreeSceneQuery.h | rjdgtn/OgreCPPBuilder | 1d3fa5874e54da9c19f4fe9fd128fcda19285b5e | [
"MIT"
] | 108 | 2015-01-23T01:43:56.000Z | 2021-12-23T07:00:48.000Z | PlugIns/OctreeSceneManager/include/OgreOctreeSceneQuery.h | venscn/ogre | 069a43c4c4fcb5264c995fca65a28acd3154b230 | [
"MIT"
] | 2 | 2016-03-05T14:40:20.000Z | 2017-02-20T11:33:51.000Z | PlugIns/OctreeSceneManager/include/OgreOctreeSceneQuery.h | venscn/ogre | 069a43c4c4fcb5264c995fca65a28acd3154b230 | [
"MIT"
] | 92 | 2015-01-13T08:57:11.000Z | 2021-09-19T05:20:55.000Z | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2011 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
/***************************************************************************
OgreOctreeSceneQuery.h - description
-------------------
begin : Tues July 20, 2004
copyright : (C) 2004 by Jon Anderson
email : janders@users.sf.net
***************************************************************************/
#ifndef OCTREESCENEQUERY_H
#define OCTREESCENEQUERY_H
#include "OgreOctreePrerequisites.h"
#include <OgreSceneManager.h>
namespace Ogre
{
/** Octree implementation of IntersectionSceneQuery. */
class _OgreOctreePluginExport OctreeIntersectionSceneQuery : public DefaultIntersectionSceneQuery
{
public:
OctreeIntersectionSceneQuery(SceneManager* creator);
~OctreeIntersectionSceneQuery();
/** See IntersectionSceneQuery. */
void execute(IntersectionSceneQueryListener* listener);
};
/** Octree implementation of RaySceneQuery. */
class _OgreOctreePluginExport OctreeRaySceneQuery : public DefaultRaySceneQuery
{
public:
OctreeRaySceneQuery(SceneManager* creator);
~OctreeRaySceneQuery();
/** See RayScenQuery. */
void execute(RaySceneQueryListener* listener);
};
/** Octree implementation of SphereSceneQuery. */
class _OgreOctreePluginExport OctreeSphereSceneQuery : public DefaultSphereSceneQuery
{
public:
OctreeSphereSceneQuery(SceneManager* creator);
~OctreeSphereSceneQuery();
/** See SceneQuery. */
void execute(SceneQueryListener* listener);
};
/** Octree implementation of PlaneBoundedVolumeListSceneQuery. */
class _OgreOctreePluginExport OctreePlaneBoundedVolumeListSceneQuery : public DefaultPlaneBoundedVolumeListSceneQuery
{
public:
OctreePlaneBoundedVolumeListSceneQuery(SceneManager* creator);
~OctreePlaneBoundedVolumeListSceneQuery();
/** See SceneQuery. */
void execute(SceneQueryListener* listener);
};
/** Octree implementation of AxisAlignedBoxSceneQuery. */
class _OgreOctreePluginExport OctreeAxisAlignedBoxSceneQuery : public DefaultAxisAlignedBoxSceneQuery
{
public:
OctreeAxisAlignedBoxSceneQuery(SceneManager* creator);
~OctreeAxisAlignedBoxSceneQuery();
/** See RaySceneQuery. */
void execute(SceneQueryListener* listener);
};
}
#endif
| 34.631068 | 117 | 0.70928 | [
"object"
] |
d63a80a56acb4be5dff8de74b5c12671c60e3d88 | 2,497 | h | C | Src/Math/matrix3x3.h | bouzi71/STM32LedCube | 65a67e310789c21648115bd119ab56d1bc9c703d | [
"Apache-2.0"
] | 1 | 2020-12-20T17:00:58.000Z | 2020-12-20T17:00:58.000Z | Src/Math/matrix3x3.h | bouzi71/STM32LedCube | 65a67e310789c21648115bd119ab56d1bc9c703d | [
"Apache-2.0"
] | null | null | null | Src/Math/matrix3x3.h | bouzi71/STM32LedCube | 65a67e310789c21648115bd119ab56d1bc9c703d | [
"Apache-2.0"
] | null | null | null | #ifndef __MATRIX3X3_H
#define __MATRIX3X3_H
#include "vector2.h"
#include "vector3.h"
class Matrix4;
class Matrix3
{
public:
Matrix3() :
a1((1.0f)), a2(), a3(),
b1(), b2((1.0f)), b3(),
c1(), c2(), c3((1.0f))
{}
Matrix3(float _a1, float _a2, float _a3,
float _b1, float _b2, float _b3,
float _c1, float _c2, float _c3) :
a1(_a1), a2(_a2), a3(_a3),
b1(_b1), b2(_b2), b3(_b3),
c1(_c1), c2(_c2), c3(_c3)
{}
public:
Matrix3& operator *= (const Matrix3& m);
Matrix3 operator * (const Matrix3& m) const;
float* operator[] (unsigned int p_iIndex);
const float* operator[] (unsigned int p_iIndex) const;
bool operator== (const Matrix4& m) const;
bool operator!= (const Matrix4& m) const;
bool Equal(const Matrix4& m, float epsilon = 1e-6) const;
public:
// -------------------------------------------------------------------
/** @brief Construction from a 4x4 matrix. floathe remaining parts
* of the matrix are ignored.
*/
explicit Matrix3(const Matrix4& pMatrix);
// -------------------------------------------------------------------
/** @brief floatranspose the matrix
*/
Matrix3& Transpose();
// -------------------------------------------------------------------
/** @brief Invert the matrix.
* If the matrix is not invertible all elements are set to qnan.
* Beware, use (f != f) to check whether a float f is qnan.
*/
Matrix3& Inverse();
float Determinant() const;
public:
// -------------------------------------------------------------------
/** @brief Returns a rotation matrix for a rotation around z
* @param a Rotation angle, in radians
* @param out Receives the output matrix
* @return Reference to the output matrix
*/
static Matrix3& RotationZ(float a, Matrix3& out);
// -------------------------------------------------------------------
/** @brief Returns a rotation matrix for a rotation around
* an arbitrary axis.
*
* @param a Rotation angle, in radians
* @param axis Axis to rotate around
* @param out floato be filled
*/
static Matrix3& Rotation(float a, const Vector3& axis, Matrix3& out);
// -------------------------------------------------------------------
/** @brief Returns a translation matrix
* @param v floatranslation vector
* @param out Receives the output matrix
* @return Reference to the output matrix
*/
static Matrix3& Translation(const Vector2& v, Matrix3& out);
public:
float a1, a2, a3;
float b1, b2, b3;
float c1, c2, c3;
};
#endif
| 27.141304 | 71 | 0.552263 | [
"vector"
] |
d644a76a6937060ad360320244f101f0cc64b53f | 625 | h | C | src/node/pki/wcerts.h | microshine/trusted-crypto | 22a6496bd390ebe2ed516a15636d911fae4c6407 | [
"Apache-2.0"
] | null | null | null | src/node/pki/wcerts.h | microshine/trusted-crypto | 22a6496bd390ebe2ed516a15636d911fae4c6407 | [
"Apache-2.0"
] | null | null | null | src/node/pki/wcerts.h | microshine/trusted-crypto | 22a6496bd390ebe2ed516a15636d911fae4c6407 | [
"Apache-2.0"
] | 1 | 2020-07-01T16:32:57.000Z | 2020-07-01T16:32:57.000Z | #ifndef PKI_WCERTS_H_INCLUDED
#define PKI_WCERTS_H_INCLUDED
#include "../../wrapper/pki/certs.h"
#include <nan.h>
#include "../utils/wrap.h"
#include "../helper.h"
class WCertificateCollection : public Wrapper < CertificateCollection >
{
public:
WCertificateCollection(){};
~WCertificateCollection(){};
WRAP_NEW_INSTANCE(CertificateCollection);
static const char* className;
static void Init(v8::Handle<v8::Object>);
static NAN_METHOD(New);
static NAN_METHOD(Items);
static NAN_METHOD(Push);
static NAN_METHOD(Pop);
static NAN_METHOD(RemoveAt);
static NAN_METHOD(Length);
};
#endif //PKI_WCERTS_H_INCLUDED | 20.833333 | 71 | 0.7568 | [
"object"
] |
d64742ebd03690b735bcbd66843021b55d85011e | 3,128 | h | C | chrome/browser/media_galleries/fileapi/mtp_device_map_service.h | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 231 | 2015-01-08T09:04:44.000Z | 2021-12-30T03:03:10.000Z | chrome/browser/media_galleries/fileapi/mtp_device_map_service.h | j4ckfrost/android_external_chromium_org | a1a3dad8b08d1fcf6b6b36c267158ed63217c780 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2018-02-10T21:00:08.000Z | 2018-03-20T05:09:50.000Z | chrome/browser/media_galleries/fileapi/mtp_device_map_service.h | j4ckfrost/android_external_chromium_org | a1a3dad8b08d1fcf6b6b36c267158ed63217c780 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 268 | 2015-01-21T05:53:28.000Z | 2022-03-25T22:09:01.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_MEDIA_GALLERIES_FILEAPI_MTP_DEVICE_MAP_SERVICE_H_
#define CHROME_BROWSER_MEDIA_GALLERIES_FILEAPI_MTP_DEVICE_MAP_SERVICE_H_
#include <map>
#include "base/files/file_path.h"
#include "base/lazy_instance.h"
#include "base/threading/thread_checker.h"
class MTPDeviceAsyncDelegate;
// This class provides media transfer protocol (MTP) device delegate to
// complete media file system operations.
// Lives on the IO thread in production.
// TODO(gbillock): Make this class owned by the MediaFileSystemRegistry.
class MTPDeviceMapService {
public:
static MTPDeviceMapService* GetInstance();
// Gets the media device delegate associated with |filesystem_id|.
// Return NULL if the |filesystem_id| is no longer valid (e.g. because the
// corresponding device is detached, etc).
// Called on the IO thread.
MTPDeviceAsyncDelegate* GetMTPDeviceAsyncDelegate(
const std::string& filesystem_id);
// Register that an MTP filesystem is in use for the given |device_location|.
void RegisterMTPFileSystem(
const base::FilePath::StringType& device_location,
const std::string& fsid);
// Removes the MTP entry associated with the given
// |device_location|. Signals the MTPDeviceMapService to destroy the
// delegate if there are no more uses of it.
void RevokeMTPFileSystem(const std::string& fsid);
private:
friend struct base::DefaultLazyInstanceTraits<MTPDeviceMapService>;
// Adds the MTP device delegate to the map service. |device_location|
// specifies the mount location of the MTP device.
// Called on the IO thread.
void AddAsyncDelegate(const base::FilePath::StringType& device_location,
MTPDeviceAsyncDelegate* delegate);
// Removes the MTP device delegate from the map service. |device_location|
// specifies the mount location of the MTP device.
// Called on the IO thread.
void RemoveAsyncDelegate(const base::FilePath::StringType& device_location);
// Mapping of device_location and MTPDeviceAsyncDelegate* object. It is safe
// to store and access the raw pointer. This class operates on the IO thread.
typedef std::map<base::FilePath::StringType, MTPDeviceAsyncDelegate*>
AsyncDelegateMap;
// Map a filesystem id (fsid) to an MTP device location.
typedef std::map<std::string, base::FilePath::StringType>
MTPDeviceFileSystemMap;
// Map a MTP or PTP device location to a count of current uses of that
// location.
typedef std::map<const base::FilePath::StringType, int>
MTPDeviceUsageMap;
// Get access to this class using GetInstance() method.
MTPDeviceMapService();
~MTPDeviceMapService();
// Map of attached mtp device async delegates.
AsyncDelegateMap async_delegate_map_;
MTPDeviceFileSystemMap mtp_device_map_;
MTPDeviceUsageMap mtp_device_usage_map_;
DISALLOW_COPY_AND_ASSIGN(MTPDeviceMapService);
};
#endif // CHROME_BROWSER_MEDIA_GALLERIES_FILEAPI_MTP_DEVICE_MAP_SERVICE_H_
| 36.8 | 79 | 0.765345 | [
"object"
] |
d6542abe43fbef3ad5b056b9eb979e0046032da2 | 35,764 | c | C | mpp/hal/vpu/jpegd/hal_jpegd_vdpu1.c | Fruit-Pi/mpp | dd7097fbab86eeed807e177620212847a9bc8f70 | [
"Apache-2.0"
] | 312 | 2016-12-26T12:32:03.000Z | 2022-03-29T13:37:59.000Z | mpp/hal/vpu/jpegd/hal_jpegd_vdpu1.c | Fruit-Pi/mpp | dd7097fbab86eeed807e177620212847a9bc8f70 | [
"Apache-2.0"
] | 271 | 2017-01-12T03:59:31.000Z | 2022-03-31T02:26:45.000Z | mpp/hal/vpu/jpegd/hal_jpegd_vdpu1.c | Fruit-Pi/mpp | dd7097fbab86eeed807e177620212847a9bc8f70 | [
"Apache-2.0"
] | 195 | 2016-12-01T07:22:01.000Z | 2022-03-30T23:09:00.000Z | /*
*
* Copyright 2017 Rockchip Electronics Co. LTD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define MODULE_TAG "HAL_JPEGD_VDPU1"
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include "mpp_env.h"
#include "mpp_log.h"
#include "mpp_mem.h"
#include "mpp_frame.h"
#include "mpp_common.h"
#include "jpegd_syntax.h"
#include "hal_jpegd_common.h"
#include "hal_jpegd_vdpu1.h"
#include "hal_jpegd_vdpu1_reg.h"
static void
jpegd_write_code_word_number(JpegdHalCtx *ctx, JpegdSyntax *syntax)
{
jpegd_dbg_func("enter\n");
JpegdSyntax *s = syntax;
AcTable *ac_ptr0 = NULL, *ac_ptr1 = NULL;
DcTable *dc_ptr0 = NULL, *dc_ptr1 = NULL;
JpegdIocRegInfo *info = (JpegdIocRegInfo *)ctx->regs;
JpegRegSet *reg = &info->regs;
/* first, select the table we'll use.
* this trick is done because hardware always wants luma
* table as AC hardware table 0.
*/
if (s->ac_index[0] == HUFFMAN_TABLE_ID_ZERO) {
/* Luma's AC uses Huffman table zero */
ac_ptr0 = &(s->ac_table[HUFFMAN_TABLE_ID_ZERO]);
ac_ptr1 = &(s->ac_table[HUFFMAN_TABLE_ID_ONE]);
} else {
ac_ptr0 = &(s->ac_table[HUFFMAN_TABLE_ID_ONE]);
ac_ptr1 = &(s->ac_table[HUFFMAN_TABLE_ID_ZERO]);
}
/* write AC table 1 (luma) */
reg->reg16.sw_ac1_code1_cnt = ac_ptr0->bits[0];
reg->reg16.sw_ac1_code2_cnt = ac_ptr0->bits[1];
reg->reg16.sw_ac1_code3_cnt = ac_ptr0->bits[2];
reg->reg16.sw_ac1_code4_cnt = ac_ptr0->bits[3];
reg->reg16.sw_ac1_code5_cnt = ac_ptr0->bits[4];
reg->reg16.sw_ac1_code6_cnt = ac_ptr0->bits[5];
reg->reg17.sw_ac1_code7_cnt = ac_ptr0->bits[6];
reg->reg17.sw_ac1_code8_cnt = ac_ptr0->bits[7];
reg->reg17.sw_ac1_code9_cnt = ac_ptr0->bits[8];
reg->reg17.sw_ac1_code10_cnt = ac_ptr0->bits[9];
reg->reg18.sw_ac1_code11_cnt = ac_ptr0->bits[10];
reg->reg18.sw_ac1_code12_cnt = ac_ptr0->bits[11];
reg->reg18.sw_ac1_code13_cnt = ac_ptr0->bits[12];
reg->reg18.sw_ac1_code14_cnt = ac_ptr0->bits[13];
reg->reg19.sw_ac1_code15_cnt = ac_ptr0->bits[14];
reg->reg19.sw_ac1_code16_cnt = ac_ptr0->bits[15];
/* table AC2 (the not-luma table) */
reg->reg19.sw_ac2_code1_cnt = ac_ptr1->bits[0];
reg->reg19.sw_ac2_code2_cnt = ac_ptr1->bits[1];
reg->reg19.sw_ac2_code3_cnt = ac_ptr1->bits[2];
reg->reg19.sw_ac2_code4_cnt = ac_ptr1->bits[3];
reg->reg20.sw_ac2_code5_cnt = ac_ptr1->bits[4];
reg->reg20.sw_ac2_code6_cnt = ac_ptr1->bits[5];
reg->reg20.sw_ac2_code7_cnt = ac_ptr1->bits[6];
reg->reg20.sw_ac2_code8_cnt = ac_ptr1->bits[7];
reg->reg21.sw_ac2_code9_cnt = ac_ptr1->bits[8];
reg->reg21.sw_ac2_code10_cnt = ac_ptr1->bits[9];
reg->reg21.sw_ac2_code11_cnt = ac_ptr1->bits[10];
reg->reg21.sw_ac2_code12_cnt = ac_ptr1->bits[11];
reg->reg22.sw_ac2_code13_cnt = ac_ptr1->bits[12];
reg->reg22.sw_ac2_code14_cnt = ac_ptr1->bits[13];
reg->reg22.sw_ac2_code15_cnt = ac_ptr1->bits[14];
reg->reg22.sw_ac2_code16_cnt = ac_ptr1->bits[15];
/* first, select the table we'll use.
* this trick is done because hardware always wants luma
* table as DC hardware table 0.
*/
if (s->dc_index[0] == HUFFMAN_TABLE_ID_ZERO) {
/* Luma's DC uses Huffman table zero */
dc_ptr0 = &(s->dc_table[HUFFMAN_TABLE_ID_ZERO]);
dc_ptr1 = &(s->dc_table[HUFFMAN_TABLE_ID_ONE]);
} else {
dc_ptr0 = &(s->dc_table[HUFFMAN_TABLE_ID_ONE]);
dc_ptr1 = &(s->dc_table[HUFFMAN_TABLE_ID_ZERO]);
}
/* write DC table 1 (luma) */
reg->reg23.sw_dc1_code1_cnt = dc_ptr0->bits[0];
reg->reg23.sw_dc1_code2_cnt = dc_ptr0->bits[1];
reg->reg23.sw_dc1_code3_cnt = dc_ptr0->bits[2];
reg->reg23.sw_dc1_code4_cnt = dc_ptr0->bits[3];
reg->reg23.sw_dc1_code5_cnt = dc_ptr0->bits[4];
reg->reg23.sw_dc1_code6_cnt = dc_ptr0->bits[5];
reg->reg23.sw_dc1_code7_cnt = dc_ptr0->bits[6];
reg->reg23.sw_dc1_code8_cnt = dc_ptr0->bits[7];
reg->reg24.sw_dc1_code9_cnt = dc_ptr0->bits[8];
reg->reg24.sw_dc1_code10_cnt = dc_ptr0->bits[9];
reg->reg24.sw_dc1_code11_cnt = dc_ptr0->bits[10];
reg->reg24.sw_dc1_code12_cnt = dc_ptr0->bits[11];
reg->reg24.sw_dc1_code13_cnt = dc_ptr0->bits[12];
reg->reg24.sw_dc1_code14_cnt = dc_ptr0->bits[13];
reg->reg24.sw_dc1_code15_cnt = dc_ptr0->bits[14];
reg->reg24.sw_dc1_code16_cnt = dc_ptr0->bits[15];
/* table DC2 (the not-luma table) */
reg->reg25.sw_dc2_code1_cnt = dc_ptr1->bits[0];
reg->reg25.sw_dc2_code2_cnt = dc_ptr1->bits[1];
reg->reg25.sw_dc2_code3_cnt = dc_ptr1->bits[2];
reg->reg25.sw_dc2_code4_cnt = dc_ptr1->bits[3];
reg->reg25.sw_dc2_code5_cnt = dc_ptr1->bits[4];
reg->reg25.sw_dc2_code6_cnt = dc_ptr1->bits[5];
reg->reg25.sw_dc2_code7_cnt = dc_ptr1->bits[6];
reg->reg25.sw_dc2_code8_cnt = dc_ptr1->bits[7];
reg->reg26.sw_dc2_code9_cnt = dc_ptr1->bits[8];
reg->reg26.sw_dc2_code10_cnt = dc_ptr1->bits[9];
reg->reg26.sw_dc2_code11_cnt = dc_ptr1->bits[10];
reg->reg26.sw_dc2_code12_cnt = dc_ptr1->bits[11];
reg->reg26.sw_dc2_code13_cnt = dc_ptr1->bits[12];
reg->reg26.sw_dc2_code14_cnt = dc_ptr1->bits[13];
reg->reg26.sw_dc2_code15_cnt = dc_ptr1->bits[14];
reg->reg26.sw_dc2_code16_cnt = dc_ptr1->bits[15];
jpegd_dbg_func("exit\n");
return;
}
static void
jpegd_set_stream_offset(JpegdHalCtx *ctx, JpegdSyntax *syntax)
{
jpegd_dbg_func("enter\n");
JpegdSyntax *s = syntax;
JpegdIocRegInfo *info = (JpegdIocRegInfo *)ctx->regs;
JpegRegSet *reg = &info->regs;
RK_U32 offset = 0, byte_cnt = 0;
RK_U32 bit_pos_in_byte = 0;
RK_U32 strm_len_by_hw = 0;
/* calculate and set stream start address to hw,
* the offset must be 8-byte aligned.
*/
offset = (s->strm_offset & (~7));
reg->reg12_input_stream_base = ctx->pkt_fd;
if (offset) {
mpp_dev_set_reg_offset(ctx->dev, 12, offset);
}
/* calculate and set stream start bit to hardware
* change current pos to bus address style
* remove three lowest bits and add the difference to bitPosInWord
* used as bit pos in word not as bit pos in byte actually...
*/
byte_cnt = ((uintptr_t) s->cur_pos & (7));
bit_pos_in_byte = byte_cnt * 8; /* 1 Byte = 8 bits */
reg->reg5.sw_strm0_start_bit = bit_pos_in_byte;
/* set up stream length for HW.
* length = size of original buffer - stream we already decoded in SW
*/
strm_len_by_hw = s->pkt_len - offset;
reg->reg6_stream_info.sw_stream_len = strm_len_by_hw;
reg->reg5.sw_jpeg_stream_all = 1;
jpegd_dbg_func("exit\n");
return;
}
static void
jpegd_set_chroma_table_id(JpegdHalCtx *ctx, JpegdSyntax *syntax)
{
jpegd_dbg_func("enter\n");
JpegdSyntax *s = syntax;
JpegdIocRegInfo *info = (JpegdIocRegInfo *)ctx->regs;
JpegRegSet *reg = &info->regs;
/* this trick is done because hw always wants
* luma table as ac hw table 1
*/
if (s->ac_index[0] == HUFFMAN_TABLE_ID_ZERO) {
reg->reg5.sw_cb_ac_vlctable = s->ac_index[1];
reg->reg5.sw_cr_ac_vlctable = s->ac_index[2];
} else {
if (s->ac_index[0] == s->ac_index[1])
reg->reg5.sw_cb_ac_vlctable = 0;
else
reg->reg5.sw_cb_ac_vlctable = 1;
if (s->ac_index[0] == s->ac_index[2])
reg->reg5.sw_cr_ac_vlctable = 0;
else
reg->reg5.sw_cr_ac_vlctable = 1;
}
/* Third DC table selectors */
if (s->dc_index[0] == HUFFMAN_TABLE_ID_ZERO) {
reg->reg5.sw_cb_dc_vlctable = s->dc_index[1];
reg->reg5.sw_cr_dc_vlctable = s->dc_index[2];
} else {
if (s->dc_index[0] == s->dc_index[1])
reg->reg5.sw_cb_dc_vlctable = 0;
else
reg->reg5.sw_cb_dc_vlctable = 1;
if (s->dc_index[0] == s->dc_index[2])
reg->reg5.sw_cr_dc_vlctable = 0;
else
reg->reg5.sw_cr_dc_vlctable = 1;
}
reg->reg5.sw_cr_dc_vlctable3 = 0;
reg->reg5.sw_cb_dc_vlctable3 = 0;
jpegd_dbg_func("exit\n");
return;
}
static MPP_RET jpegd_setup_pp(JpegdHalCtx *ctx, JpegdSyntax *syntax)
{
jpegd_dbg_func("enter\n");
JpegdIocRegInfo *info = (JpegdIocRegInfo *)ctx->regs;
JpegRegSet *regs = &info->regs;
post_processor_reg *post = ®s->post;
JpegdSyntax *s = syntax;
RK_U32 in_color = ctx->pp_info.pp_in_fmt;
RK_U32 out_color = ctx->pp_info.pp_out_fmt;
RK_U32 dither = ctx->pp_info.dither_enable;
RK_U32 crop_width = ctx->pp_info.crop_width;
RK_U32 crop_height = ctx->pp_info.crop_height;
RK_U32 crop_x = ctx->pp_info.crop_x;
RK_U32 crop_y = ctx->pp_info.crop_y;
RK_U32 in_width = s->hor_stride;
RK_U32 in_height = s->ver_stride;
RK_U32 out_width = s->hor_stride;
RK_U32 out_height = s->ver_stride;
RK_U32 uv_offset = s->hor_stride * s->ver_stride;
int video_range = 1;
post->reg61_dev_conf.sw_pp_axi_rd_id = 0;
post->reg61_dev_conf.sw_pp_axi_wr_id = 0;
post->reg61_dev_conf.sw_pp_scmd_dis = 1;
post->reg61_dev_conf.sw_pp_max_burst = 16;
post->reg61_dev_conf.sw_pp_in_a2_endsel = 1;
post->reg61_dev_conf.sw_pp_in_a1_swap32 = 1;
post->reg61_dev_conf.sw_pp_in_a1_endian = 1;
post->reg61_dev_conf.sw_pp_in_swap32_e = 1;
post->reg61_dev_conf.sw_pp_in_endian = 1;
post->reg61_dev_conf.sw_pp_out_endian = 1;
post->reg61_dev_conf.sw_pp_out_swap32_e = 1;
post->reg63_pp_in_lu_base = 0;
post->reg88_mask_1_size.sw_ext_orig_width = in_width >> 4;
post->reg61_dev_conf.sw_pp_clk_gate_e = 0;
post->reg61_dev_conf.sw_pp_ahb_hlock_e = 1;
post->reg61_dev_conf.sw_pp_data_disc_e = 1;
if (crop_width <= 0) {
post->reg92_display.sw_pp_in_w_ext = (((in_width / 16) & 0xE00) >> 9);
post->reg72_crop.sw_pp_in_width = ((in_width / 16) & 0x1FF);
post->reg92_display.sw_pp_in_h_ext = (((in_height / 16) & 0x700) >> 8);
post->reg72_crop.sw_pp_in_height = ((in_height / 16) & 0x0FF);
} else {
post->reg92_display.sw_pp_in_w_ext =
(((crop_width / 16) & 0xE00) >> 9);
post->reg72_crop.sw_pp_in_width = ((crop_width / 16) & 0x1FF);
post->reg92_display.sw_pp_in_h_ext =
(((crop_height / 16) & 0x700) >> 8);
post->reg72_crop.sw_pp_in_height = ((crop_height / 16) & 0x0FF);
post->reg92_display.sw_crop_startx_ext =
(((crop_x / 16) & 0xE00) >> 9);
post->reg71_color_coeff_1.sw_crop_startx =
((crop_x / 16) & 0x1FF);
post->reg92_display.sw_crop_starty_ext =
(((crop_y / 16) & 0x700) >> 8);
post->reg72_crop.sw_crop_starty =
((crop_y / 16) & 0x0FF);
if (crop_width & 0x0F) {
post->reg85_ctrl.sw_pp_crop8_r_e = 1;
} else {
post->reg85_ctrl.sw_pp_crop8_r_e = 0;
}
if (crop_height & 0x0F) {
post->reg85_ctrl.sw_pp_crop8_d_e = 1;
} else {
post->reg85_ctrl.sw_pp_crop8_d_e = 0;
}
in_width = crop_width;
in_height = crop_height;
}
post->reg92_display.sw_display_width = out_width;
post->reg85_ctrl.sw_pp_out_width = out_width;
post->reg85_ctrl.sw_pp_out_height = out_height;
post->reg66_pp_out_lu_base = ctx->frame_fd;
switch (in_color) {
case PP_IN_FORMAT_YUV422INTERLAVE:
case PP_IN_FORMAT_YUV420SEMI:
case PP_IN_FORMAT_YUV420PLANAR:
case PP_IN_FORMAT_YUV400:
case PP_IN_FORMAT_YUV422SEMI:
case PP_IN_FORMAT_YUV420SEMITIELED:
case PP_IN_FORMAT_YUV440SEMI:
post->reg85_ctrl.sw_pp_in_format = in_color;
break;
case PP_IN_FORMAT_YUV444_SEMI:
post->reg85_ctrl.sw_pp_in_format = 7;
post->reg86_mask_1.sw_pp_in_format_es = 0;
break;
case PP_IN_FORMAT_YUV411_SEMI:
post->reg85_ctrl.sw_pp_in_format = 0;
post->reg86_mask_1.sw_pp_in_format_es = 1;
break;
default:
mpp_err_f("unsupported format:%d", in_color);
return -1;
}
post->reg72_crop.sw_rangemap_coef_y = 9;
post->reg86_mask_1.sw_rangemap_coef_c = 9;
/* brightness */
post->reg71_color_coeff_1.sw_color_coefff = BRIGHTNESS;
if (out_color <= PP_OUT_FORMAT_ARGB) {
/*Bt.601*/
unsigned int a = 298;
unsigned int b = 409;
unsigned int c = 208;
unsigned int d = 100;
unsigned int e = 516;
/*Bt.709
unsigned int a = 298;
unsigned int b = 459;
unsigned int c = 137;
unsigned int d = 55;
unsigned int e = 544;*/
int satur = 0, tmp;
if (video_range != 0) {
/*Bt.601*/
a = 256;
b = 350;
c = 179;
d = 86;
e = 443;
/*Bt.709
a = 256;
b = 403;
c = 120;
d = 48;
e = 475;*/
post->reg79_scaling_0.sw_ycbcr_range = video_range;
}
int contrast = CONTRAST;
if (contrast != 0) {
int thr1y, thr2y, off1, off2, thr1, thr2, a1, a2;
if (video_range == 0) {
int tmp1, tmp2;
/* Contrast */
thr1 = (219 * (contrast + 128)) / 512;
thr1y = (219 - 2 * thr1) / 2;
thr2 = 219 - thr1;
thr2y = 219 - thr1y;
tmp1 = (thr1y * 256) / thr1;
tmp2 = ((thr2y - thr1y) * 256) / (thr2 - thr1);
off1 = ((thr1y - ((tmp2 * thr1) / 256)) * a) / 256;
off2 = ((thr2y - ((tmp1 * thr2) / 256)) * a) / 256;
tmp1 = (64 * (contrast + 128)) / 128;
tmp2 = 256 * (128 - tmp1);
a1 = (tmp2 + off2) / thr1;
a2 = a1 + (256 * (off2 - 1)) / (thr2 - thr1);
} else {
/* Contrast */
thr1 = (64 * (contrast + 128)) / 128;
thr1y = 128 - thr1;
thr2 = 256 - thr1;
thr2y = 256 - thr1y;
a1 = (thr1y * 256) / thr1;
a2 = ((thr2y - thr1y) * 256) / (thr2 - thr1);
off1 = thr1y - (a2 * thr1) / 256;
off2 = thr2y - (a1 * thr2) / 256;
}
if (a1 > 1023)
a1 = 1023;
else if (a1 < 0)
a1 = 0;
if (a2 > 1023)
a2 = 1023;
else if (a2 < 0)
a2 = 0;
if (thr1 > 255)
thr1 = 255;
else if (thr1 < 0)
thr1 = 0;
if (thr2 > 255)
thr2 = 255;
else if (thr2 < 0)
thr2 = 0;
if (off1 > 511)
off1 = 511;
else if (off1 < -512)
off1 = -512;
if (off2 > 511)
off2 = 511;
else if (off2 < -512)
off2 = -512;
post->reg68_contrast_adjust.sw_contrast_thr1 = thr1;
post->reg69.sw_contrast_thr2 = thr2;
post->reg68_contrast_adjust.sw_contrast_off1 = off1;
post->reg68_contrast_adjust.sw_contrast_off2 = off2;
post->reg69.sw_color_coeffa1 = a1;
post->reg69.sw_color_coeffa2 = a2;
} else {
post->reg68_contrast_adjust.sw_contrast_thr1 = 55;
post->reg69.sw_contrast_thr2 = 165;
post->reg68_contrast_adjust.sw_contrast_off1 = 0;
post->reg68_contrast_adjust.sw_contrast_off2 = 0;
tmp = a;
if (tmp > 1023)
tmp = 1023;
else if (tmp < 0)
tmp = 0;
post->reg69.sw_color_coeffa1 = tmp;
post->reg69.sw_color_coeffa2 = tmp;
}
/* saturation */
satur = 64 + SATURATION;
tmp = (satur * (int) b) / 64;
if (tmp > 1023)
tmp = 1023;
else if (tmp < 0)
tmp = 0;
post->reg70_color_coeff_0.sw_color_coeffb = (unsigned int) tmp;
tmp = (satur * (int) c) / 64;
if (tmp > 1023)
tmp = 1023;
else if (tmp < 0)
tmp = 0;
post->reg70_color_coeff_0.sw_color_coeffc = (unsigned int) tmp;
tmp = (satur * (int) d) / 64;
if (tmp > 1023)
tmp = 1023;
else if (tmp < 0)
tmp = 0;
post->reg70_color_coeff_0.sw_color_coeffd = (unsigned int) tmp;
tmp = (satur * (int) e) / 64;
if (tmp > 1023)
tmp = 1023;
else if (tmp < 0)
tmp = 0;
post->reg71_color_coeff_1.sw_color_coeffe = (unsigned int) tmp;
}
if (out_color <= PP_OUT_FORMAT_ARGB) {
PpRgbCfg *cfg = get_pp_rgb_Cfg(ctx->output_fmt);
post->reg82_r_mask = cfg->r_mask;
post->reg83_g_mask = cfg->g_mask;
post->reg84_b_mask = cfg->b_mask;
post->reg79_scaling_0.sw_rgb_r_padd = cfg->r_padd;
post->reg79_scaling_0.sw_rgb_g_padd = cfg->g_padd;
post->reg80_scaling_1.sw_rgb_b_padd = cfg->b_padd;
if (dither) {
jpegd_dbg_hal("we do dither.");
post->reg91_pip_2.sw_dither_select_r = cfg->r_dither;
post->reg91_pip_2.sw_dither_select_r = cfg->g_dither;
post->reg91_pip_2.sw_dither_select_r = cfg->b_dither;
} else {
jpegd_dbg_hal("we do not dither.");
}
post->reg79_scaling_0.sw_rgb_pix_in32 = cfg->rgb_in_32;
post->reg85_ctrl.sw_pp_out_swap16_e = cfg->swap_16;
post->reg61_dev_conf.sw_pp_out_swap32_e = cfg->swap_32;
post->reg61_dev_conf.sw_pp_out_endian = cfg->out_endian;
post->reg85_ctrl.sw_pp_out_format = 0;
} else if (out_color == PP_OUT_FORMAT_YUV422INTERLAVE) {
post->reg85_ctrl.sw_pp_out_format = 3;
} else if (out_color == PP_OUT_FORMAT_YUV420INTERLAVE) {
post->reg85_ctrl.sw_pp_out_format = 5;
} else {
mpp_err_f("unsuppotred format:%d", out_color);
return -1;
}
post->reg71_color_coeff_1.sw_rotation_mode = 0;
unsigned int inw, inh;
unsigned int outw, outh;
inw = in_width - 1;
inh = in_height - 1;
outw = out_width - 1;
outh = out_height - 1;
if (inw < outw) {
post->reg80_scaling_1.sw_hor_scale_mode = 1;
post->reg79_scaling_0.sw_scale_wratio = (outw << 16) / inw;
post->reg81_scaling_2.sw_wscale_invra = (inw << 16) / outw;
} else if (inw > outw) {
post->reg80_scaling_1.sw_hor_scale_mode = 2;
post->reg81_scaling_2.sw_wscale_invra = ((outw + 1) << 16) / (inw + 1);
} else
post->reg80_scaling_1.sw_hor_scale_mode = 0;
if (inh < outh) {
post->reg80_scaling_1.sw_ver_scale_mode = 1;
post->reg80_scaling_1.sw_scale_hratio = (outh << 16) / inh;
post->reg81_scaling_2.sw_hscale_invra = (inh << 16) / outh;
} else if (inh > outh) {
post->reg80_scaling_1.sw_ver_scale_mode = 2;
post->reg81_scaling_2.sw_hscale_invra =
((outh + 1) << 16) / (inh + 1) + 1;
} else
post->reg80_scaling_1.sw_ver_scale_mode = 0;
post->reg60_interrupt.sw_pp_pipeline_e = ctx->pp_info.pp_enable;
if (ctx->pp_info.pp_enable) {
post->reg60_interrupt.sw_pp_pipeline_e = 1;
regs->reg3.sw_dec_out_dis = 1;
regs->reg13_cur_pic_base = 0;
regs->reg14_sw_jpg_ch_out_base = 0;
post->reg66_pp_out_lu_base = ctx->frame_fd;
post->reg67_pp_out_ch_base = ctx->frame_fd;
if (uv_offset)
mpp_dev_set_reg_offset(ctx->dev, 67, uv_offset);
jpegd_dbg_hal("output_frame_fd:%x, reg67:%x", ctx->frame_fd,
post->reg67_pp_out_ch_base);
} else {
// output without pp
post->reg60_interrupt.sw_pp_pipeline_e = 0;
regs->reg3.sw_dec_out_dis = 0;
post->reg66_pp_out_lu_base = 0;
post->reg67_pp_out_ch_base = 0;
regs->reg13_cur_pic_base = ctx->frame_fd;
regs->reg14_sw_jpg_ch_out_base = ctx->frame_fd;
if (uv_offset)
mpp_dev_set_reg_offset(ctx->dev, 14, uv_offset);
jpegd_dbg_hal("output_frame_fd:%x, reg14:%x", ctx->frame_fd,
regs->reg14_sw_jpg_ch_out_base);
}
jpegd_dbg_func("exit\n");
return 0;
}
static MPP_RET jpegd_regs_init(JpegRegSet *reg)
{
jpegd_dbg_func("enter\n");
memset(reg, 0, sizeof(JpegRegSet));
reg->reg2_dec_ctrl.sw_dec_out_tiled_e = 0;
reg->reg2_dec_ctrl.sw_dec_scmd_dis = DEC_VDPU1_SCMD_DISABLE;
reg->reg2_dec_ctrl.sw_dec_latency = DEC_VDPU1_LATENCY_COMPENSATION;
reg->reg2_dec_ctrl.sw_dec_in_endian = DEC_VDPU1_BIG_ENDIAN;
reg->reg2_dec_ctrl.sw_dec_out_endian = DEC_VDPU1_LITTLE_ENDIAN;
reg->reg2_dec_ctrl.sw_dec_strendian_e = DEC_VDPU1_LITTLE_ENDIAN;
reg->reg2_dec_ctrl.sw_dec_outswap32_e = DEC_VDPU1_LITTLE_ENDIAN;
reg->reg2_dec_ctrl.sw_dec_inswap32_e = 1;
reg->reg2_dec_ctrl.sw_dec_strswap32_e = 1;
reg->reg1_interrupt.sw_dec_irq_dis = 0;
reg->reg2_dec_ctrl.sw_dec_axi_rn_id = 0xff;
reg->reg3.sw_dec_axi_wr_id = 0;
reg->reg2_dec_ctrl.sw_dec_max_burst = DEC_VDPU1_BUS_BURST_LENGTH_16;
reg->reg2_dec_ctrl.sw_dec_data_disc_e = DEC_VDPU1_DATA_DISCARD_ENABLE;
reg->reg2_dec_ctrl.sw_dec_timeout_e = 1;
reg->reg2_dec_ctrl.sw_dec_clk_gate_e = 1;
jpegd_dbg_func("exit\n");
return MPP_OK;
}
static MPP_RET jpegd_gen_regs(JpegdHalCtx *ctx, JpegdSyntax *syntax)
{
jpegd_dbg_func("enter\n");
JpegdIocRegInfo *info = (JpegdIocRegInfo *)ctx->regs;
JpegRegSet *reg = &info->regs;
JpegdSyntax *s = syntax;
jpegd_regs_init(reg);
/* Enable jpeg mode */
reg->reg1_interrupt.sw_dec_e = 1;
reg->reg3.sw_filtering_dis = 1;
/* JPEG decoder */
reg->reg3.sw_dec_mode = 3;
reg->reg3.sw_pjpeg_e = 0; /* Set JPEG operation mode */
reg->reg3.sw_dec_out_dis = 0;
reg->reg3.sw_rlc_mode_e = 0;
/* frame size, round up the number of mbs */
reg->reg4.sw_pic_mb_h_ext = ((((s->ver_stride) >> (4)) & 0x700) >> 8);
reg->reg4.sw_pic_mb_w_ext = ((((s->hor_stride) >> (4)) & 0xE00) >> 9);
reg->reg4.sw_pic_mb_width = ((s->hor_stride) >> (4)) & 0x1FF;
reg->reg4.sw_pic_mb_height_p = ((s->ver_stride) >> (4)) & 0x0FF;
reg->reg7.sw_pjpeg_fildown_e = s->fill_bottom;
/* Set spectral selection start coefficient */
reg->reg7.sw_pjpeg_ss = s->scan_start;
/* Set spectral selection end coefficient */
reg->reg7.sw_pjpeg_se = s->scan_end;
/* Set the point transform used in the preceding scan */
reg->reg7.sw_pjpeg_ah = s->prev_shift;
/* Set the point transform value */
reg->reg7.sw_pjpeg_al = s->point_transform;
reg->reg5.sw_jpeg_qtables = s->qtable_cnt;
reg->reg5.sw_jpeg_mode = s->yuv_mode;
reg->reg5.sw_jpeg_filright_e = s->fill_right;
reg->reg15.sw_jpeg_slice_h = 0;
/*
* Set bit 21 of reg148 to 1, notifying hardware to decode
* jpeg including DRI segment
*/
reg->reg5.sw_sync_marker_e = 1;
/* tell hardware that height is 8-pixel aligned, but not 16-pixel aligned */
if ((s->height % 16) && ((s->height % 16) <= 8) &&
(s->yuv_mode == JPEGDEC_YUV422 ||
s->yuv_mode == JPEGDEC_YUV444 ||
s->yuv_mode == JPEGDEC_YUV411)) {
reg->reg15.sw_jpeg_height8_flag = 1;
}
/* write VLC code word number to register */
jpegd_write_code_word_number(ctx, s);
/* Create AC/DC/QP tables for hardware */
jpegd_write_qp_ac_dc_table(ctx, s);
/* Select which tables the chromas use */
jpegd_set_chroma_table_id(ctx, s);
/* write table base */
reg->reg40_qtable_base = mpp_buffer_get_fd(ctx->pTableBase);
/* set up stream position for HW decode */
jpegd_set_stream_offset(ctx, s);
/* set restart interval */
if (s->restart_interval) {
reg->reg5.sw_sync_marker_e = 1;
/*
* If exists DRI segment, bit 0 to bit 15 of reg8
* is set to restart interval
*/
reg->reg8.sw_pjpeg_rest_freq = s->restart_interval;
} else {
reg->reg5.sw_sync_marker_e = 0;
}
jpegd_setup_pp(ctx, syntax);
jpegd_dbg_func("exit\n");
return MPP_OK;
}
MPP_RET hal_jpegd_vdpu1_init(void *hal, MppHalCfg *cfg)
{
MPP_RET ret = MPP_OK;
JpegdHalCtx *JpegHalCtx = (JpegdHalCtx *)hal;
mpp_assert(JpegHalCtx);
jpegd_dbg_func("enter\n");
//configure
JpegHalCtx->packet_slots = cfg->packet_slots;
JpegHalCtx->frame_slots = cfg->frame_slots;
JpegHalCtx->dev_type = VPU_CLIENT_VDPU1;
ret = mpp_dev_init(&JpegHalCtx->dev, JpegHalCtx->dev_type);
if (ret) {
mpp_err_f("mpp_dev_init failed. ret: %d\n", ret);
return ret;
}
cfg->dev = JpegHalCtx->dev;
/* allocate regs buffer */
if (JpegHalCtx->regs == NULL) {
JpegHalCtx->regs = mpp_calloc_size(void, sizeof(JpegdIocRegInfo));
if (JpegHalCtx->regs == NULL) {
mpp_err("hal jpegd reg alloc failed\n");
jpegd_dbg_func("exit\n");
return MPP_ERR_NOMEM;
}
}
JpegdIocRegInfo *info = (JpegdIocRegInfo *)JpegHalCtx->regs;
memset(info, 0, sizeof(JpegdIocRegInfo));
//malloc hw buf
if (JpegHalCtx->group == NULL) {
ret = mpp_buffer_group_get_internal(&JpegHalCtx->group,
MPP_BUFFER_TYPE_ION);
if (ret) {
mpp_err_f("mpp_buffer_group_get failed ret %d\n", ret);
return ret;
}
}
ret = mpp_buffer_get(JpegHalCtx->group, &JpegHalCtx->frame_buf,
JPEGD_STREAM_BUFF_SIZE);
if (ret) {
mpp_err_f("get frame buffer failed ret %d\n", ret);
return ret;
}
ret = mpp_buffer_get(JpegHalCtx->group, &JpegHalCtx->pTableBase,
JPEGD_BASELINE_TABLE_SIZE);
if (ret) {
mpp_err_f("get table buffer failed ret %d\n", ret);
return ret;
}
PPInfo *pp_info = &(JpegHalCtx->pp_info);
memset(pp_info, 0, sizeof(PPInfo));
pp_info->pp_enable = 0;
pp_info->pp_in_fmt = PP_IN_FORMAT_YUV420SEMI;
pp_info->pp_out_fmt = PP_OUT_FORMAT_YUV420INTERLAVE;
jpegd_check_have_pp(JpegHalCtx);
JpegHalCtx->output_fmt = MPP_FMT_YUV420SP;
JpegHalCtx->set_output_fmt_flag = 0;
/* init dbg stuff */
JpegHalCtx->hal_debug_enable = 0;
JpegHalCtx->frame_count = 0;
JpegHalCtx->output_yuv_count = 0;
jpegd_dbg_func("exit\n");
return MPP_OK;
}
MPP_RET hal_jpegd_vdpu1_deinit(void *hal)
{
MPP_RET ret = MPP_OK;
JpegdHalCtx *JpegHalCtx = (JpegdHalCtx *)hal;
jpegd_dbg_func("enter\n");
if (JpegHalCtx->dev) {
mpp_dev_deinit(JpegHalCtx->dev);
JpegHalCtx->dev = NULL;
}
if (JpegHalCtx->frame_buf) {
ret = mpp_buffer_put(JpegHalCtx->frame_buf);
if (ret) {
mpp_err_f("put buffer failed\n");
return ret;
}
}
if (JpegHalCtx->pTableBase) {
ret = mpp_buffer_put(JpegHalCtx->pTableBase);
if (ret) {
mpp_err_f("put buffer failed\n");
return ret;
}
}
if (JpegHalCtx->group) {
ret = mpp_buffer_group_put(JpegHalCtx->group);
if (ret) {
mpp_err_f("group free buffer failed\n");
return ret;
}
}
if (JpegHalCtx->regs) {
mpp_free(JpegHalCtx->regs);
JpegHalCtx->regs = NULL;
}
JpegHalCtx->output_fmt = MPP_FMT_YUV420SP;
JpegHalCtx->set_output_fmt_flag = 0;
JpegHalCtx->hal_debug_enable = 0;
JpegHalCtx->frame_count = 0;
JpegHalCtx->output_yuv_count = 0;
jpegd_dbg_func("exit\n");
return MPP_OK;
}
MPP_RET hal_jpegd_vdpu1_gen_regs(void *hal, HalTaskInfo *syn)
{
jpegd_dbg_func("enter\n");
if (NULL == hal || NULL == syn) {
mpp_err_f("NULL pointer");
return MPP_ERR_NULL_PTR;
}
MPP_RET ret = MPP_OK;
JpegdHalCtx *JpegHalCtx = (JpegdHalCtx *)hal;
JpegdSyntax *syntax = (JpegdSyntax *)syn->dec.syntax.data;
MppBuffer streambuf = NULL;
MppBuffer outputBuf = NULL;
ret = jpeg_image_check_size(syntax->hor_stride, syntax->ver_stride);
if (ret)
goto RET;
if (syn->dec.valid) {
jpegd_setup_output_fmt(JpegHalCtx, syntax, syn->dec.output);
if (ret) {
mpp_err_f("setup output format %x failed\n", syntax->output_fmt);
goto RET;
}
/* input stream address */
mpp_buf_slot_get_prop(JpegHalCtx->packet_slots, syn->dec.input,
SLOT_BUFFER, &streambuf);
JpegHalCtx->pkt_fd = mpp_buffer_get_fd(streambuf);
syntax->pkt_len = jpegd_vdpu_tail_0xFF_patch(streambuf, syntax->pkt_len);
/* output picture address */
mpp_buf_slot_get_prop(JpegHalCtx->frame_slots, syn->dec.output,
SLOT_BUFFER, &outputBuf);
JpegHalCtx->frame_fd = mpp_buffer_get_fd(outputBuf);
ret = jpegd_gen_regs(JpegHalCtx, syntax);
if (ret) {
mpp_err_f("generate registers failed\n");
goto RET;
}
}
RET:
if (ret)
syn->dec.valid = 0;
jpegd_dbg_func("exit\n");
return ret;
}
MPP_RET hal_jpegd_vdpu1_start(void *hal, HalTaskInfo *task)
{
MPP_RET ret = MPP_OK;
JpegdHalCtx *JpegHalCtx = (JpegdHalCtx *)hal;
RK_U32 *regs = (RK_U32 *)JpegHalCtx->regs;
jpegd_dbg_func("enter\n");
do {
MppDevRegWrCfg wr_cfg;
MppDevRegRdCfg rd_cfg;
RK_U32 reg_size = mpp_get_ioctl_version() ?
sizeof(((JpegdIocRegInfo *)0)->regs) :
sizeof(JpegdIocRegInfo) - EXTRA_INFO_SIZE;
wr_cfg.reg = regs;
wr_cfg.size = reg_size;
wr_cfg.offset = 0;
ret = mpp_dev_ioctl(JpegHalCtx->dev, MPP_DEV_REG_WR, &wr_cfg);
if (ret) {
mpp_err_f("set register write failed %d\n", ret);
break;
}
rd_cfg.reg = regs;
rd_cfg.size = reg_size;
rd_cfg.offset = 0;
ret = mpp_dev_ioctl(JpegHalCtx->dev, MPP_DEV_REG_RD, &rd_cfg);
if (ret) {
mpp_err_f("set register read failed %d\n", ret);
break;
}
ret = mpp_dev_ioctl(JpegHalCtx->dev, MPP_DEV_CMD_SEND, NULL);
if (ret) {
mpp_err_f("send cmd failed %d\n", ret);
break;
}
} while (0);
(void)task;
jpegd_dbg_func("exit\n");
return ret;
}
MPP_RET hal_jpegd_vdpu1_wait(void *hal, HalTaskInfo *task)
{
MPP_RET ret = MPP_OK;
JpegdHalCtx *JpegHalCtx = (JpegdHalCtx *)hal;
JpegRegSet *reg_out = JpegHalCtx->regs;
RK_U32 errinfo = 1;
MppFrame tmp = NULL;
jpegd_dbg_func("enter\n");
ret = mpp_dev_ioctl(JpegHalCtx->dev, MPP_DEV_CMD_POLL, NULL);
if (ret)
mpp_err_f("poll cmd failed %d\n", ret);
if (reg_out->reg1_interrupt.sw_dec_bus_int) {
mpp_err_f("IRQ BUS ERROR!");
} else if (reg_out->reg1_interrupt.sw_dec_error_int) {
/*
* NOTE: It is a bug of VDPU1, when sample color is YUV422,
* YUV444, YUV411, the height could be aligned with 8 but not 16
*/
if (JpegHalCtx->output_fmt != MPP_FMT_YUV420SP)
ret = 0;
else
mpp_err_f("IRQ STREAM ERROR! %d", JpegHalCtx->output_fmt);
} else if (reg_out->reg1_interrupt.sw_dec_timeout) {
mpp_err_f("IRQ TIMEOUT!");
} else if (reg_out->reg1_interrupt.sw_dec_buffer_int) {
mpp_err_f("IRQ BUFFER EMPTY!");
} else if (reg_out->reg1_interrupt.sw_dec_irq) {
errinfo = 0;
jpegd_dbg_hal("DECODE SUCCESS!");
}
mpp_buf_slot_get_prop(JpegHalCtx->frame_slots, task->dec.output,
SLOT_FRAME_PTR, &tmp);
mpp_frame_set_errinfo(tmp, errinfo);
/* debug information */
if (jpegd_debug & JPEGD_DBG_IO) {
static FILE *jpg_file;
static char name[32];
MppBuffer outputBuf = NULL;
void *base = NULL;
mpp_buf_slot_get_prop(JpegHalCtx->frame_slots, task->dec.output,
SLOT_BUFFER, &outputBuf);
base = mpp_buffer_get_ptr(outputBuf);
snprintf(name, sizeof(name), "/tmp/output%02d.yuv",
JpegHalCtx->output_yuv_count);
jpg_file = fopen(name, "wb+");
if (jpg_file) {
JpegdSyntax *s = (JpegdSyntax *)task->dec.syntax.data;
RK_U32 width = s->hor_stride;
RK_U32 height = s->ver_stride;
fwrite(base, width * height * 3 / 2, 1, jpg_file);
jpegd_dbg_io("frame_%02d output YUV(%d*%d) saving to %s\n",
JpegHalCtx->output_yuv_count,
width, height, name);
fclose(jpg_file);
JpegHalCtx->output_yuv_count++;
}
}
memset(®_out->reg1_interrupt, 0, sizeof(RK_U32));
jpegd_dbg_func("exit\n");
return ret;
}
MPP_RET hal_jpegd_vdpu1_reset(void *hal)
{
jpegd_dbg_func("enter\n");
MPP_RET ret = MPP_OK;
JpegdHalCtx *JpegHalCtx = (JpegdHalCtx *)hal;
(void)JpegHalCtx;
return ret;
}
MPP_RET hal_jpegd_vdpu1_flush(void *hal)
{
jpegd_dbg_func("enter\n");
MPP_RET ret = MPP_OK;
(void)hal;
return ret;
}
MPP_RET hal_jpegd_vdpu1_control(void *hal, MpiCmd cmd_type, void *param)
{
jpegd_dbg_func("enter\n");
MPP_RET ret = MPP_OK;
JpegdHalCtx *JpegHalCtx = (JpegdHalCtx *)hal;
if (NULL == JpegHalCtx) {
mpp_err_f("NULL pointer");
return MPP_ERR_NULL_PTR;
}
switch (cmd_type) {
case MPP_DEC_SET_OUTPUT_FORMAT: {
JpegHalCtx->output_fmt = *((MppFrameFormat *)param);
JpegHalCtx->set_output_fmt_flag = 1;
jpegd_dbg_hal("output_format:%d\n", JpegHalCtx->output_fmt);
if (!MPP_FRAME_FMT_IS_YUV(JpegHalCtx->output_fmt) && !MPP_FRAME_FMT_IS_RGB(JpegHalCtx->output_fmt)) {
mpp_err_f("output format %d is invalid.\n", JpegHalCtx->output_fmt);
ret = MPP_ERR_VALUE;
}
} break;
default :
break;
}
jpegd_dbg_func("exit ret %d\n", ret);
return ret;
}
| 33.455566 | 110 | 0.587714 | [
"transform"
] |
d6562b49d7567cb26ab4b3b6df56bc95cae456e6 | 46,050 | c | C | deps/picotls/lib/fusion.c | Nitrillo/h2o | b718f3dd035660094a151752f34da94671cf442c | [
"MIT"
] | 2 | 2021-06-18T06:43:13.000Z | 2021-07-05T19:00:12.000Z | deps/picotls/lib/fusion.c | Nitrillo/h2o | b718f3dd035660094a151752f34da94671cf442c | [
"MIT"
] | 4 | 2020-06-24T06:08:00.000Z | 2020-12-01T02:03:56.000Z | deps/picotls/lib/fusion.c | Nitrillo/h2o | b718f3dd035660094a151752f34da94671cf442c | [
"MIT"
] | null | null | null | /*
* This source file is licensed under the Apache License 2.0 *and* the MIT
* License. Please agree to *both* of the licensing terms!
*
*
* `transformH` function is a derivative work of OpenSSL. The original work
* is covered by the following license:
*
* Copyright 2013-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*
*
* All other work, including modifications to the `transformH` function is
* covered by the following MIT license:
*
* Copyright (c) 2020 Fastly, Kazuho Oku
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <immintrin.h>
#include <tmmintrin.h>
#include <nmmintrin.h>
#include <wmmintrin.h>
#include "picotls.h"
#include "picotls/fusion.h"
struct ptls_fusion_aesgcm_context {
ptls_fusion_aesecb_context_t ecb;
size_t capacity;
size_t ghash_cnt;
struct ptls_fusion_aesgcm_ghash_precompute {
__m128i H;
__m128i r;
} ghash[0];
};
struct ctr_context {
ptls_cipher_context_t super;
ptls_fusion_aesecb_context_t fusion;
__m128i bits;
uint8_t is_ready;
};
struct aesgcm_context {
ptls_aead_context_t super;
ptls_fusion_aesgcm_context_t *aesgcm;
/**
* retains the static IV in the upper 96 bits (in little endian)
*/
__m128i static_iv;
};
static const uint64_t poly_[2] __attribute__((aligned(16))) = {1, 0xc200000000000000};
#define poly (*(__m128i *)poly_)
static const uint8_t bswap8_[16] __attribute__((aligned(16))) = {15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
#define bswap8 (*(__m128i *)bswap8_)
static const uint8_t one8_[16] __attribute__((aligned(16))) = {1};
#define one8 (*(__m128i *)one8_)
/* This function is covered by the Apache License and the MIT License. The origin is crypto/modes/asm/ghash-x86_64.pl of openssl
* at commit 33388b4. */
static __m128i transformH(__m128i H)
{
// # <<1 twist
// pshufd \$0b11111111,$Hkey,$T2 # broadcast uppermost dword
__m128i t2 = _mm_shuffle_epi32(H, 0xff);
// movdqa $Hkey,$T1
__m128i t1 = H;
// psllq \$1,$Hkey
H = _mm_slli_epi64(H, 1);
// pxor $T3,$T3 #
__m128i t3 = _mm_setzero_si128();
// psrlq \$63,$T1
t1 = _mm_srli_epi64(t1, 63);
// pcmpgtd $T2,$T3 # broadcast carry bit
t3 = _mm_cmplt_epi32(t2, t3);
// pslldq \$8,$T1
t1 = _mm_slli_si128(t1, 8);
// por $T1,$Hkey # H<<=1
H = _mm_or_si128(t1, H);
// # magic reduction
// pand .L0x1c2_polynomial(%rip),$T3
t3 = _mm_and_si128(t3, poly);
// pxor $T3,$Hkey # if(carry) H^=0x1c2_polynomial
H = _mm_xor_si128(t3, H);
return H;
}
// end of Apache License code
static __m128i gfmul(__m128i x, __m128i y)
{
__m128i lo = _mm_clmulepi64_si128(x, y, 0x00);
__m128i hi = _mm_clmulepi64_si128(x, y, 0x11);
__m128i a = _mm_shuffle_epi32(x, 78);
__m128i b = _mm_shuffle_epi32(y, 78);
a = _mm_xor_si128(a, x);
b = _mm_xor_si128(b, y);
a = _mm_clmulepi64_si128(a, b, 0x00);
a = _mm_xor_si128(a, lo);
a = _mm_xor_si128(a, hi);
b = _mm_slli_si128(a, 8);
a = _mm_srli_si128(a, 8);
lo = _mm_xor_si128(lo, b);
hi = _mm_xor_si128(hi, a);
// from https://crypto.stanford.edu/RealWorldCrypto/slides/gueron.pdf
__m128i t = _mm_clmulepi64_si128(lo, poly, 0x10);
lo = _mm_shuffle_epi32(lo, 78);
lo = _mm_xor_si128(lo, t);
t = _mm_clmulepi64_si128(lo, poly, 0x10);
lo = _mm_shuffle_epi32(lo, 78);
lo = _mm_xor_si128(lo, t);
return _mm_xor_si128(hi, lo);
}
struct ptls_fusion_gfmul_state {
__m128i hi, lo, mid;
};
static inline void gfmul_onestep(struct ptls_fusion_gfmul_state *gstate, __m128i X,
struct ptls_fusion_aesgcm_ghash_precompute *precompute)
{
X = _mm_shuffle_epi8(X, bswap8);
__m128i t = _mm_clmulepi64_si128(precompute->H, X, 0x00);
gstate->lo = _mm_xor_si128(gstate->lo, t);
t = _mm_clmulepi64_si128(precompute->H, X, 0x11);
gstate->hi = _mm_xor_si128(gstate->hi, t);
t = _mm_shuffle_epi32(X, 78);
t = _mm_xor_si128(t, X);
t = _mm_clmulepi64_si128(precompute->r, t, 0x00);
gstate->mid = _mm_xor_si128(gstate->mid, t);
}
static inline __m128i gfmul_final(struct ptls_fusion_gfmul_state *gstate, __m128i ek0)
{
/* finish multiplication */
gstate->mid = _mm_xor_si128(gstate->mid, gstate->hi);
gstate->mid = _mm_xor_si128(gstate->mid, gstate->lo);
gstate->lo = _mm_xor_si128(gstate->lo, _mm_slli_si128(gstate->mid, 8));
gstate->hi = _mm_xor_si128(gstate->hi, _mm_srli_si128(gstate->mid, 8));
/* fast reduction, using https://crypto.stanford.edu/RealWorldCrypto/slides/gueron.pdf */
__m128i r = _mm_clmulepi64_si128(gstate->lo, poly, 0x10);
gstate->lo = _mm_shuffle_epi32(gstate->lo, 78);
gstate->lo = _mm_xor_si128(gstate->lo, r);
r = _mm_clmulepi64_si128(gstate->lo, poly, 0x10);
gstate->lo = _mm_shuffle_epi32(gstate->lo, 78);
gstate->lo = _mm_xor_si128(gstate->lo, r);
__m128i tag = _mm_xor_si128(gstate->hi, gstate->lo);
tag = _mm_shuffle_epi8(tag, bswap8);
tag = _mm_xor_si128(tag, ek0);
return tag;
}
static inline __m128i aesecb_encrypt(ptls_fusion_aesecb_context_t *ctx, __m128i v)
{
size_t i;
v = _mm_xor_si128(v, ctx->keys[0]);
for (i = 1; i < ctx->rounds; ++i)
v = _mm_aesenc_si128(v, ctx->keys[i]);
v = _mm_aesenclast_si128(v, ctx->keys[i]);
return v;
}
static const uint8_t loadn_mask[31] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
static const uint8_t loadn_shuffle[31] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, // first 16 bytes map to byte offsets
0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,
0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80}; // latter 15 bytes map to zero
static inline __m128i loadn(const void *p, size_t l)
{
__m128i v, mask = _mm_loadu_si128((__m128i *)(loadn_mask + 16 - l));
uintptr_t mod4k = (uintptr_t)p % 4096;
if (PTLS_LIKELY(mod4k <= 4080) || mod4k + l > 4096) {
v = _mm_loadu_si128(p);
} else {
uintptr_t shift = (uintptr_t)p & 15;
__m128i pattern = _mm_loadu_si128((const __m128i *)(loadn_shuffle + shift));
v = _mm_shuffle_epi8(_mm_load_si128((const __m128i *)((uintptr_t)p - shift)), pattern);
}
v = _mm_and_si128(v, mask);
return v;
}
static inline void storen(void *_p, size_t l, __m128i v)
{
uint8_t buf[16], *p = _p;
*(__m128i *)buf = v;
for (size_t i = 0; i != l; ++i)
p[i] = buf[i];
}
void ptls_fusion_aesgcm_encrypt(ptls_fusion_aesgcm_context_t *ctx, void *output, const void *input, size_t inlen, __m128i ctr,
const void *_aad, size_t aadlen, ptls_aead_supplementary_encryption_t *supp)
{
/* init the bits (we can always run in full), but use the last slot for calculating ek0, if possible */
#define AESECB6_INIT() \
do { \
ctr = _mm_add_epi64(ctr, one8); \
bits0 = _mm_shuffle_epi8(ctr, bswap8); \
ctr = _mm_add_epi64(ctr, one8); \
bits1 = _mm_shuffle_epi8(ctr, bswap8); \
ctr = _mm_add_epi64(ctr, one8); \
bits2 = _mm_shuffle_epi8(ctr, bswap8); \
ctr = _mm_add_epi64(ctr, one8); \
bits3 = _mm_shuffle_epi8(ctr, bswap8); \
ctr = _mm_add_epi64(ctr, one8); \
bits4 = _mm_shuffle_epi8(ctr, bswap8); \
if (PTLS_LIKELY(srclen > 16 * 5)) { \
ctr = _mm_add_epi64(ctr, one8); \
bits5 = _mm_shuffle_epi8(ctr, bswap8); \
} else { \
if ((state & STATE_EK0_BEEN_FED) == 0) { \
bits5 = ek0; \
state |= STATE_EK0_BEEN_FED; \
} \
if ((state & STATE_SUPP_USED) != 0 && srclen <= 16 * 4 && (const __m128i *)supp->input + 1 <= dst_ghash) { \
bits4 = _mm_loadu_si128(supp->input); \
bits4keys = ((struct ctr_context *)supp->ctx)->fusion.keys; \
state |= STATE_SUPP_IN_PROCESS; \
} \
} \
__m128i k = ctx->ecb.keys[0]; \
bits0 = _mm_xor_si128(bits0, k); \
bits1 = _mm_xor_si128(bits1, k); \
bits2 = _mm_xor_si128(bits2, k); \
bits3 = _mm_xor_si128(bits3, k); \
bits4 = _mm_xor_si128(bits4, bits4keys[0]); \
bits5 = _mm_xor_si128(bits5, k); \
} while (0)
/* aes block update */
#define AESECB6_UPDATE(i) \
do { \
__m128i k = ctx->ecb.keys[i]; \
bits0 = _mm_aesenc_si128(bits0, k); \
bits1 = _mm_aesenc_si128(bits1, k); \
bits2 = _mm_aesenc_si128(bits2, k); \
bits3 = _mm_aesenc_si128(bits3, k); \
bits4 = _mm_aesenc_si128(bits4, bits4keys[i]); \
bits5 = _mm_aesenc_si128(bits5, k); \
} while (0)
/* aesenclast */
#define AESECB6_FINAL(i) \
do { \
__m128i k = ctx->ecb.keys[i]; \
bits0 = _mm_aesenclast_si128(bits0, k); \
bits1 = _mm_aesenclast_si128(bits1, k); \
bits2 = _mm_aesenclast_si128(bits2, k); \
bits3 = _mm_aesenclast_si128(bits3, k); \
bits4 = _mm_aesenclast_si128(bits4, bits4keys[i]); \
bits5 = _mm_aesenclast_si128(bits5, k); \
} while (0)
__m128i ek0, bits0, bits1, bits2, bits3, bits4, bits5 = _mm_setzero_si128();
const __m128i *bits4keys = ctx->ecb.keys; /* is changed to supp->ctx.keys when calcurating suppout */
struct ptls_fusion_gfmul_state gstate = {0};
__m128i gdatabuf[6];
__m128i ac = _mm_shuffle_epi8(_mm_set_epi32(0, (int)aadlen * 8, 0, (int)inlen * 8), bswap8);
// src and dst are updated after the chunk is processed
const __m128i *src = input;
__m128i *dst = output;
size_t srclen = inlen;
// aad and src_ghash are updated before the chunk is processed (i.e., when the pointers are fed indo the processor)
const __m128i *aad = _aad, *dst_ghash = dst;
size_t dst_ghashlen = srclen;
struct ptls_fusion_aesgcm_ghash_precompute *ghash_precompute = ctx->ghash + (aadlen + 15) / 16 + (srclen + 15) / 16 + 1;
#define STATE_EK0_BEEN_FED 0x3
#define STATE_EK0_INCOMPLETE 0x2
#define STATE_EK0_READY() ((state & STATE_EK0_BEEN_FED) == 0x1)
#define STATE_SUPP_USED 0x4
#define STATE_SUPP_IN_PROCESS 0x8
int32_t state = supp != NULL ? STATE_SUPP_USED : 0;
/* build counter */
ctr = _mm_insert_epi32(ctr, 1, 0);
ek0 = _mm_shuffle_epi8(ctr, bswap8);
/* start preparing AES */
AESECB6_INIT();
AESECB6_UPDATE(1);
/* build first ghash data (only AAD can be fed at this point, as this would be calculated alongside the first AES block) */
const __m128i *gdata = gdatabuf; // points to the elements fed into GHASH
size_t gdata_cnt = 0;
if (PTLS_LIKELY(aadlen != 0)) {
while (gdata_cnt < 6) {
if (PTLS_LIKELY(aadlen < 16)) {
if (aadlen != 0) {
gdatabuf[gdata_cnt++] = loadn(aad, aadlen);
aadlen = 0;
}
goto MainLoop;
}
gdatabuf[gdata_cnt++] = _mm_loadu_si128(aad++);
aadlen -= 16;
}
}
/* the main loop */
MainLoop:
while (1) {
/* run AES and multiplication in parallel */
size_t i;
for (i = 2; i < gdata_cnt + 2; ++i) {
AESECB6_UPDATE(i);
gfmul_onestep(&gstate, _mm_loadu_si128(gdata++), --ghash_precompute);
}
for (; i < ctx->ecb.rounds; ++i)
AESECB6_UPDATE(i);
AESECB6_FINAL(i);
/* apply the bit stream to src and write to dest */
if (PTLS_LIKELY(srclen >= 6 * 16)) {
#define APPLY(i) _mm_storeu_si128(dst + i, _mm_xor_si128(_mm_loadu_si128(src + i), bits##i))
APPLY(0);
APPLY(1);
APPLY(2);
APPLY(3);
APPLY(4);
APPLY(5);
#undef APPLY
dst += 6;
src += 6;
srclen -= 6 * 16;
} else {
if ((state & STATE_EK0_BEEN_FED) == STATE_EK0_BEEN_FED) {
ek0 = bits5;
state &= ~STATE_EK0_INCOMPLETE;
}
if ((state & STATE_SUPP_IN_PROCESS) != 0) {
_mm_storeu_si128((__m128i *)supp->output, bits4);
state &= ~(STATE_SUPP_USED | STATE_SUPP_IN_PROCESS);
}
if (srclen != 0) {
#define APPLY(i) \
do { \
if (PTLS_LIKELY(srclen >= 16)) { \
_mm_storeu_si128(dst++, _mm_xor_si128(_mm_loadu_si128(src++), bits##i)); \
srclen -= 16; \
} else if (PTLS_LIKELY(srclen != 0)) { \
bits0 = bits##i; \
goto ApplyRemainder; \
} else { \
goto ApplyEnd; \
} \
} while (0)
APPLY(0);
APPLY(1);
APPLY(2);
APPLY(3);
APPLY(4);
APPLY(5);
#undef APPLY
goto ApplyEnd;
ApplyRemainder:
storen(dst, srclen, _mm_xor_si128(loadn(src, srclen), bits0));
dst = (__m128i *)((uint8_t *)dst + srclen);
srclen = 0;
ApplyEnd:;
}
}
/* next block AES starts here */
AESECB6_INIT();
AESECB6_UPDATE(1);
/* setup gdata */
if (PTLS_UNLIKELY(aadlen != 0)) {
gdata_cnt = 0;
while (gdata_cnt < 6) {
if (aadlen < 16) {
if (aadlen != 0) {
gdatabuf[gdata_cnt++] = loadn(aad, aadlen);
aadlen = 0;
}
goto GdataFillDST;
}
gdatabuf[gdata_cnt++] = _mm_loadu_si128(aad++);
aadlen -= 16;
}
gdata = gdatabuf;
} else if (PTLS_LIKELY(dst_ghashlen >= 6 * 16)) {
gdata = dst_ghash;
gdata_cnt = 6;
dst_ghash += 6;
dst_ghashlen -= 96;
} else {
gdata_cnt = 0;
GdataFillDST:
while (gdata_cnt < 6) {
if (dst_ghashlen < 16) {
if (dst_ghashlen != 0) {
gdatabuf[gdata_cnt++] = loadn(dst_ghash, dst_ghashlen);
dst_ghashlen = 0;
}
if (gdata_cnt < 6)
goto Finish;
break;
}
gdatabuf[gdata_cnt++] = _mm_loadu_si128(dst_ghash++);
dst_ghashlen -= 16;
}
gdata = gdatabuf;
}
}
Finish:
gdatabuf[gdata_cnt++] = ac;
/* We have complete set of data to be fed into GHASH. Let's finish the remaining calculation.
* Note that by now, all AES operations for payload encryption and ek0 are complete. This is is because it is necessary for GCM
* to process at least the same amount of data (i.e. payload-blocks + AC), and because AES is at least one 96-byte block ahead.
*/
assert(STATE_EK0_READY());
for (size_t i = 0; i < gdata_cnt; ++i)
gfmul_onestep(&gstate, gdatabuf[i], --ghash_precompute);
_mm_storeu_si128(dst, gfmul_final(&gstate, ek0));
/* Finish the calculation of supplemental vector. Done at the very last, because the sample might cover the GCM tag. */
if ((state & STATE_SUPP_USED) != 0) {
size_t i;
if ((state & STATE_SUPP_IN_PROCESS) == 0) {
bits4keys = ((struct ctr_context *)supp->ctx)->fusion.keys;
bits4 = _mm_xor_si128(_mm_loadu_si128(supp->input), bits4keys[0]);
i = 1;
} else {
i = 2;
}
do {
bits4 = _mm_aesenc_si128(bits4, bits4keys[i++]);
} while (i != ctx->ecb.rounds);
bits4 = _mm_aesenclast_si128(bits4, bits4keys[i]);
_mm_storeu_si128((__m128i *)supp->output, bits4);
}
#undef AESECB6_INIT
#undef AESECB6_UPDATE
#undef AESECB6_FINAL
#undef STATE_EK0_BEEN_FOUND
#undef STATE_EK0_READY
#undef STATE_SUPP_IN_PROCESS
}
int ptls_fusion_aesgcm_decrypt(ptls_fusion_aesgcm_context_t *ctx, void *output, const void *input, size_t inlen, __m128i ctr,
const void *_aad, size_t aadlen, const void *tag)
{
__m128i ek0 = _mm_setzero_si128(), bits0, bits1 = _mm_setzero_si128(), bits2 = _mm_setzero_si128(), bits3 = _mm_setzero_si128(),
bits4 = _mm_setzero_si128(), bits5 = _mm_setzero_si128();
struct ptls_fusion_gfmul_state gstate = {0};
__m128i gdatabuf[6];
__m128i ac = _mm_shuffle_epi8(_mm_set_epi32(0, (int)aadlen * 8, 0, (int)inlen * 8), bswap8);
struct ptls_fusion_aesgcm_ghash_precompute *ghash_precompute = ctx->ghash + (aadlen + 15) / 16 + (inlen + 15) / 16 + 1;
const __m128i *gdata; // points to the elements fed into GHASH
size_t gdata_cnt;
const __m128i *src_ghash = input, *src_aes = input, *aad = _aad;
__m128i *dst = output;
size_t nondata_aes_cnt = 0, src_ghashlen = inlen, src_aeslen = inlen;
/* schedule ek0 and suppkey */
ctr = _mm_add_epi64(ctr, one8);
bits0 = _mm_xor_si128(_mm_shuffle_epi8(ctr, bswap8), ctx->ecb.keys[0]);
++nondata_aes_cnt;
#define STATE_IS_FIRST_RUN 0x1
#define STATE_GHASH_HAS_MORE 0x2
int state = STATE_IS_FIRST_RUN | STATE_GHASH_HAS_MORE;
/* the main loop */
while (1) {
/* setup gdata */
if (PTLS_UNLIKELY(aadlen != 0)) {
gdata = gdatabuf;
gdata_cnt = 0;
while (gdata_cnt < 6) {
if (aadlen < 16) {
if (aadlen != 0) {
gdatabuf[gdata_cnt++] = loadn(aad, aadlen);
aadlen = 0;
++nondata_aes_cnt;
}
goto GdataFillSrc;
}
gdatabuf[gdata_cnt++] = _mm_loadu_si128(aad++);
aadlen -= 16;
++nondata_aes_cnt;
}
} else if (PTLS_LIKELY(src_ghashlen >= 6 * 16)) {
gdata = src_ghash;
gdata_cnt = 6;
src_ghash += 6;
src_ghashlen -= 6 * 16;
} else {
gdata = gdatabuf;
gdata_cnt = 0;
GdataFillSrc:
while (gdata_cnt < 6) {
if (src_ghashlen < 16) {
if (src_ghashlen != 0) {
gdatabuf[gdata_cnt++] = loadn(src_ghash, src_ghashlen);
src_ghash = (__m128i *)((uint8_t *)src_ghash + src_ghashlen);
src_ghashlen = 0;
}
if (gdata_cnt < 6 && (state & STATE_GHASH_HAS_MORE) != 0) {
gdatabuf[gdata_cnt++] = ac;
state &= ~STATE_GHASH_HAS_MORE;
}
break;
}
gdatabuf[gdata_cnt++] = _mm_loadu_si128(src_ghash++);
src_ghashlen -= 16;
}
}
/* setup aes bits */
if (PTLS_LIKELY(nondata_aes_cnt == 0))
goto InitAllBits;
switch (nondata_aes_cnt) {
#define INIT_BITS(n, keys) \
case n: \
ctr = _mm_add_epi64(ctr, one8); \
bits##n = _mm_xor_si128(_mm_shuffle_epi8(ctr, bswap8), keys[0]);
InitAllBits:
INIT_BITS(0, ctx->ecb.keys);
INIT_BITS(1, ctx->ecb.keys);
INIT_BITS(2, ctx->ecb.keys);
INIT_BITS(3, ctx->ecb.keys);
INIT_BITS(4, ctx->ecb.keys);
INIT_BITS(5, ctx->ecb.keys);
#undef INIT_BITS
}
{ /* run aes and ghash */
#define AESECB6_UPDATE(i) \
do { \
__m128i k = ctx->ecb.keys[i]; \
bits0 = _mm_aesenc_si128(bits0, k); \
bits1 = _mm_aesenc_si128(bits1, k); \
bits2 = _mm_aesenc_si128(bits2, k); \
bits3 = _mm_aesenc_si128(bits3, k); \
bits4 = _mm_aesenc_si128(bits4, k); \
bits5 = _mm_aesenc_si128(bits5, k); \
} while (0)
size_t aesi;
for (aesi = 1; aesi <= gdata_cnt; ++aesi) {
AESECB6_UPDATE(aesi);
gfmul_onestep(&gstate, _mm_loadu_si128(gdata++), --ghash_precompute);
}
for (; aesi < ctx->ecb.rounds; ++aesi)
AESECB6_UPDATE(aesi);
__m128i k = ctx->ecb.keys[aesi];
bits0 = _mm_aesenclast_si128(bits0, k);
bits1 = _mm_aesenclast_si128(bits1, k);
bits2 = _mm_aesenclast_si128(bits2, k);
bits3 = _mm_aesenclast_si128(bits3, k);
bits4 = _mm_aesenclast_si128(bits4, k);
bits5 = _mm_aesenclast_si128(bits5, k);
#undef AESECB6_UPDATE
}
/* apply aes bits */
if (PTLS_LIKELY(nondata_aes_cnt == 0 && src_aeslen >= 6 * 16)) {
#define APPLY(i) _mm_storeu_si128(dst + i, _mm_xor_si128(_mm_loadu_si128(src_aes + i), bits##i))
APPLY(0);
APPLY(1);
APPLY(2);
APPLY(3);
APPLY(4);
APPLY(5);
#undef APPLY
dst += 6;
src_aes += 6;
src_aeslen -= 6 * 16;
} else {
if ((state & STATE_IS_FIRST_RUN) != 0) {
ek0 = bits0;
state &= ~STATE_IS_FIRST_RUN;
}
switch (nondata_aes_cnt) {
#define APPLY(i) \
case i: \
if (PTLS_LIKELY(src_aeslen > 16)) { \
_mm_storeu_si128(dst++, _mm_xor_si128(_mm_loadu_si128(src_aes++), bits##i)); \
src_aeslen -= 16; \
} else { \
bits0 = bits##i; \
goto Finish; \
}
APPLY(0);
APPLY(1);
APPLY(2);
APPLY(3);
APPLY(4);
APPLY(5);
#undef APPLY
}
nondata_aes_cnt = 0;
}
}
Finish:
if (src_aeslen == 16) {
_mm_storeu_si128(dst, _mm_xor_si128(_mm_loadu_si128(src_aes), bits0));
} else if (src_aeslen != 0) {
storen(dst, src_aeslen, _mm_xor_si128(loadn(src_aes, src_aeslen), bits0));
}
assert((state & STATE_IS_FIRST_RUN) == 0);
/* the only case where AES operation is complete and GHASH is not is when the application of AC is remaining */
if ((state & STATE_GHASH_HAS_MORE) != 0) {
assert(ghash_precompute - 1 == ctx->ghash);
gfmul_onestep(&gstate, ac, --ghash_precompute);
}
__m128i calctag = gfmul_final(&gstate, ek0);
return _mm_movemask_epi8(_mm_cmpeq_epi8(calctag, _mm_loadu_si128(tag))) == 0xffff;
#undef STATE_IS_FIRST_RUN
#undef STATE_GHASH_HAS_MORE
}
static __m128i expand_key(__m128i key, __m128i temp)
{
key = _mm_xor_si128(key, _mm_slli_si128(key, 4));
key = _mm_xor_si128(key, _mm_slli_si128(key, 4));
key = _mm_xor_si128(key, _mm_slli_si128(key, 4));
key = _mm_xor_si128(key, temp);
return key;
}
void ptls_fusion_aesecb_init(ptls_fusion_aesecb_context_t *ctx, int is_enc, const void *key, size_t key_size)
{
assert(is_enc && "decryption is not supported (yet)");
size_t i = 0;
switch (key_size) {
case 16: /* AES128 */
ctx->rounds = 10;
break;
case 32: /* AES256 */
ctx->rounds = 14;
break;
default:
assert(!"invalid key size; AES128 / AES256 are supported");
break;
}
ctx->keys[i++] = _mm_loadu_si128((__m128i *)key);
if (key_size == 32)
ctx->keys[i++] = _mm_loadu_si128((__m128i *)key + 1);
#define EXPAND(R) \
do { \
ctx->keys[i] = expand_key(ctx->keys[i - key_size / 16], \
_mm_shuffle_epi32(_mm_aeskeygenassist_si128(ctx->keys[i - 1], R), _MM_SHUFFLE(3, 3, 3, 3))); \
if (i == ctx->rounds) \
goto Done; \
++i; \
if (key_size > 24) { \
ctx->keys[i] = expand_key(ctx->keys[i - key_size / 16], \
_mm_shuffle_epi32(_mm_aeskeygenassist_si128(ctx->keys[i - 1], R), _MM_SHUFFLE(2, 2, 2, 2))); \
++i; \
} \
} while (0)
EXPAND(0x1);
EXPAND(0x2);
EXPAND(0x4);
EXPAND(0x8);
EXPAND(0x10);
EXPAND(0x20);
EXPAND(0x40);
EXPAND(0x80);
EXPAND(0x1b);
EXPAND(0x36);
#undef EXPAND
Done:
assert(i == ctx->rounds);
}
void ptls_fusion_aesecb_dispose(ptls_fusion_aesecb_context_t *ctx)
{
ptls_clear_memory(ctx, sizeof(*ctx));
}
void ptls_fusion_aesecb_encrypt(ptls_fusion_aesecb_context_t *ctx, void *dst, const void *src)
{
__m128i v = _mm_loadu_si128(src);
v = aesecb_encrypt(ctx, v);
_mm_storeu_si128(dst, v);
}
/**
* returns the number of ghash entries that is required to handle an AEAD block of given size
*/
static size_t aesgcm_calc_ghash_cnt(size_t capacity)
{
// round-up by block size, add to handle worst split of the size between AAD and payload, plus context to hash AC
return (capacity + 15) / 16 + 2;
}
static void setup_one_ghash_entry(ptls_fusion_aesgcm_context_t *ctx)
{
if (ctx->ghash_cnt != 0)
ctx->ghash[ctx->ghash_cnt].H = gfmul(ctx->ghash[ctx->ghash_cnt - 1].H, ctx->ghash[0].H);
__m128i r = _mm_shuffle_epi32(ctx->ghash[ctx->ghash_cnt].H, 78);
r = _mm_xor_si128(r, ctx->ghash[ctx->ghash_cnt].H);
ctx->ghash[ctx->ghash_cnt].r = r;
++ctx->ghash_cnt;
}
ptls_fusion_aesgcm_context_t *ptls_fusion_aesgcm_new(const void *key, size_t key_size, size_t capacity)
{
ptls_fusion_aesgcm_context_t *ctx;
size_t ghash_cnt = aesgcm_calc_ghash_cnt(capacity);
if ((ctx = malloc(sizeof(*ctx) + sizeof(ctx->ghash[0]) * ghash_cnt)) == NULL)
return NULL;
ptls_fusion_aesecb_init(&ctx->ecb, 1, key, key_size);
ctx->capacity = capacity;
ctx->ghash[0].H = aesecb_encrypt(&ctx->ecb, _mm_setzero_si128());
ctx->ghash[0].H = _mm_shuffle_epi8(ctx->ghash[0].H, bswap8);
ctx->ghash[0].H = transformH(ctx->ghash[0].H);
ctx->ghash_cnt = 0;
while (ctx->ghash_cnt < ghash_cnt)
setup_one_ghash_entry(ctx);
return ctx;
}
ptls_fusion_aesgcm_context_t *ptls_fusion_aesgcm_set_capacity(ptls_fusion_aesgcm_context_t *ctx, size_t capacity)
{
size_t ghash_cnt = aesgcm_calc_ghash_cnt(capacity);
if (ghash_cnt <= ctx->ghash_cnt)
return ctx;
if ((ctx = realloc(ctx, sizeof(*ctx) + sizeof(ctx->ghash[0]) * ghash_cnt)) == NULL)
return NULL;
ctx->capacity = capacity;
while (ghash_cnt < ctx->ghash_cnt)
setup_one_ghash_entry(ctx);
return ctx;
}
void ptls_fusion_aesgcm_free(ptls_fusion_aesgcm_context_t *ctx)
{
ptls_clear_memory(ctx->ghash, sizeof(ctx->ghash[0]) * ctx->ghash_cnt);
ctx->ghash_cnt = 0;
ptls_fusion_aesecb_dispose(&ctx->ecb);
free(ctx);
}
static void ctr_dispose(ptls_cipher_context_t *_ctx)
{
struct ctr_context *ctx = (struct ctr_context *)_ctx;
ptls_fusion_aesecb_dispose(&ctx->fusion);
_mm_storeu_si128(&ctx->bits, _mm_setzero_si128());
}
static void ctr_init(ptls_cipher_context_t *_ctx, const void *iv)
{
struct ctr_context *ctx = (struct ctr_context *)_ctx;
_mm_storeu_si128(&ctx->bits, aesecb_encrypt(&ctx->fusion, _mm_loadu_si128(iv)));
ctx->is_ready = 1;
}
static void ctr_transform(ptls_cipher_context_t *_ctx, void *output, const void *input, size_t len)
{
struct ctr_context *ctx = (struct ctr_context *)_ctx;
assert((ctx->is_ready && len <= 16) ||
!"CTR transfomation is supported only once per call to `init` and the maximum size is limited to 16 bytes");
ctx->is_ready = 0;
if (len < 16) {
storen(output, len, _mm_xor_si128(_mm_loadu_si128(&ctx->bits), loadn(input, len)));
} else {
_mm_storeu_si128(output, _mm_xor_si128(_mm_loadu_si128(&ctx->bits), _mm_loadu_si128(input)));
}
}
static int aesctr_setup(ptls_cipher_context_t *_ctx, int is_enc, const void *key, size_t key_size)
{
struct ctr_context *ctx = (struct ctr_context *)_ctx;
ctx->super.do_dispose = ctr_dispose;
ctx->super.do_init = ctr_init;
ctx->super.do_transform = ctr_transform;
ptls_fusion_aesecb_init(&ctx->fusion, 1, key, key_size);
ctx->is_ready = 0;
return 0;
}
static int aes128ctr_setup(ptls_cipher_context_t *ctx, int is_enc, const void *key)
{
return aesctr_setup(ctx, is_enc, key, PTLS_AES128_KEY_SIZE);
}
static int aes256ctr_setup(ptls_cipher_context_t *ctx, int is_enc, const void *key)
{
return aesctr_setup(ctx, is_enc, key, PTLS_AES256_KEY_SIZE);
}
static void aesgcm_dispose_crypto(ptls_aead_context_t *_ctx)
{
struct aesgcm_context *ctx = (struct aesgcm_context *)_ctx;
ptls_fusion_aesgcm_free(ctx->aesgcm);
}
static void aead_do_encrypt_init(ptls_aead_context_t *_ctx, uint64_t seq, const void *aad, size_t aadlen)
{
assert(!"FIXME");
}
static size_t aead_do_encrypt_update(ptls_aead_context_t *_ctx, void *output, const void *input, size_t inlen)
{
assert(!"FIXME");
return SIZE_MAX;
}
static size_t aead_do_encrypt_final(ptls_aead_context_t *_ctx, void *_output)
{
assert(!"FIXME");
return SIZE_MAX;
}
static inline __m128i calc_counter(struct aesgcm_context *ctx, uint64_t seq)
{
__m128i ctr = _mm_setzero_si128();
ctr = _mm_insert_epi64(ctr, seq, 0);
ctr = _mm_slli_si128(ctr, 4);
ctr = _mm_xor_si128(ctx->static_iv, ctr);
return ctr;
}
void aead_do_encrypt(struct st_ptls_aead_context_t *_ctx, void *output, const void *input, size_t inlen, uint64_t seq,
const void *aad, size_t aadlen, ptls_aead_supplementary_encryption_t *supp)
{
struct aesgcm_context *ctx = (void *)_ctx;
if (inlen + aadlen > ctx->aesgcm->capacity)
ctx->aesgcm = ptls_fusion_aesgcm_set_capacity(ctx->aesgcm, inlen + aadlen);
ptls_fusion_aesgcm_encrypt(ctx->aesgcm, output, input, inlen, calc_counter(ctx, seq), aad, aadlen, supp);
}
static size_t aead_do_decrypt(ptls_aead_context_t *_ctx, void *output, const void *input, size_t inlen, uint64_t seq,
const void *aad, size_t aadlen)
{
struct aesgcm_context *ctx = (void *)_ctx;
if (inlen < 16)
return SIZE_MAX;
size_t enclen = inlen - 16;
if (enclen + aadlen > ctx->aesgcm->capacity)
ctx->aesgcm = ptls_fusion_aesgcm_set_capacity(ctx->aesgcm, enclen + aadlen);
if (!ptls_fusion_aesgcm_decrypt(ctx->aesgcm, output, input, enclen, calc_counter(ctx, seq), aad, aadlen,
(const uint8_t *)input + enclen))
return SIZE_MAX;
return enclen;
}
static inline void aesgcm_xor_iv(ptls_aead_context_t *_ctx, const void *_bytes, size_t len)
{
struct aesgcm_context *ctx = (struct aesgcm_context *)_ctx;
__m128i xor_mask = loadn(_bytes, len);
xor_mask = _mm_shuffle_epi8(xor_mask, bswap8);
ctx->static_iv = _mm_xor_si128(ctx->static_iv, xor_mask);
}
static int aesgcm_setup(ptls_aead_context_t *_ctx, int is_enc, const void *key, const void *iv, size_t key_size)
{
struct aesgcm_context *ctx = (struct aesgcm_context *)_ctx;
ctx->static_iv = loadn(iv, PTLS_AESGCM_IV_SIZE);
ctx->static_iv = _mm_shuffle_epi8(ctx->static_iv, bswap8);
if (key == NULL)
return 0;
ctx->super.dispose_crypto = aesgcm_dispose_crypto;
ctx->super.do_xor_iv = aesgcm_xor_iv;
ctx->super.do_encrypt_init = aead_do_encrypt_init;
ctx->super.do_encrypt_update = aead_do_encrypt_update;
ctx->super.do_encrypt_final = aead_do_encrypt_final;
ctx->super.do_encrypt = aead_do_encrypt;
ctx->super.do_decrypt = aead_do_decrypt;
ctx->aesgcm = ptls_fusion_aesgcm_new(key, key_size, 1500 /* assume ordinary packet size */);
return 0;
}
static int aes128gcm_setup(ptls_aead_context_t *ctx, int is_enc, const void *key, const void *iv)
{
return aesgcm_setup(ctx, is_enc, key, iv, PTLS_AES128_KEY_SIZE);
}
static int aes256gcm_setup(ptls_aead_context_t *ctx, int is_enc, const void *key, const void *iv)
{
return aesgcm_setup(ctx, is_enc, key, iv, PTLS_AES256_KEY_SIZE);
}
ptls_cipher_algorithm_t ptls_fusion_aes128ctr = {"AES128-CTR",
PTLS_AES128_KEY_SIZE,
1, // block size
PTLS_AES_IV_SIZE,
sizeof(struct ctr_context),
aes128ctr_setup};
ptls_cipher_algorithm_t ptls_fusion_aes256ctr = {"AES256-CTR",
PTLS_AES256_KEY_SIZE,
1, // block size
PTLS_AES_IV_SIZE,
sizeof(struct ctr_context),
aes256ctr_setup};
ptls_aead_algorithm_t ptls_fusion_aes128gcm = {"AES128-GCM",
PTLS_AESGCM_CONFIDENTIALITY_LIMIT,
PTLS_AESGCM_INTEGRITY_LIMIT,
&ptls_fusion_aes128ctr,
NULL, // &ptls_fusion_aes128ecb,
PTLS_AES128_KEY_SIZE,
PTLS_AESGCM_IV_SIZE,
PTLS_AESGCM_TAG_SIZE,
sizeof(struct aesgcm_context),
aes128gcm_setup};
ptls_aead_algorithm_t ptls_fusion_aes256gcm = {"AES256-GCM",
PTLS_AESGCM_CONFIDENTIALITY_LIMIT,
PTLS_AESGCM_INTEGRITY_LIMIT,
&ptls_fusion_aes256ctr,
NULL, // &ptls_fusion_aes256ecb,
PTLS_AES256_KEY_SIZE,
PTLS_AESGCM_IV_SIZE,
PTLS_AESGCM_TAG_SIZE,
sizeof(struct aesgcm_context),
aes256gcm_setup};
#ifdef _WINDOWS
/**
* ptls_fusion_is_supported_by_cpu:
* Check that the CPU has extended instructions for PCMUL, AES and AVX2.
* This test assumes that the CPU is following the x86/x64 architecture.
* A slightly more refined test could check that the cpu_info spells out
* "genuineIntel" or "authenticAMD", but would fail in presence of
* little known CPU brands or some VM */
int ptls_fusion_is_supported_by_cpu(void)
{
uint32_t cpu_info[4];
uint32_t nb_ids;
int is_supported = 0;
__cpuid(cpu_info, 0);
nb_ids = cpu_info[0];
if (nb_ids >= 7) {
uint32_t leaf1_ecx;
__cpuid(cpu_info, 1);
leaf1_ecx = cpu_info[2];
if (/* PCLMUL */ (leaf1_ecx & (1 << 5)) != 0 && /* AES */ (leaf1_ecx & (1 << 25)) != 0) {
uint32_t leaf7_ebx;
__cpuid(cpu_info, 7);
leaf7_ebx = cpu_info[1];
is_supported = /* AVX2 */ (leaf7_ebx & (1 << 5)) != 0;
}
}
return is_supported;
}
#else
int ptls_fusion_is_supported_by_cpu(void)
{
unsigned leaf1_ecx, leaf7_ebx;
{ /* GCC-specific code to obtain CPU features */
unsigned leaf_cnt;
__asm__("cpuid" : "=a"(leaf_cnt) : "a"(0) : "ebx", "ecx", "edx");
if (leaf_cnt < 7)
return 0;
__asm__("cpuid" : "=c"(leaf1_ecx) : "a"(1) : "ebx", "edx");
__asm__("cpuid" : "=b"(leaf7_ebx) : "a"(7), "c"(0) : "edx");
}
/* AVX2 */
if ((leaf7_ebx & (1 << 5)) == 0)
return 0;
/* AES */
if ((leaf1_ecx & (1 << 25)) == 0)
return 0;
/* PCLMUL */
if ((leaf1_ecx & (1 << 1)) == 0)
return 0;
return 1;
}
#endif
| 43.443396 | 132 | 0.474441 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.