Search is not available for this dataset
max_stars_repo_path
stringlengths 2
976
| max_stars_repo_name
stringlengths 5
109
| max_stars_count
float64 0
191k
| id
stringlengths 1
7
| content
stringlengths 1
11.6M
| score
float64 -0.83
3.86
| int_score
int64 0
4
|
---|---|---|---|---|---|---|
FreeRTOS/Demo/ARM7_LPC2138_Rowley/main.c | ydong08/freertos | 1 | 4 | /*
* FreeRTOS Kernel V10.1.1
* Copyright (C) 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* http://www.FreeRTOS.org
* http://aws.amazon.com/freertos
*
* 1 tab == 4 spaces!
*/
/*
* This file contains a demo created to execute on the Rowley Associates
* LPC2138 CrossFire development board.
*
* main() creates all the demo application tasks, then starts the scheduler.
* The WEB documentation provides more details of the standard demo application
* tasks.
*
* Main.c also creates a task called "Check". This only executes every few
* seconds but has a high priority so is guaranteed to get processor time.
* Its function is to check that all the other tasks are still operational.
* Each standard demo task maintains a unique count that is incremented each
* time the task successfully completes its function. Should any error occur
* within such a task the count is permanently halted. The check task inspects
* the count of each task to ensure it has changed since the last time the
* check task executed. If all the count variables have changed all the tasks
* are still executing error free, and the check task writes "PASS" to the
* CrossStudio terminal IO window. Should any task contain an error at any time
* the error is latched and "FAIL" written to the terminal IO window.
*
* Finally, main() sets up an interrupt service routine and task to handle
* pushes of the button that is built into the CrossFire board. When the button
* is pushed the ISR wakes the button task - which generates a table of task
* status information which is also displayed on the terminal IO window.
*
* A print task is defined to ensure exclusive and consistent access to the
* terminal IO. This is the only task that is allowed to access the terminal.
* The check and button task therefore do not access the terminal directly but
* instead pass a pointer to the message they wish to display to the print task.
*/
/* Standard includes. */
#include <__cross_studio_io.h>
/* Scheduler includes. */
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"
/* Demo app includes. */
#include "BlockQ.h"
#include "death.h"
#include "dynamic.h"
#include "integer.h"
#include "PollQ.h"
#include "blocktim.h"
#include "recmutex.h"
#include "semtest.h"
/* Hardware configuration definitions. */
#define mainBUS_CLK_FULL ( ( unsigned char ) 0x01 )
#define mainLED_BIT 0x80000000
#define mainP0_14__EINT_1 ( 2 << 28 )
#define mainEINT_1_EDGE_SENSITIVE 2
#define mainEINT_1_FALLING_EDGE_SENSITIVE 0
#define mainEINT_1_CHANNEL 15
#define mainEINT_1_VIC_CHANNEL_BIT ( 1 << mainEINT_1_CHANNEL )
#define mainEINT_1_ENABLE_BIT ( 1 << 5 )
/* Demo application definitions. */
#define mainQUEUE_SIZE ( 3 )
#define mainLED_DELAY ( ( TickType_t ) 500 / portTICK_PERIOD_MS )
#define mainERROR_LED_DELAY ( ( TickType_t ) 50 / portTICK_PERIOD_MS )
#define mainCHECK_DELAY ( ( TickType_t ) 5000 / portTICK_PERIOD_MS )
#define mainLIST_BUFFER_SIZE 2048
#define mainNO_DELAY ( 0 )
#define mainSHORT_DELAY ( 150 / portTICK_PERIOD_MS )
/* Task priorities. */
#define mainLED_TASK_PRIORITY ( tskIDLE_PRIORITY + 2 )
#define mainQUEUE_POLL_PRIORITY ( tskIDLE_PRIORITY + 2 )
#define mainCHECK_TASK_PRIORITY ( tskIDLE_PRIORITY + 3 )
#define mainSEM_TEST_PRIORITY ( tskIDLE_PRIORITY + 1 )
#define mainBLOCK_Q_PRIORITY ( tskIDLE_PRIORITY + 2 )
#define mainPRINT_TASK_PRIORITY ( tskIDLE_PRIORITY + 0 )
/*-----------------------------------------------------------*/
/* The semaphore used to wake the button task from within the external interrupt
handler. */
SemaphoreHandle_t xButtonSemaphore;
/* The queue that is used to send message to vPrintTask for display in the
terminal output window. */
QueueHandle_t xPrintQueue;
/* The rate at which the LED will toggle. The toggle rate increases if an
error is detected in any task. */
static TickType_t xLED_Delay = mainLED_DELAY;
/*-----------------------------------------------------------*/
/*
* Simply flashes the on board LED every mainLED_DELAY milliseconds.
*/
static void vLEDTask( void *pvParameters );
/*
* Checks the status of all the demo tasks then prints a message to the
* CrossStudio terminal IO windows. The message will be either PASS or FAIL
* depending on the status of the demo applications tasks. A FAIL status will
* be latched.
*
* Messages are not written directly to the terminal, but passed to vPrintTask
* via a queue.
*/
static void vCheckTask( void *pvParameters );
/*
* Controls all terminal output. If a task wants to send a message to the
* terminal IO it posts a pointer to the text to vPrintTask via a queue. This
* ensures serial access to the terminal IO.
*/
static void vPrintTask( void *pvParameter );
/*
* Simply waits for an interrupt to be generated from the built in button, then
* generates a table of tasks states that is then written by vPrintTask to the
* terminal output window within CrossStudio.
*/
static void vButtonHandlerTask( void *pvParameters );
/*-----------------------------------------------------------*/
int main( void )
{
/* Setup the peripheral bus to be the same as the PLL output. */
VPBDIV = mainBUS_CLK_FULL;
/* Create the queue used to pass message to vPrintTask. */
xPrintQueue = xQueueCreate( mainQUEUE_SIZE, sizeof( char * ) );
/* Create the semaphore used to wake vButtonHandlerTask(). */
vSemaphoreCreateBinary( xButtonSemaphore );
xSemaphoreTake( xButtonSemaphore, 0 );
/* Start the standard demo tasks. */
vStartIntegerMathTasks( tskIDLE_PRIORITY );
vStartPolledQueueTasks( mainQUEUE_POLL_PRIORITY );
vStartSemaphoreTasks( mainSEM_TEST_PRIORITY );
vStartDynamicPriorityTasks();
vStartBlockingQueueTasks( mainBLOCK_Q_PRIORITY );
#if configUSE_PREEMPTION == 1
{
/* The timing of console output when not using the preemptive
scheduler causes the block time tests to detect a timing problem. */
vCreateBlockTimeTasks();
}
#endif
vStartRecursiveMutexTasks();
/* Start the tasks defined within this file. */
xTaskCreate( vLEDTask, "LED", configMINIMAL_STACK_SIZE, NULL, mainLED_TASK_PRIORITY, NULL );
xTaskCreate( vCheckTask, "Check", configMINIMAL_STACK_SIZE, NULL, mainCHECK_TASK_PRIORITY, NULL );
xTaskCreate( vPrintTask, "Print", configMINIMAL_STACK_SIZE, NULL, mainPRINT_TASK_PRIORITY, NULL );
xTaskCreate( vButtonHandlerTask, "Button", configMINIMAL_STACK_SIZE, NULL, mainCHECK_TASK_PRIORITY, NULL );
/* Start the scheduler. */
vTaskStartScheduler();
/* The scheduler should now be running, so we will only ever reach here if we
ran out of heap space. */
return 0;
}
/*-----------------------------------------------------------*/
static void vLEDTask( void *pvParameters )
{
/* Just to remove compiler warnings. */
( void ) pvParameters;
/* Configure IO. */
IO0DIR |= mainLED_BIT;
IO0SET = mainLED_BIT;
for( ;; )
{
/* Not very exiting - just delay... */
vTaskDelay( xLED_Delay );
/* ...set the IO ... */
IO0CLR = mainLED_BIT;
/* ...delay again... */
vTaskDelay( xLED_Delay );
/* ...then clear the IO. */
IO0SET = mainLED_BIT;
}
}
/*-----------------------------------------------------------*/
static void vCheckTask( void *pvParameters )
{
portBASE_TYPE xErrorOccurred = pdFALSE;
TickType_t xLastExecutionTime;
const char * const pcPassMessage = "PASS\n";
const char * const pcFailMessage = "FAIL\n";
/* Just to remove compiler warnings. */
( void ) pvParameters;
/* Initialise xLastExecutionTime so the first call to vTaskDelayUntil()
works correctly. */
xLastExecutionTime = xTaskGetTickCount();
for( ;; )
{
/* Perform this check every mainCHECK_DELAY milliseconds. */
vTaskDelayUntil( &xLastExecutionTime, mainCHECK_DELAY );
/* Has an error been found in any task? */
if( xAreIntegerMathsTaskStillRunning() != pdTRUE )
{
xErrorOccurred = pdTRUE;
}
if( xArePollingQueuesStillRunning() != pdTRUE )
{
xErrorOccurred = pdTRUE;
}
if( xAreSemaphoreTasksStillRunning() != pdTRUE )
{
xErrorOccurred = pdTRUE;
}
if( xAreDynamicPriorityTasksStillRunning() != pdTRUE )
{
xErrorOccurred = pdTRUE;
}
if( xAreBlockingQueuesStillRunning() != pdTRUE )
{
xErrorOccurred = pdTRUE;
}
#if configUSE_PREEMPTION == 1
{
/* The timing of console output when not using the preemptive
scheduler causes the block time tests to detect a timing problem. */
if( xAreBlockTimeTestTasksStillRunning() != pdTRUE )
{
xErrorOccurred = pdTRUE;
}
}
#endif
if( xAreRecursiveMutexTasksStillRunning() != pdTRUE )
{
xErrorOccurred = pdTRUE;
}
/* Send either a pass or fail message. If an error is found it is
never cleared again. */
if( xErrorOccurred == pdTRUE )
{
xLED_Delay = mainERROR_LED_DELAY;
xQueueSend( xPrintQueue, &pcFailMessage, portMAX_DELAY );
}
else
{
xQueueSend( xPrintQueue, &pcPassMessage, portMAX_DELAY );
}
}
}
/*-----------------------------------------------------------*/
static void vPrintTask( void *pvParameters )
{
char *pcMessage;
/* Just to stop compiler warnings. */
( void ) pvParameters;
for( ;; )
{
/* Wait for a message to arrive. */
while( xQueueReceive( xPrintQueue, &pcMessage, portMAX_DELAY ) != pdPASS );
/* Write the message to the terminal IO. */
#ifndef NDEBUG
debug_printf( "%s", pcMessage );
#endif
}
}
/*-----------------------------------------------------------*/
static void vButtonHandlerTask( void *pvParameters )
{
static char cListBuffer[ mainLIST_BUFFER_SIZE ];
const char *pcList = &( cListBuffer[ 0 ] );
const char * const pcHeader = "\nTask State Priority Stack #\n************************************************";
extern void (vButtonISRWrapper) ( void );
/* Just to stop compiler warnings. */
( void ) pvParameters;
/* Configure the interrupt. */
portENTER_CRITICAL();
{
/* Configure P0.14 to generate interrupts. */
PINSEL0 |= mainP0_14__EINT_1;
EXTMODE = mainEINT_1_EDGE_SENSITIVE;
EXTPOLAR = mainEINT_1_FALLING_EDGE_SENSITIVE;
/* Setup the VIC for EINT 1. */
VICIntSelect &= ~mainEINT_1_VIC_CHANNEL_BIT;
VICIntEnable |= mainEINT_1_VIC_CHANNEL_BIT;
VICVectAddr1 = ( long ) vButtonISRWrapper;
VICVectCntl1 = mainEINT_1_ENABLE_BIT | mainEINT_1_CHANNEL;
}
portEXIT_CRITICAL();
for( ;; )
{
/* For debouncing, wait a while then clear the semaphore. */
vTaskDelay( mainSHORT_DELAY );
xSemaphoreTake( xButtonSemaphore, mainNO_DELAY );
/* Wait for an interrupt. */
xSemaphoreTake( xButtonSemaphore, portMAX_DELAY );
/* Send the column headers to the print task for display. */
xQueueSend( xPrintQueue, &pcHeader, portMAX_DELAY );
/* Create the list of task states. */
vTaskList( cListBuffer );
/* Send the task status information to the print task for display. */
xQueueSend( xPrintQueue, &pcList, portMAX_DELAY );
}
}
/*-----------------------------------------------------------*/
void vApplicationStackOverflowHook( TaskHandle_t pxTask, char *pcTaskName )
{
/* Check pcTaskName for the name of the offending task, or pxCurrentTCB
if pcTaskName has itself been corrupted. */
( void ) pxTask;
( void ) pcTaskName;
for( ;; );
}
| 1.726563 | 2 |
hackathon/2010/li_yun/ITK-V3D-Plugins/Source/RegistrationIntegrated/FilterPlugin/CastOut.h | zzhmark/vaa3d_tools | 1 | 12 | #ifndef __CastOut_H__
#define __CastOut_H__
#include <QtGui>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <v3d_interface.h>
class CastOutPlugin : public QObject, public V3DPluginInterface2
{
Q_OBJECT
Q_INTERFACES(V3DPluginInterface2)
public:
CastOutPlugin() {}
QStringList menulist() const;
QStringList funclist() const;
void domenu(const QString & menu_name, V3DPluginCallback2 & callback, QWidget * parent);
bool dofunc(const QString & func_name, const V3DPluginArgList & input, V3DPluginArgList & output,
V3DPluginCallback2 & v3d, QWidget * parent);
};
#endif
| 1.101563 | 1 |
System/Library/PrivateFrameworks/GameCenterUI.framework/UICollectionViewDelegate.h | lechium/tvOS130Headers | 11 | 20 | /*
* This header is generated by classdump-dyld 1.0
* on Tuesday, November 5, 2019 at 2:40:55 AM Mountain Standard Time
* Operating System: Version 13.0 (Build 17J586)
* Image Source: /System/Library/PrivateFrameworks/GameCenterUI.framework/GameCenterUI
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>.
*/
@protocol UICollectionViewDelegate <UIScrollViewDelegate>
@optional
-(void)collectionView:(id)arg1 didSelectItemAtIndexPath:(id)arg2;
-(BOOL)collectionView:(id)arg1 shouldHighlightItemAtIndexPath:(id)arg2;
-(void)collectionView:(id)arg1 didHighlightItemAtIndexPath:(id)arg2;
-(void)collectionView:(id)arg1 didUnhighlightItemAtIndexPath:(id)arg2;
-(BOOL)collectionView:(id)arg1 shouldSelectItemAtIndexPath:(id)arg2;
-(BOOL)collectionView:(id)arg1 shouldDeselectItemAtIndexPath:(id)arg2;
-(void)collectionView:(id)arg1 didDeselectItemAtIndexPath:(id)arg2;
-(void)collectionView:(id)arg1 willDisplayCell:(id)arg2 forItemAtIndexPath:(id)arg3;
-(void)collectionView:(id)arg1 willDisplaySupplementaryView:(id)arg2 forElementKind:(id)arg3 atIndexPath:(id)arg4;
-(void)collectionView:(id)arg1 didEndDisplayingCell:(id)arg2 forItemAtIndexPath:(id)arg3;
-(void)collectionView:(id)arg1 didEndDisplayingSupplementaryView:(id)arg2 forElementOfKind:(id)arg3 atIndexPath:(id)arg4;
-(BOOL)collectionView:(id)arg1 shouldShowMenuForItemAtIndexPath:(id)arg2;
-(BOOL)collectionView:(id)arg1 canPerformAction:(SEL)arg2 forItemAtIndexPath:(id)arg3 withSender:(id)arg4;
-(void)collectionView:(id)arg1 performAction:(SEL)arg2 forItemAtIndexPath:(id)arg3 withSender:(id)arg4;
-(id)collectionView:(id)arg1 transitionLayoutForOldLayout:(id)arg2 newLayout:(id)arg3;
-(BOOL)collectionView:(id)arg1 canFocusItemAtIndexPath:(id)arg2;
-(BOOL)collectionView:(id)arg1 shouldUpdateFocusInContext:(id)arg2;
-(void)collectionView:(id)arg1 didUpdateFocusInContext:(id)arg2 withAnimationCoordinator:(id)arg3;
-(id)indexPathForPreferredFocusedViewInCollectionView:(id)arg1;
-(id)collectionView:(id)arg1 targetIndexPathForMoveFromItemAtIndexPath:(id)arg2 toProposedIndexPath:(id)arg3;
-(CGPoint*)collectionView:(id)arg1 targetContentOffsetForProposedContentOffset:(CGPoint)arg2;
-(BOOL)collectionView:(id)arg1 shouldSpringLoadItemAtIndexPath:(id)arg2 withContext:(id)arg3;
-(BOOL)collectionView:(id)arg1 shouldBeginMultipleSelectionInteractionAtIndexPath:(id)arg2;
-(void)collectionView:(id)arg1 didBeginMultipleSelectionInteractionAtIndexPath:(id)arg2;
-(void)collectionViewDidEndMultipleSelectionInteraction:(id)arg1;
-(id)collectionView:(id)arg1 contextMenuConfigurationForItemAtIndexPath:(id)arg2 point:(CGPoint)arg3;
-(id)collectionView:(id)arg1 previewForHighlightingContextMenuWithConfiguration:(id)arg2;
-(id)collectionView:(id)arg1 previewForDismissingContextMenuWithConfiguration:(id)arg2;
-(void)collectionView:(id)arg1 willPerformPreviewActionForMenuWithConfiguration:(id)arg2 animator:(id)arg3;
@end
| 0.855469 | 1 |
Pods/FirebaseFirestore/Firestore/core/src/firebase/firestore/local/remote_document_cache.h | MrsTrier/RememberArt | 0 | 28 | version https://git-lfs.github.com/spec/v1
oid sha256:2b116292015dce87b1e1e8ac40f7084088963b307261b85e8923e01a84f4dd51
size 3344
| 0.015503 | 0 |
platforms/ios/Pods/Headers/Public/NatImage/MWCommon.h | weexjs/weex-plugins | 2 | 36 | //
// MWPreprocessor.h
// MWPhotoBrowser
//
// Created by <NAME> on 01/10/2013.
//
#define SYSTEM_VERSION_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)
| 0.167969 | 0 |
tests/kernel/workq/work_queue/src/main.c | jeffrizzo/zephyr | 1 | 44 | /*
* Copyright (c) 2016 Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <stdbool.h>
#include <zephyr.h>
#include <ztest.h>
#include <tc_util.h>
#include <sys/util.h>
#define NUM_TEST_ITEMS 6
/* Each work item takes 100ms */
#define WORK_ITEM_WAIT 100
/* In fact, each work item could take up to this value */
#define WORK_ITEM_WAIT_ALIGNED \
k_ticks_to_ms_floor64(k_ms_to_ticks_ceil32(WORK_ITEM_WAIT) + _TICK_ALIGN)
/*
* Wait 50ms between work submissions, to ensure co-op and prempt
* preempt thread submit alternatively.
*/
#define SUBMIT_WAIT 50
#define STACK_SIZE (1024 + CONFIG_TEST_EXTRA_STACKSIZE)
/* How long to wait for the full test suite to complete. Allow for a
* little slop
*/
#define CHECK_WAIT ((NUM_TEST_ITEMS + 1) * WORK_ITEM_WAIT_ALIGNED)
struct delayed_test_item {
int key;
struct k_delayed_work work;
};
struct triggered_test_item {
int key;
struct k_work_poll work;
struct k_poll_signal signal;
struct k_poll_event event;
};
static K_THREAD_STACK_DEFINE(co_op_stack, STACK_SIZE);
static struct k_thread co_op_data;
static struct delayed_test_item delayed_tests[NUM_TEST_ITEMS];
static struct triggered_test_item triggered_tests[NUM_TEST_ITEMS];
static int results[NUM_TEST_ITEMS];
static int num_results;
static int expected_poll_result;
static void work_handler(struct k_work *work)
{
struct delayed_test_item *ti =
CONTAINER_OF(work, struct delayed_test_item, work);
TC_PRINT(" - Running test item %d\n", ti->key);
k_msleep(WORK_ITEM_WAIT);
results[num_results++] = ti->key;
}
/**
* @ingroup kernel_workqueue_tests
* @see k_work_init()
*/
static void delayed_test_items_init(void)
{
int i;
for (i = 0; i < NUM_TEST_ITEMS; i++) {
delayed_tests[i].key = i + 1;
k_work_init(&delayed_tests[i].work.work, work_handler);
}
}
static void reset_results(void)
{
int i;
for (i = 0; i < NUM_TEST_ITEMS; i++) {
results[i] = 0;
}
num_results = 0;
}
static void coop_work_main(int arg1, int arg2)
{
int i;
ARG_UNUSED(arg1);
ARG_UNUSED(arg2);
/* Let the preempt thread submit the first work item. */
k_msleep(SUBMIT_WAIT / 2);
for (i = 1; i < NUM_TEST_ITEMS; i += 2) {
TC_PRINT(" - Submitting work %d from coop thread\n", i + 1);
k_work_submit(&delayed_tests[i].work.work);
k_msleep(SUBMIT_WAIT);
}
}
/**
* @ingroup kernel_workqueue_tests
* @see k_work_submit()
*/
static void delayed_test_items_submit(void)
{
int i;
k_thread_create(&co_op_data, co_op_stack, STACK_SIZE,
(k_thread_entry_t)coop_work_main,
NULL, NULL, NULL, K_PRIO_COOP(10), 0, K_NO_WAIT);
for (i = 0; i < NUM_TEST_ITEMS; i += 2) {
TC_PRINT(" - Submitting work %d from preempt thread\n", i + 1);
k_work_submit(&delayed_tests[i].work.work);
k_msleep(SUBMIT_WAIT);
}
}
static void check_results(int num_tests)
{
int i;
zassert_equal(num_results, num_tests,
"*** work items finished: %d (expected: %d)\n",
num_results, num_tests);
for (i = 0; i < num_tests; i++) {
zassert_equal(results[i], i + 1,
"*** got result %d in position %d"
" (expected %d)\n",
results[i], i, i + 1);
}
}
/**
* @brief Test work queue items submission sequence
*
* @ingroup kernel_workqueue_tests
*
* @see k_work_init(), k_work_submit()
*/
static void test_sequence(void)
{
TC_PRINT(" - Initializing test items\n");
delayed_test_items_init();
TC_PRINT(" - Submitting test items\n");
delayed_test_items_submit();
TC_PRINT(" - Waiting for work to finish\n");
k_msleep(CHECK_WAIT);
check_results(NUM_TEST_ITEMS);
reset_results();
}
static void resubmit_work_handler(struct k_work *work)
{
struct delayed_test_item *ti =
CONTAINER_OF(work, struct delayed_test_item, work);
k_msleep(WORK_ITEM_WAIT);
results[num_results++] = ti->key;
if (ti->key < NUM_TEST_ITEMS) {
ti->key++;
TC_PRINT(" - Resubmitting work\n");
k_work_submit(work);
}
}
/**
* @brief Test work queue item resubmission
*
* @ingroup kernel_workqueue_tests
*
* @see k_work_submit()
*/
static void test_resubmit(void)
{
TC_PRINT("Starting resubmit test\n");
delayed_tests[0].key = 1;
delayed_tests[0].work.work.handler = resubmit_work_handler;
TC_PRINT(" - Submitting work\n");
k_work_submit(&delayed_tests[0].work.work);
TC_PRINT(" - Waiting for work to finish\n");
k_msleep(CHECK_WAIT);
TC_PRINT(" - Checking results\n");
check_results(NUM_TEST_ITEMS);
reset_results();
}
static void delayed_work_handler(struct k_work *work)
{
struct delayed_test_item *ti =
CONTAINER_OF(work, struct delayed_test_item, work);
TC_PRINT(" - Running delayed test item %d\n", ti->key);
results[num_results++] = ti->key;
}
/**
* @brief Test delayed work queue init
*
* @ingroup kernel_workqueue_tests
*
* @see k_delayed_work_init()
*/
static void test_delayed_init(void)
{
int i;
for (i = 0; i < NUM_TEST_ITEMS; i++) {
delayed_tests[i].key = i + 1;
k_delayed_work_init(&delayed_tests[i].work,
delayed_work_handler);
}
}
static void coop_delayed_work_main(int arg1, int arg2)
{
int i;
ARG_UNUSED(arg1);
ARG_UNUSED(arg2);
/* Let the preempt thread submit the first work item. */
k_msleep(SUBMIT_WAIT / 2);
for (i = 1; i < NUM_TEST_ITEMS; i += 2) {
TC_PRINT(" - Submitting delayed work %d from"
" coop thread\n", i + 1);
k_delayed_work_submit(&delayed_tests[i].work,
K_MSEC((i + 1) * WORK_ITEM_WAIT));
}
}
/**
* @brief Test delayed workqueue submit
*
* @ingroup kernel_workqueue_tests
*
* @see k_delayed_work_init(), k_delayed_work_submit()
*/
static void test_delayed_submit(void)
{
int i;
k_thread_create(&co_op_data, co_op_stack, STACK_SIZE,
(k_thread_entry_t)coop_delayed_work_main,
NULL, NULL, NULL, K_PRIO_COOP(10), 0, K_NO_WAIT);
for (i = 0; i < NUM_TEST_ITEMS; i += 2) {
TC_PRINT(" - Submitting delayed work %d from"
" preempt thread\n", i + 1);
zassert_true(k_delayed_work_submit(&delayed_tests[i].work,
K_MSEC((i + 1) * WORK_ITEM_WAIT)) == 0, NULL);
}
}
static void coop_delayed_work_cancel_main(int arg1, int arg2)
{
ARG_UNUSED(arg1);
ARG_UNUSED(arg2);
k_delayed_work_submit(&delayed_tests[1].work, K_MSEC(WORK_ITEM_WAIT));
TC_PRINT(" - Cancel delayed work from coop thread\n");
k_delayed_work_cancel(&delayed_tests[1].work);
}
/**
* @brief Test work queue delayed cancel
*
* @ingroup kernel_workqueue_tests
*
* @see k_delayed_work_init(), k_delayed_work_submit(),
* k_delayed_work_cancel()
*/
static void test_delayed_cancel(void)
{
TC_PRINT("Starting delayed cancel test\n");
k_delayed_work_submit(&delayed_tests[0].work, K_MSEC(WORK_ITEM_WAIT));
TC_PRINT(" - Cancel delayed work from preempt thread\n");
k_delayed_work_cancel(&delayed_tests[0].work);
k_thread_create(&co_op_data, co_op_stack, STACK_SIZE,
(k_thread_entry_t)coop_delayed_work_cancel_main,
NULL, NULL, NULL, K_HIGHEST_THREAD_PRIO, 0, K_NO_WAIT);
TC_PRINT(" - Waiting for work to finish\n");
k_msleep(WORK_ITEM_WAIT_ALIGNED);
TC_PRINT(" - Checking results\n");
check_results(0);
}
static void delayed_resubmit_work_handler(struct k_work *work)
{
struct delayed_test_item *ti =
CONTAINER_OF(work, struct delayed_test_item, work);
results[num_results++] = ti->key;
if (ti->key < NUM_TEST_ITEMS) {
ti->key++;
TC_PRINT(" - Resubmitting delayed work\n");
k_delayed_work_submit(&ti->work, K_MSEC(WORK_ITEM_WAIT));
}
}
/**
* @brief Test delayed resubmission of work queue item
*
* @ingroup kernel_workqueue_tests
*
* @see k_delayed_work_init(), k_delayed_work_submit()
*/
static void test_delayed_resubmit(void)
{
TC_PRINT("Starting delayed resubmit test\n");
delayed_tests[0].key = 1;
k_delayed_work_init(&delayed_tests[0].work,
delayed_resubmit_work_handler);
TC_PRINT(" - Submitting delayed work\n");
k_delayed_work_submit(&delayed_tests[0].work, K_MSEC(WORK_ITEM_WAIT));
TC_PRINT(" - Waiting for work to finish\n");
k_msleep(CHECK_WAIT);
TC_PRINT(" - Checking results\n");
check_results(NUM_TEST_ITEMS);
reset_results();
}
static void coop_delayed_work_resubmit(void)
{
int i;
for (i = 0; i < NUM_TEST_ITEMS; i++) {
TC_PRINT(" - Resubmitting delayed work with 1 ms\n");
k_delayed_work_submit(&delayed_tests[0].work, K_MSEC(1));
/* Busy wait 1 ms to force a clash with workqueue */
#if defined(CONFIG_ARCH_POSIX)
k_busy_wait(1000);
#else
volatile u32_t uptime;
uptime = k_uptime_get_32();
while (k_uptime_get_32() == uptime) {
}
#endif
}
}
/**
* @brief Test delayed resubmission of work queue thread
*
* @ingroup kernel_workqueue_tests
*
* @see k_delayed_work_init()
*/
static void test_delayed_resubmit_thread(void)
{
TC_PRINT("Starting delayed resubmit from coop thread test\n");
delayed_tests[0].key = 1;
k_delayed_work_init(&delayed_tests[0].work, delayed_work_handler);
k_thread_create(&co_op_data, co_op_stack, STACK_SIZE,
(k_thread_entry_t)coop_delayed_work_resubmit,
NULL, NULL, NULL, K_PRIO_COOP(10), 0, K_NO_WAIT);
TC_PRINT(" - Waiting for work to finish\n");
k_msleep(WORK_ITEM_WAIT_ALIGNED);
TC_PRINT(" - Checking results\n");
check_results(1);
reset_results();
}
/**
* @brief Test delayed work items
*
* @ingroup kernel_workqueue_tests
*
* @see k_delayed_work_init(), k_delayed_work_submit()
*/
static void test_delayed(void)
{
TC_PRINT("Starting delayed test\n");
TC_PRINT(" - Initializing delayed test items\n");
test_delayed_init();
TC_PRINT(" - Submitting delayed test items\n");
test_delayed_submit();
TC_PRINT(" - Waiting for delayed work to finish\n");
k_msleep(CHECK_WAIT);
TC_PRINT(" - Checking results\n");
check_results(NUM_TEST_ITEMS);
reset_results();
}
static void triggered_work_handler(struct k_work *work)
{
struct triggered_test_item *ti =
CONTAINER_OF(work, struct triggered_test_item, work);
TC_PRINT(" - Running triggered test item %d\n", ti->key);
zassert_equal(ti->work.poll_result, expected_poll_result,
"res %d expect %d", ti->work.poll_result, expected_poll_result);
results[num_results++] = ti->key;
}
/**
* @brief Test triggered work queue init
*
* @ingroup kernel_workqueue_tests
*
* @see k_work_poll_init()
*/
static void test_triggered_init(void)
{
int i;
for (i = 0; i < NUM_TEST_ITEMS; i++) {
triggered_tests[i].key = i + 1;
k_work_poll_init(&triggered_tests[i].work,
triggered_work_handler);
k_poll_signal_init(&triggered_tests[i].signal);
k_poll_event_init(&triggered_tests[i].event,
K_POLL_TYPE_SIGNAL,
K_POLL_MODE_NOTIFY_ONLY,
&triggered_tests[i].signal);
}
}
/**
* @brief Test triggered workqueue submit
*
* @ingroup kernel_workqueue_tests
*
* @see k_work_poll_init(), k_work_poll_submit()
*/
static void test_triggered_submit(k_timeout_t timeout)
{
int i;
for (i = 0; i < NUM_TEST_ITEMS; i++) {
TC_PRINT(" - Submitting triggered work %d\n", i + 1);
zassert_true(k_work_poll_submit(&triggered_tests[i].work,
&triggered_tests[i].event,
1, timeout) == 0, NULL);
}
}
/**
* @brief Trigger triggered workqueue execution
*
* @ingroup kernel_workqueue_tests
*/
static void test_triggered_trigger(void)
{
int i;
for (i = 0; i < NUM_TEST_ITEMS; i++) {
TC_PRINT(" - Triggering work %d\n", i + 1);
zassert_true(k_poll_signal_raise(&triggered_tests[i].signal,
1) == 0, NULL);
}
}
/**
* @brief Test triggered work items
*
* @ingroup kernel_workqueue_tests
*
* @see k_work_poll_init(), k_work_poll_submit()
*/
static void test_triggered(void)
{
TC_PRINT("Starting triggered test\n");
/* As work items are triggered, they should indicate an event. */
expected_poll_result = 0;
TC_PRINT(" - Initializing triggered test items\n");
test_triggered_init();
TC_PRINT(" - Submitting triggered test items\n");
test_triggered_submit(K_FOREVER);
TC_PRINT(" - Triggering test items execution\n");
test_triggered_trigger();
/* Items should be executed when we will be sleeping. */
k_msleep(WORK_ITEM_WAIT);
TC_PRINT(" - Checking results\n");
check_results(NUM_TEST_ITEMS);
reset_results();
}
/**
* @brief Test already triggered work items
*
* @ingroup kernel_workqueue_tests
*
* @see k_work_poll_init(), k_work_poll_submit()
*/
static void test_already_triggered(void)
{
TC_PRINT("Starting triggered test\n");
/* As work items are triggered, they should indicate an event. */
expected_poll_result = 0;
TC_PRINT(" - Initializing triggered test items\n");
test_triggered_init();
TC_PRINT(" - Triggering test items execution\n");
test_triggered_trigger();
TC_PRINT(" - Submitting triggered test items\n");
test_triggered_submit(K_FOREVER);
/* Items should be executed when we will be sleeping. */
k_msleep(WORK_ITEM_WAIT);
TC_PRINT(" - Checking results\n");
check_results(NUM_TEST_ITEMS);
reset_results();
}
static void triggered_resubmit_work_handler(struct k_work *work)
{
struct triggered_test_item *ti =
CONTAINER_OF(work, struct triggered_test_item, work);
results[num_results++] = ti->key;
if (ti->key < NUM_TEST_ITEMS) {
ti->key++;
TC_PRINT(" - Resubmitting triggered work\n");
k_poll_signal_reset(&triggered_tests[0].signal);
zassert_true(k_work_poll_submit(&triggered_tests[0].work,
&triggered_tests[0].event,
1, K_FOREVER) == 0, NULL);
}
}
/**
* @brief Test resubmission of triggered work queue item
*
* @ingroup kernel_workqueue_tests
*
* @see k_work_poll_init(), k_work_poll_submit()
*/
static void test_triggered_resubmit(void)
{
int i;
TC_PRINT("Starting triggered resubmit test\n");
/* As work items are triggered, they should indicate an event. */
expected_poll_result = 0;
triggered_tests[0].key = 1;
k_work_poll_init(&triggered_tests[0].work,
triggered_resubmit_work_handler);
k_poll_signal_init(&triggered_tests[0].signal);
k_poll_event_init(&triggered_tests[0].event,
K_POLL_TYPE_SIGNAL,
K_POLL_MODE_NOTIFY_ONLY,
&triggered_tests[0].signal);
TC_PRINT(" - Submitting triggered work\n");
zassert_true(k_work_poll_submit(&triggered_tests[0].work,
&triggered_tests[0].event,
1, K_FOREVER) == 0, NULL);
for (i = 0; i < NUM_TEST_ITEMS; i++) {
TC_PRINT(" - Triggering test item execution (iteration: %d)\n",
i + 1);
zassert_true(k_poll_signal_raise(&triggered_tests[0].signal,
1) == 0, NULL);
k_msleep(WORK_ITEM_WAIT);
}
TC_PRINT(" - Checking results\n");
check_results(NUM_TEST_ITEMS);
reset_results();
}
/**
* @brief Test triggered work items with K_NO_WAIT timeout
*
* @ingroup kernel_workqueue_tests
*
* @see k_work_poll_init(), k_work_poll_submit()
*/
static void test_triggered_no_wait(void)
{
TC_PRINT("Starting triggered test\n");
/* As work items are triggered, they should indicate an event. */
expected_poll_result = 0;
TC_PRINT(" - Initializing triggered test items\n");
test_triggered_init();
TC_PRINT(" - Triggering test items execution\n");
test_triggered_trigger();
TC_PRINT(" - Submitting triggered test items\n");
test_triggered_submit(K_NO_WAIT);
/* Items should be executed when we will be sleeping. */
k_msleep(WORK_ITEM_WAIT);
TC_PRINT(" - Checking results\n");
check_results(NUM_TEST_ITEMS);
reset_results();
}
/**
* @brief Test expired triggered work items with K_NO_WAIT timeout
*
* @ingroup kernel_workqueue_tests
*
* @see k_work_poll_init(), k_work_poll_submit()
*/
static void test_triggered_no_wait_expired(void)
{
TC_PRINT("Starting triggered test\n");
/* As work items are not triggered, they should be marked as expired. */
expected_poll_result = -EAGAIN;
TC_PRINT(" - Initializing triggered test items\n");
test_triggered_init();
TC_PRINT(" - Submitting triggered test items\n");
test_triggered_submit(K_NO_WAIT);
/* Items should be executed when we will be sleeping. */
k_msleep(WORK_ITEM_WAIT);
TC_PRINT(" - Checking results\n");
check_results(NUM_TEST_ITEMS);
reset_results();
}
/**
* @brief Test triggered work items with arbitrary timeout
*
* @ingroup kernel_workqueue_tests
*
* @see k_work_poll_init(), k_work_poll_submit()
*/
static void test_triggered_wait(void)
{
TC_PRINT("Starting triggered test\n");
/* As work items are triggered, they should indicate an event. */
expected_poll_result = 0;
TC_PRINT(" - Initializing triggered test items\n");
test_triggered_init();
TC_PRINT(" - Triggering test items execution\n");
test_triggered_trigger();
TC_PRINT(" - Submitting triggered test items\n");
test_triggered_submit(K_MSEC(2 * SUBMIT_WAIT));
/* Items should be executed when we will be sleeping. */
k_msleep(SUBMIT_WAIT);
TC_PRINT(" - Checking results\n");
check_results(NUM_TEST_ITEMS);
reset_results();
}
/**
* @brief Test expired triggered work items with arbitrary timeout
*
* @ingroup kernel_workqueue_tests
*
* @see k_work_poll_init(), k_work_poll_submit()
*/
static void test_triggered_wait_expired(void)
{
TC_PRINT("Starting triggered test\n");
/* As work items are not triggered, they should time out. */
expected_poll_result = -EAGAIN;
TC_PRINT(" - Initializing triggered test items\n");
test_triggered_init();
TC_PRINT(" - Submitting triggered test items\n");
test_triggered_submit(K_MSEC(2 * SUBMIT_WAIT));
/* Items should not be executed when we will be sleeping here. */
k_msleep(SUBMIT_WAIT);
TC_PRINT(" - Checking results (before timeout)\n");
check_results(0);
/* Items should be executed when we will be sleeping here. */
k_msleep(SUBMIT_WAIT);
TC_PRINT(" - Checking results (after timeout)\n");
check_results(NUM_TEST_ITEMS);
reset_results();
}
/*test case main entry*/
void test_main(void)
{
k_thread_priority_set(k_current_get(), 0);
ztest_test_suite(workqueue,
ztest_1cpu_unit_test(test_sequence),
ztest_1cpu_unit_test(test_resubmit),
ztest_1cpu_unit_test(test_delayed),
ztest_1cpu_unit_test(test_delayed_resubmit),
ztest_1cpu_unit_test(test_delayed_resubmit_thread),
ztest_1cpu_unit_test(test_delayed_cancel),
ztest_1cpu_unit_test(test_triggered),
ztest_1cpu_unit_test(test_already_triggered),
ztest_1cpu_unit_test(test_triggered_resubmit),
ztest_1cpu_unit_test(test_triggered_no_wait),
ztest_1cpu_unit_test(test_triggered_no_wait_expired),
ztest_1cpu_unit_test(test_triggered_wait),
ztest_1cpu_unit_test(test_triggered_wait_expired)
);
ztest_run_test_suite(workqueue);
}
| 1.648438 | 2 |
apps/Tasks/src/version.h | mbits-os/JiraDesktop | 0 | 52 | #pragma once
#include "program_version.h"
#define PROGRAM_NAME "Tasks"
#define PROGRAM_COPYRIGHT_HOLDER "midnightBITS"
#define VERSION_STRINGIFY(n) VERSION_STRINGIFY_HELPER(n)
#define VERSION_STRINGIFY_HELPER(n) #n
#define PROGRAM_VERSION_STRING \
VERSION_STRINGIFY(PROGRAM_VERSION_MAJOR) "." \
VERSION_STRINGIFY(PROGRAM_VERSION_MINOR) "." \
VERSION_STRINGIFY(PROGRAM_VERSION_PATCH)
#define PROGRAM_VERSION_FULL \
VERSION_STRINGIFY(PROGRAM_VERSION_MAJOR) "." \
VERSION_STRINGIFY(PROGRAM_VERSION_MINOR) "." \
VERSION_STRINGIFY(PROGRAM_VERSION_PATCH) \
PROGRAM_VERSION_STABILITY "+" \
VERSION_STRINGIFY(PROGRAM_VERSION_BUILD)
#define PROGRAM_VERSION_STRING_SHORT \
VERSION_STRINGIFY(PROGRAM_VERSION_MAJOR) "." \
VERSION_STRINGIFY(PROGRAM_VERSION_MINOR)
#define PROGRAM_VERSION_RC PROGRAM_VERSION_MAJOR ##, \
##PROGRAM_VERSION_MINOR ##, \
##PROGRAM_VERSION_PATCH
| 0.898438 | 1 |
freebsd4/sys/dev/mly/mly_pci.c | shisa/kame-shisa | 1 | 60 | /*-
* Copyright (c) 2000, 2001 <NAME>
* Copyright (c) 2000 BSDi
* 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/sys/dev/mly/mly_pci.c,v 1.1.2.2 2001/03/05 20:17:24 msmith Exp $
*/
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/malloc.h>
#include <sys/kernel.h>
#include <sys/bus.h>
#include <sys/conf.h>
#include <sys/devicestat.h>
#include <sys/disk.h>
#include <machine/bus_memio.h>
#include <machine/bus.h>
#include <machine/resource.h>
#include <sys/rman.h>
#include <pci/pcireg.h>
#include <pci/pcivar.h>
#include <dev/mly/mlyreg.h>
#include <dev/mly/mlyio.h>
#include <dev/mly/mlyvar.h>
static int mly_pci_probe(device_t dev);
static int mly_pci_attach(device_t dev);
static int mly_pci_detach(device_t dev);
static int mly_pci_shutdown(device_t dev);
static int mly_pci_suspend(device_t dev);
static int mly_pci_resume(device_t dev);
static void mly_pci_intr(void *arg);
static int mly_sg_map(struct mly_softc *sc);
static void mly_sg_map_helper(void *arg, bus_dma_segment_t *segs, int nseg, int error);
static int mly_mmbox_map(struct mly_softc *sc);
static void mly_mmbox_map_helper(void *arg, bus_dma_segment_t *segs, int nseg, int error);
static device_method_t mly_methods[] = {
/* Device interface */
DEVMETHOD(device_probe, mly_pci_probe),
DEVMETHOD(device_attach, mly_pci_attach),
DEVMETHOD(device_detach, mly_pci_detach),
DEVMETHOD(device_shutdown, mly_pci_shutdown),
DEVMETHOD(device_suspend, mly_pci_suspend),
DEVMETHOD(device_resume, mly_pci_resume),
{ 0, 0 }
};
static driver_t mly_pci_driver = {
"mly",
mly_methods,
sizeof(struct mly_softc)
};
static devclass_t mly_devclass;
DRIVER_MODULE(mly, pci, mly_pci_driver, mly_devclass, 0, 0);
struct mly_ident
{
u_int16_t vendor;
u_int16_t device;
u_int16_t subvendor;
u_int16_t subdevice;
int hwif;
char *desc;
} mly_identifiers[] = {
{0x1069, 0xba56, 0x1069, 0x0040, MLY_HWIF_STRONGARM, "Mylex eXtremeRAID 2000"},
{0x1069, 0xba56, 0x1069, 0x0030, MLY_HWIF_STRONGARM, "Mylex eXtremeRAID 3000"},
{0x1069, 0x0050, 0x1069, 0x0050, MLY_HWIF_I960RX, "Mylex AcceleRAID 352"},
{0x1069, 0x0050, 0x1069, 0x0052, MLY_HWIF_I960RX, "Mylex AcceleRAID 170"},
{0x1069, 0x0050, 0x1069, 0x0054, MLY_HWIF_I960RX, "Mylex AcceleRAID 160"},
{0, 0, 0, 0, 0, 0}
};
/********************************************************************************
********************************************************************************
Bus Interface
********************************************************************************
********************************************************************************/
static int
mly_pci_probe(device_t dev)
{
struct mly_ident *m;
debug_called(1);
for (m = mly_identifiers; m->vendor != 0; m++) {
if ((m->vendor == pci_get_vendor(dev)) &&
(m->device == pci_get_device(dev)) &&
((m->subvendor == 0) || ((m->subvendor == pci_get_subvendor(dev)) &&
(m->subdevice == pci_get_subdevice(dev))))) {
device_set_desc(dev, m->desc);
return(-10); /* allow room to be overridden */
}
}
return(ENXIO);
}
static int
mly_pci_attach(device_t dev)
{
struct mly_softc *sc;
int i, error;
u_int32_t command;
debug_called(1);
/*
* Initialise softc.
*/
sc = device_get_softc(dev);
bzero(sc, sizeof(*sc));
sc->mly_dev = dev;
#ifdef MLY_DEBUG
if (device_get_unit(sc->mly_dev) == 0)
mly_softc0 = sc;
#endif
/* assume failure is 'not configured' */
error = ENXIO;
/*
* Verify that the adapter is correctly set up in PCI space.
*/
command = pci_read_config(sc->mly_dev, PCIR_COMMAND, 2);
command |= PCIM_CMD_BUSMASTEREN;
pci_write_config(dev, PCIR_COMMAND, command, 2);
command = pci_read_config(sc->mly_dev, PCIR_COMMAND, 2);
if (!(command & PCIM_CMD_BUSMASTEREN)) {
mly_printf(sc, "can't enable busmaster feature\n");
goto fail;
}
if ((command & PCIM_CMD_MEMEN) == 0) {
mly_printf(sc, "memory window not available\n");
goto fail;
}
/*
* Allocate the PCI register window.
*/
sc->mly_regs_rid = PCIR_MAPS; /* first base address register */
if ((sc->mly_regs_resource = bus_alloc_resource(sc->mly_dev, SYS_RES_MEMORY, &sc->mly_regs_rid,
0, ~0, 1, RF_ACTIVE)) == NULL) {
mly_printf(sc, "can't allocate register window\n");
goto fail;
}
sc->mly_btag = rman_get_bustag(sc->mly_regs_resource);
sc->mly_bhandle = rman_get_bushandle(sc->mly_regs_resource);
/*
* Allocate and connect our interrupt.
*/
sc->mly_irq_rid = 0;
if ((sc->mly_irq = bus_alloc_resource(sc->mly_dev, SYS_RES_IRQ, &sc->mly_irq_rid,
0, ~0, 1, RF_SHAREABLE | RF_ACTIVE)) == NULL) {
mly_printf(sc, "can't allocate interrupt\n");
goto fail;
}
if (bus_setup_intr(sc->mly_dev, sc->mly_irq, INTR_TYPE_CAM, mly_pci_intr, sc, &sc->mly_intr)) {
mly_printf(sc, "can't set up interrupt\n");
goto fail;
}
/* assume failure is 'out of memory' */
error = ENOMEM;
/*
* Allocate the parent bus DMA tag appropriate for our PCI interface.
*
* Note that all of these controllers are 64-bit capable.
*/
if (bus_dma_tag_create(NULL, /* parent */
1, 0, /* alignment, boundary */
BUS_SPACE_MAXADDR_32BIT, /* lowaddr */
BUS_SPACE_MAXADDR, /* highaddr */
NULL, NULL, /* filter, filterarg */
MAXBSIZE, MLY_MAXSGENTRIES, /* maxsize, nsegments */
BUS_SPACE_MAXSIZE_32BIT, /* maxsegsize */
BUS_DMA_ALLOCNOW, /* flags */
&sc->mly_parent_dmat)) {
mly_printf(sc, "can't allocate parent DMA tag\n");
goto fail;
}
/*
* Create DMA tag for mapping buffers into controller-addressable space.
*/
if (bus_dma_tag_create(sc->mly_parent_dmat, /* parent */
1, 0, /* alignment, boundary */
BUS_SPACE_MAXADDR, /* lowaddr */
BUS_SPACE_MAXADDR, /* highaddr */
NULL, NULL, /* filter, filterarg */
MAXBSIZE, MLY_MAXSGENTRIES, /* maxsize, nsegments */
BUS_SPACE_MAXSIZE_32BIT, /* maxsegsize */
0, /* flags */
&sc->mly_buffer_dmat)) {
mly_printf(sc, "can't allocate buffer DMA tag\n");
goto fail;
}
/*
* Initialise the DMA tag for command packets.
*/
if (bus_dma_tag_create(sc->mly_parent_dmat, /* parent */
1, 0, /* alignment, boundary */
BUS_SPACE_MAXADDR, /* lowaddr */
BUS_SPACE_MAXADDR, /* highaddr */
NULL, NULL, /* filter, filterarg */
sizeof(union mly_command_packet) * MLY_MAXCOMMANDS, 1, /* maxsize, nsegments */
BUS_SPACE_MAXSIZE_32BIT, /* maxsegsize */
0, /* flags */
&sc->mly_packet_dmat)) {
mly_printf(sc, "can't allocate command packet DMA tag\n");
goto fail;
}
/*
* Detect the hardware interface version
*/
for (i = 0; mly_identifiers[i].vendor != 0; i++) {
if ((mly_identifiers[i].vendor == pci_get_vendor(dev)) &&
(mly_identifiers[i].device == pci_get_device(dev))) {
sc->mly_hwif = mly_identifiers[i].hwif;
switch(sc->mly_hwif) {
case MLY_HWIF_I960RX:
debug(2, "set hardware up for i960RX");
sc->mly_doorbell_true = 0x00;
sc->mly_command_mailbox = MLY_I960RX_COMMAND_MAILBOX;
sc->mly_status_mailbox = MLY_I960RX_STATUS_MAILBOX;
sc->mly_idbr = MLY_I960RX_IDBR;
sc->mly_odbr = MLY_I960RX_ODBR;
sc->mly_error_status = MLY_I960RX_ERROR_STATUS;
sc->mly_interrupt_status = MLY_I960RX_INTERRUPT_STATUS;
sc->mly_interrupt_mask = MLY_I960RX_INTERRUPT_MASK;
break;
case MLY_HWIF_STRONGARM:
debug(2, "set hardware up for StrongARM");
sc->mly_doorbell_true = 0xff; /* doorbell 'true' is 0 */
sc->mly_command_mailbox = MLY_STRONGARM_COMMAND_MAILBOX;
sc->mly_status_mailbox = MLY_STRONGARM_STATUS_MAILBOX;
sc->mly_idbr = MLY_STRONGARM_IDBR;
sc->mly_odbr = MLY_STRONGARM_ODBR;
sc->mly_error_status = MLY_STRONGARM_ERROR_STATUS;
sc->mly_interrupt_status = MLY_STRONGARM_INTERRUPT_STATUS;
sc->mly_interrupt_mask = MLY_STRONGARM_INTERRUPT_MASK;
break;
}
break;
}
}
/*
* Create the scatter/gather mappings.
*/
if ((error = mly_sg_map(sc)))
goto fail;
/*
* Allocate and map the memory mailbox
*/
if ((error = mly_mmbox_map(sc)))
goto fail;
/*
* Do bus-independent initialisation.
*/
if ((error = mly_attach(sc)))
goto fail;
return(0);
fail:
mly_free(sc);
return(error);
}
/********************************************************************************
* Disconnect from the controller completely, in preparation for unload.
*/
static int
mly_pci_detach(device_t dev)
{
struct mly_softc *sc = device_get_softc(dev);
int error;
debug_called(1);
if (sc->mly_state & MLY_STATE_OPEN)
return(EBUSY);
if ((error = mly_pci_shutdown(dev)))
return(error);
mly_free(sc);
return(0);
}
/********************************************************************************
* Bring the controller down to a dormant state and detach all child devices.
*
* This function is called before detach or system shutdown.
*
* Note that we can assume that the camq on the controller is empty, as we won't
* allow shutdown if any device is open.
*/
static int
mly_pci_shutdown(device_t dev)
{
struct mly_softc *sc = device_get_softc(dev);
debug_called(1);
mly_detach(sc);
return(0);
}
/********************************************************************************
* Bring the controller to a quiescent state, ready for system suspend.
*
* We can't assume that the controller is not active at this point, so we need
* to mask interrupts.
*/
static int
mly_pci_suspend(device_t dev)
{
struct mly_softc *sc = device_get_softc(dev);
int s;
debug_called(1);
s = splcam();
mly_detach(sc);
splx(s);
return(0);
}
/********************************************************************************
* Bring the controller back to a state ready for operation.
*/
static int
mly_pci_resume(device_t dev)
{
struct mly_softc *sc = device_get_softc(dev);
debug_called(1);
sc->mly_state &= ~MLY_STATE_SUSPEND;
MLY_UNMASK_INTERRUPTS(sc);
return(0);
}
/*******************************************************************************
* Take an interrupt, or be poked by other code to look for interrupt-worthy
* status.
*/
static void
mly_pci_intr(void *arg)
{
struct mly_softc *sc = (struct mly_softc *)arg;
debug_called(3);
/* collect finished commands, queue anything waiting */
mly_done(sc);
};
/********************************************************************************
********************************************************************************
Bus-dependant Resource Management
********************************************************************************
********************************************************************************/
/********************************************************************************
* Allocate memory for the scatter/gather tables
*/
static int
mly_sg_map(struct mly_softc *sc)
{
size_t segsize;
debug_called(1);
/*
* Create a single tag describing a region large enough to hold all of
* the s/g lists we will need.
*/
segsize = sizeof(struct mly_sg_entry) * MLY_MAXCOMMANDS * MLY_MAXSGENTRIES;
if (bus_dma_tag_create(sc->mly_parent_dmat, /* parent */
1, 0, /* alignment, boundary */
BUS_SPACE_MAXADDR, /* lowaddr */
BUS_SPACE_MAXADDR, /* highaddr */
NULL, NULL, /* filter, filterarg */
segsize, 1, /* maxsize, nsegments */
BUS_SPACE_MAXSIZE_32BIT, /* maxsegsize */
0, /* flags */
&sc->mly_sg_dmat)) {
mly_printf(sc, "can't allocate scatter/gather DMA tag\n");
return(ENOMEM);
}
/*
* Allocate enough s/g maps for all commands and permanently map them into
* controller-visible space.
*
* XXX this assumes we can get enough space for all the s/g maps in one
* contiguous slab.
*/
if (bus_dmamem_alloc(sc->mly_sg_dmat, (void **)&sc->mly_sg_table, BUS_DMA_NOWAIT, &sc->mly_sg_dmamap)) {
mly_printf(sc, "can't allocate s/g table\n");
return(ENOMEM);
}
bus_dmamap_load(sc->mly_sg_dmat, sc->mly_sg_dmamap, sc->mly_sg_table, segsize, mly_sg_map_helper, sc, 0);
return(0);
}
/********************************************************************************
* Save the physical address of the base of the s/g table.
*/
static void
mly_sg_map_helper(void *arg, bus_dma_segment_t *segs, int nseg, int error)
{
struct mly_softc *sc = (struct mly_softc *)arg;
debug_called(2);
/* save base of s/g table's address in bus space */
sc->mly_sg_busaddr = segs->ds_addr;
}
/********************************************************************************
* Allocate memory for the memory-mailbox interface
*/
static int
mly_mmbox_map(struct mly_softc *sc)
{
/*
* Create a DMA tag for a single contiguous region large enough for the
* memory mailbox structure.
*/
if (bus_dma_tag_create(sc->mly_parent_dmat, /* parent */
1, 0, /* alignment, boundary */
BUS_SPACE_MAXADDR, /* lowaddr */
BUS_SPACE_MAXADDR, /* highaddr */
NULL, NULL, /* filter, filterarg */
sizeof(struct mly_mmbox), 1, /* maxsize, nsegments */
BUS_SPACE_MAXSIZE_32BIT, /* maxsegsize */
0, /* flags */
&sc->mly_mmbox_dmat)) {
mly_printf(sc, "can't allocate memory mailbox DMA tag\n");
return(ENOMEM);
}
/*
* Allocate the buffer
*/
if (bus_dmamem_alloc(sc->mly_mmbox_dmat, (void **)&sc->mly_mmbox, BUS_DMA_NOWAIT, &sc->mly_mmbox_dmamap)) {
mly_printf(sc, "can't allocate memory mailbox\n");
return(ENOMEM);
}
bus_dmamap_load(sc->mly_mmbox_dmat, sc->mly_mmbox_dmamap, sc->mly_mmbox, sizeof(struct mly_mmbox),
mly_mmbox_map_helper, sc, 0);
bzero(sc->mly_mmbox, sizeof(*sc->mly_mmbox));
return(0);
}
/********************************************************************************
* Save the physical address of the memory mailbox
*/
static void
mly_mmbox_map_helper(void *arg, bus_dma_segment_t *segs, int nseg, int error)
{
struct mly_softc *sc = (struct mly_softc *)arg;
debug_called(2);
sc->mly_mmbox_busaddr = segs->ds_addr;
}
/********************************************************************************
* Free all of the resources associated with (sc)
*
* Should not be called if the controller is active.
*/
void
mly_free(struct mly_softc *sc)
{
struct mly_command *mc;
debug_called(1);
/* detach from CAM */
mly_cam_detach(sc);
/* throw away command buffer DMA maps */
while (mly_alloc_command(sc, &mc) == 0)
bus_dmamap_destroy(sc->mly_buffer_dmat, mc->mc_datamap);
/* release the packet storage */
if (sc->mly_packet != NULL) {
bus_dmamap_unload(sc->mly_packet_dmat, sc->mly_packetmap);
bus_dmamem_free(sc->mly_packet_dmat, sc->mly_packet, sc->mly_packetmap);
}
/* throw away the controllerinfo structure */
if (sc->mly_controllerinfo != NULL)
free(sc->mly_controllerinfo, M_DEVBUF);
/* throw away the controllerparam structure */
if (sc->mly_controllerparam != NULL)
free(sc->mly_controllerparam, M_DEVBUF);
/* destroy data-transfer DMA tag */
if (sc->mly_buffer_dmat)
bus_dma_tag_destroy(sc->mly_buffer_dmat);
/* free and destroy DMA memory and tag for s/g lists */
if (sc->mly_sg_table) {
bus_dmamap_unload(sc->mly_sg_dmat, sc->mly_sg_dmamap);
bus_dmamem_free(sc->mly_sg_dmat, sc->mly_sg_table, sc->mly_sg_dmamap);
}
if (sc->mly_sg_dmat)
bus_dma_tag_destroy(sc->mly_sg_dmat);
/* free and destroy DMA memory and tag for memory mailbox */
if (sc->mly_mmbox) {
bus_dmamap_unload(sc->mly_mmbox_dmat, sc->mly_mmbox_dmamap);
bus_dmamem_free(sc->mly_mmbox_dmat, sc->mly_mmbox, sc->mly_mmbox_dmamap);
}
if (sc->mly_mmbox_dmat)
bus_dma_tag_destroy(sc->mly_mmbox_dmat);
/* disconnect the interrupt handler */
if (sc->mly_intr)
bus_teardown_intr(sc->mly_dev, sc->mly_irq, sc->mly_intr);
if (sc->mly_irq != NULL)
bus_release_resource(sc->mly_dev, SYS_RES_IRQ, sc->mly_irq_rid, sc->mly_irq);
/* destroy the parent DMA tag */
if (sc->mly_parent_dmat)
bus_dma_tag_destroy(sc->mly_parent_dmat);
/* release the register window mapping */
if (sc->mly_regs_resource != NULL)
bus_release_resource(sc->mly_dev, SYS_RES_MEMORY, sc->mly_regs_rid, sc->mly_regs_resource);
}
| 1.21875 | 1 |
trunk/libs/angsys/include/ang/base/str_view.h | ChuyX3/angsys | 0 | 68 | /*********************************************************************************************************************/
/* File Name: ang/base/text.h */
/* Author: Ing. <NAME> <<EMAIL>>, July 2016. */
/* */
/* Copyright (C) angsys, <NAME> */
/* You may opt to use, copy, modify, merge, publish and/or distribute copies of the Software, and permit persons */
/* to whom the Software is furnished to do so. */
/* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. */
/* */
/*********************************************************************************************************************/
#ifndef __ANG_BASE_H__
#error ang/base/base.h is not included
#elif !defined __ANG_BASE_STR_VIEW_H__
#define __ANG_BASE_TEXT_H__
#define MY_LINKAGE LINK
#define MY_CHAR_TYPE ang::text::char_type_by_encoding<MY_ENCODING>::char_type
#define MY_ENCODING ang::text::encoding::ascii
#include <ang/base/inline/str_view.hpp>
#undef MY_ENCODING
#define MY_ENCODING ang::text::encoding::unicode
#include <ang/base/inline/str_view.hpp>
#undef MY_ENCODING
#define MY_ENCODING ang::text::encoding::utf8
#include <ang/base/inline/str_view.hpp>
#undef MY_ENCODING
#define MY_ENCODING ang::text::encoding::utf16
#include <ang/base/inline/str_view.hpp>
#undef MY_ENCODING
#define MY_ENCODING ang::text::encoding::utf16_se
#include <ang/base/inline/str_view.hpp>
#undef MY_ENCODING
#define MY_ENCODING ang::text::encoding::utf16_le
#include <ang/base/inline/str_view.hpp>
#undef MY_ENCODING
#define MY_ENCODING ang::text::encoding::utf16_be
#include <ang/base/inline/str_view.hpp>
#undef MY_ENCODING
#define MY_ENCODING ang::text::encoding::utf32
#include <ang/base/inline/str_view.hpp>
#undef MY_ENCODING
#define MY_ENCODING ang::text::encoding::utf32_se
#include <ang/base/inline/str_view.hpp>
#undef MY_ENCODING
#define MY_ENCODING ang::text::encoding::utf32_le
#include <ang/base/inline/str_view.hpp>
#undef MY_ENCODING
#define MY_ENCODING ang::text::encoding::utf32_be
#include <ang/base/inline/str_view.hpp>
#undef MY_ENCODING
#undef MY_LINKAGE
namespace ang
{
namespace text
{
template<> struct LINK str_view<void, text::encoding::auto_detect> {
str_view();
str_view(ang::nullptr_t const&);
str_view(void* v, wsize s, text::encoding e);
str_view(raw_str const& str);
template<typename T, text::encoding E> inline str_view(str_view<T, E> str)
: str_view(str.str(), str.size() * sizeof(typename text::char_type_by_encoding<E>::char_type), E) {
}
bool is_empty()const;
void* ptr()const;
wsize size()const;
wsize count()const;
wsize char_size()const;
text::encoding encoding()const;
template<text::encoding E> inline operator str_view<typename text::char_type_by_encoding<E>::char_type, E>() {
return E == m_encoding ? str_view<typename text::char_type_by_encoding<E>::char_type, E>(
(typename text::char_type_by_encoding<E>::str_type)m_value,
m_size / sizeof(typename text::char_type_by_encoding<E>::char_type))
: str_view<typename text::char_type_by_encoding<E>::char_type, E>();
}
template<text::encoding E> inline operator cstr_view<typename text::char_type_by_encoding<E>::char_type, E>()const {
return E == m_encoding ? cstr_view<typename text::char_type_by_encoding<E>::char_type, E>(
(typename text::char_type_by_encoding<E>::cstr_type)m_value,
m_size / sizeof(typename text::char_type_by_encoding<E>::char_type))
: cstr_view<typename text::char_type_by_encoding<E>::char_type, E>();
}
template<text::encoding E> inline str_view<typename text::char_type_by_encoding<E>::char_type, E> str() {
return E == m_encoding ? str_view<typename text::char_type_by_encoding<E>::char_type, E>(
(typename text::char_type_by_encoding<E>::str_type)m_value,
m_size / sizeof(typename text::char_type_by_encoding<E>::char_type))
: str_view<typename text::char_type_by_encoding<E>::char_type, E>();
}
template<text::encoding E> inline cstr_view<typename text::char_type_by_encoding<E>::char_type, E> cstr()const {
return E == m_encoding ? cstr_view<typename text::char_type_by_encoding<E>::char_type, E>(
(typename text::char_type_by_encoding<E>::cstr_type)m_value,
m_size / sizeof(typename text::char_type_by_encoding<E>::char_type))
: cstr_view<typename text::char_type_by_encoding<E>::char_type, E>();
}
private:
void* m_value;
wsize m_size;
text::encoding m_encoding;
};
template<> struct LINK str_view<const void, text::encoding::auto_detect> {
str_view();
str_view(ang::nullptr_t const&);
str_view(void const* v, wsize s, text::encoding e);
str_view(raw_cstr const& str);
str_view(raw_str const& str);
template<typename T, text::encoding E> inline str_view(str_view<T, E> str)
: str_view(str.cstr(), str.size() * sizeof(typename text::char_type_by_encoding<E>::char_type), E) {
}
template<typename T, text::encoding E> inline str_view(cstr_view<T, E> str)
: str_view(str.cstr(), str.size() * sizeof(typename text::char_type_by_encoding<E>::char_type), E) {
}
template<typename T, wsize N> inline str_view(const T(&str)[N])
: str_view(str, (N - 1) * sizeof(T), text::encoding_by_char_type<T>::value) {
}
bool is_empty()const;
void const* ptr()const;
wsize size()const;
wsize count()const;
wsize char_size()const;
text::encoding encoding()const;
template<text::encoding E> inline operator cstr_view<typename text::char_type_by_encoding<E>::char_type, E>()const {
return E == m_encoding ? cstr_view<typename text::char_type_by_encoding<E>::char_type, E>(
(typename text::char_type_by_encoding<E>::cstr_type)m_value,
m_size / sizeof(typename text::char_type_by_encoding<E>::char_type))
: cstr_view<typename text::char_type_by_encoding<E>::char_type, E>();
}
template<text::encoding E> inline cstr_view<typename text::char_type_by_encoding<E>::char_type, E> cstr()const {
return E == m_encoding ? cstr_view<typename text::char_type_by_encoding<E>::char_type, E>(
(typename text::char_type_by_encoding<E>::cstr_type)m_value,
m_size / sizeof(typename text::char_type_by_encoding<E>::char_type))
: cstr_view<typename text::char_type_by_encoding<E>::char_type, E>();
}
private:
void const* m_value;
wsize m_size;
text::encoding m_encoding;
};
template<typename cstr1_t, typename cstr2_t> struct str_view_compare_helper;
template<typename T1, text::encoding E1, typename T2, text::encoding E2>
struct str_view_compare_helper<str_view<T1, E1>, str_view<T2, E2>>
{
inline static int compare(const str_view<T1, E1>& value1, const str_view<T2, E2>& value2) {
if constexpr(E1 == text::encoding::auto_detect || E2 == text::encoding::auto_detect)
return text::text_encoder<text::encoding::auto_detect>::compare(value1, value2);
else
return text::text_encoder<E1>::compare(value1.cstr(), value2);
}
};
template<typename T1, text::encoding E1, typename T2>
struct str_view_compare_helper<str_view<T1, E1>, const T2*>
{
inline static int compare(const str_view<T1, E1>& value1, const T2* value2) {
if constexpr (E1 == text::encoding::auto_detect)
return text::text_encoder<text::encoding::auto_detect>::compare(value1, str_view<const T2>(value2, 1)); //optimization hack: no real size needed for null termination string
else
return text::text_encoder<E1>::compare(value1.cstr(), value2);
}
};
template<typename T1, typename T2, text::encoding E2>
struct str_view_compare_helper<const T1*, str_view<T2, E2>>
{
inline static int compare(const T1* value1, const str_view<T2, E2>& value2) {
if constexpr (E2 == text::encoding::auto_detect)
return text::text_encoder<text::encoding::auto_detect>::compare(str_view<const T1>(value1, 1), value2); //optimization hack: no real size needed for null termination string
else
return text::text_encoder<text::encoding_by_char_type<T1>::value>::compare(value1, value2);
}
};
template<typename T1, text::encoding E1, typename T2, wsize N2>
struct str_view_compare_helper<str_view<T1, E1>, T2[N2]>
{
inline static int compare(const str_view<T1, E1>& value1, T2(&value2)[N2]) {
if constexpr (E1 == text::encoding::auto_detect)
return text::text_encoder<text::encoding::auto_detect>::compare(value1, str_view<T2>(value2, N2 - 1));
else
return text::text_encoder<E1>::compare(value1.cstr(), (T2*)value2);
}
};
template<typename T1, wsize N1, typename T2, text::encoding E2>
struct str_view_compare_helper<T1[N1], str_view<T2, E2>>
{
inline static int compare(T1(&value1)[N1], const str_view<T2, E2>& value2) {
if constexpr (E2 == text::encoding::auto_detect)
return text::text_encoder<text::encoding::auto_detect>::compare(str_view<T1>(value1, N1 - 1), value2);
else
return text::text_encoder<text::encoding_by_char_type<T1>::value>::compare((T1*)value1, value2);
}
};
template<typename T, text::encoding E>
struct str_view_compare_helper<str_view<T, E>, nullptr_t>
{
static inline int compare(const str_view<T, E>& value, nullptr_t const&) {
if constexpr (E == text::encoding::auto_detect)
return value.ptr() ? 1 : 0;
else
return value.cstr() ? 1 : 0;
}
};
template<typename T, text::encoding E>
struct str_view_compare_helper<nullptr_t, str_view<T, E>>
{
static inline int compare(nullptr_t const&, const str_view<T, E>& value) {
if constexpr (E == text::encoding::auto_detect)
return value.ptr() ? -1 : 0;
else
return value.cstr() ? -1 : 0;
}
};
template<typename T1, text::encoding E1, typename T2, text::encoding E2>
bool operator == (const str_view<T1, E1>& value1, const str_view<T2, E2>& value2) {
return str_view_compare_helper<str_view<T1, E1>, str_view<T2, E2>>::compare(value1, value2) == 0;
}
template<typename T, text::encoding E, typename cstr_t>
bool operator == (const str_view<T, E>& value1, cstr_t value2) {
return str_view_compare_helper<str_view<T, E>, cstr_t>::compare(value1, value2) == 0;
}
template<typename T, text::encoding E, typename cstr_t>
bool operator == (cstr_t value1, const str_view<T, E>& value2) {
return str_view_compare_helper<cstr_t, str_view<T, E>>::compare(value1, value2) == 0;
}
template<typename T1, text::encoding E1, typename T2, text::encoding E2>
bool operator != (const str_view<T1, E1>& value1, const str_view<T2, E2>& value2) {
return str_view_compare_helper<str_view<T1, E1>, str_view<T2, E2>>::compare(value1, value2) != 0;
}
template<typename T, text::encoding E, typename cstr_t>
bool operator != (const str_view<T, E>& value1, cstr_t value2) {
return str_view_compare_helper<str_view<T, E>, cstr_t>::compare(value1, value2) != 0;
}
template<typename T, text::encoding E, typename cstr_t>
bool operator != (cstr_t value1, const str_view<T, E>& value2) {
return str_view_compare_helper<cstr_t, str_view<T, E>>::compare(value1, value2) != 0;
}
template<typename T1, text::encoding E1, typename T2, text::encoding E2>
bool operator >= (const str_view<T1, E1>& value1, const str_view<T2, E2>& value2) {
return str_view_compare_helper<str_view<T1, E1>, str_view<T2, E2>>::compare(value1, value2) >= 0;
}
template<typename T, text::encoding E, typename cstr_t>
bool operator >= (const str_view<T, E>& value1, cstr_t value2) {
return str_view_compare_helper<str_view<T, E>, cstr_t>::compare(value1, value2) >= 0;
}
template<typename T, text::encoding E, typename cstr_t>
bool operator >= (cstr_t value1, const str_view<T, E>& value2) {
return str_view_compare_helper<cstr_t, str_view<T, E>>::compare(value1, value2) >= 0;
}
template<typename T1, text::encoding E1, typename T2, text::encoding E2>
bool operator <= (const str_view<T1, E1>& value1, const str_view<T2, E2>& value2) {
return str_view_compare_helper<str_view<T1, E1>, str_view<T2, E2>>::compare(value1, value2) <= 0;
}
template<typename T, text::encoding E, typename cstr_t>
bool operator <= (const str_view<T, E>& value1, cstr_t value2) {
return str_view_compare_helper<str_view<T, E>, cstr_t>::compare(value1, value2) <= 0;
}
template<typename T, text::encoding E, typename cstr_t>
bool operator <= (cstr_t value1, const str_view<T, E>& value2) {
return str_view_compare_helper<cstr_t, str_view<T, E>>::compare(value1, value2) <= 0;
}
template<typename T1, text::encoding E1, typename T2, text::encoding E2>
bool operator > (const str_view<T1, E1>& value1, const str_view<T2, E2>& value2) {
return str_view_compare_helper<str_view<T1, E1>, str_view<T2, E2>>::compare(value1, value2) > 0;
}
template<typename T, text::encoding E, typename cstr_t>
bool operator > (const str_view<T, E>& value1, cstr_t value2) {
return str_view_compare_helper<str_view<T, E>, cstr_t>::compare(value1, value2) > 0;
}
template<typename T, text::encoding E, typename cstr_t>
bool operator > (cstr_t value1, const str_view<T, E>& value2) {
return str_view_compare_helper<cstr_t, str_view<T, E>>::compare(value1, value2) > 0;
}
template<typename T1, text::encoding E1, typename T2, text::encoding E2>
bool operator < (const str_view<T1, E1>& value1, const str_view<T2, E2>& value2) {
return str_view_compare_helper<str_view<T1, E1>, str_view<T2, E2>>::compare(value1, value2) < 0;
}
template<typename T, text::encoding E, typename cstr_t>
bool operator < (const str_view<T, E>& value1, cstr_t value2) {
return str_view_compare_helper<str_view<T, E>, cstr_t>::compare(value1, value2) < 0;
}
template<typename T, text::encoding E, typename cstr_t>
bool operator < (cstr_t value1, const str_view<T, E>& value2) {
return str_view_compare_helper<cstr_t, str_view<T, E>>::compare(value1, value2) < 0;
}
}
inline str_view<const char> operator "" _sv(const char* str, wsize sz) { return str_view<const char>(str, sz); }
inline str_view<const mchar> operator "" _svm(const char* str, wsize sz) { return str_view<const mchar>((mchar const*)str, sz); }
inline str_view<const wchar_t> operator "" _sv(const wchar_t* str, wsize sz) { return str_view<const wchar_t>(str, sz); }
inline str_view<const char16_t> operator "" _sv(const char16_t* str, wsize sz) { return str_view<const char16_t>(str, sz); }
inline str_view<const char32_t> operator "" _sv(const char32_t* str, wsize sz) { return str_view<const char32_t>(str, sz); }
inline raw_cstr_t operator "" _r(const char* str, wsize sz) { return str_view<const char>(str, sz); }
inline raw_cstr_t operator "" _r(const wchar_t* str, wsize sz) { return str_view<const wchar_t>(str, sz); }
inline raw_cstr_t operator "" _r(const char16_t* str, wsize sz) { return str_view<const char16_t>(str, sz); }
inline raw_cstr_t operator "" _r(const char32_t* str, wsize sz) { return str_view<const char32_t>(str, sz); }
namespace algorithms
{
template<typename T, text::encoding E>
struct hash<str_view<T, E>> {
static ulong64 make(str_view<T, E> const& value) {
ulong64 h = 75025;
windex i = 0, c = value.size();
for (char32_t n = text::to_char32<false, text::is_endian_swapped<E>::value>(value.cstr(), i);
n != 0;
n = text::to_char32<false, text::is_endian_swapped<E>::value>(value.cstr(), i))
{
h = (h << 5) + h + n + 1;
}
return h;
}
ulong64 operator()(str_view<T, E> const& value)const {
return make(value);
}
};
template<>
struct hash<cstr_t> {
static ulong64 make(cstr_t const& value) {
ulong64 h = 75025;
windex i = 0, c = value.size();
for (char32_t n = text::encoder::to_char32(value, i);
n != 0;
n = text::encoder::to_char32(value, i))
{
h = (h << 5) + h + n + 1;
}
return h;
}
ulong64 operator()(cstr_t const& value)const {
return make(value);
}
};
}
template<typename T, T VALUE>
struct enum_to_string
{
static const str_view<const char> value;
};
#define TO_STRING_TEMPLATE(_LINK, _VALUE) namespace ang { template<> struct _LINK enum_to_string<decltype(_VALUE), _VALUE> { static const str_view<const char> value; }; }
#define TO_STRING_TEMPLATE_IMPLEMENT(_ENUM, _VALUE) const ang::str_view<const char> ang::enum_to_string<_ENUM, _ENUM::_VALUE>::value = ANG_UTILS_TO_STRING_OBJ(_VALUE);
}
TO_STRING_TEMPLATE(LINK, ang::text::encoding::binary);
TO_STRING_TEMPLATE(LINK, ang::text::encoding::ascii);
TO_STRING_TEMPLATE(LINK, ang::text::encoding::unicode);
TO_STRING_TEMPLATE(LINK, ang::text::encoding::utf8);
TO_STRING_TEMPLATE(LINK, ang::text::encoding::utf16);
TO_STRING_TEMPLATE(LINK, ang::text::encoding::utf16_se);
TO_STRING_TEMPLATE(LINK, ang::text::encoding::utf16_le);
TO_STRING_TEMPLATE(LINK, ang::text::encoding::utf16_be);
TO_STRING_TEMPLATE(LINK, ang::text::encoding::utf32);
TO_STRING_TEMPLATE(LINK, ang::text::encoding::utf32_se);
TO_STRING_TEMPLATE(LINK, ang::text::encoding::utf32_le);
TO_STRING_TEMPLATE(LINK, ang::text::encoding::utf32_be);
TO_STRING_TEMPLATE(LINK, ang::text::encoding::auto_detect);
#endif//__ANG_BASE_TEXT_H__
| 0.984375 | 1 |
arch/risc-v/src/k210/k210_timerisr.c | robsonsopran/incubator-nuttx | 31 | 76 | /****************************************************************************
* arch/risc-v/src/k210/k210_timerisr.c
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <stdint.h>
#include <time.h>
#include <debug.h>
#include <nuttx/arch.h>
#include <arch/board/board.h>
#include "riscv_arch.h"
#include "k210.h"
#include "k210_clockconfig.h"
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
#define getreg64(a) (*(volatile uint64_t *)(a))
#define putreg64(v,a) (*(volatile uint64_t *)(a) = (v))
#ifdef CONFIG_K210_WITH_QEMU
#define TICK_COUNT (10000000 / TICK_PER_SEC)
#else
#define TICK_COUNT ((k210_get_cpuclk() / 50) / TICK_PER_SEC)
#endif
/****************************************************************************
* Private Data
****************************************************************************/
static bool _b_tick_started = false;
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: k210_reload_mtimecmp
****************************************************************************/
static void k210_reload_mtimecmp(void)
{
irqstate_t flags = spin_lock_irqsave(NULL);
uint64_t current;
uint64_t next;
if (!_b_tick_started)
{
_b_tick_started = true;
current = getreg64(K210_CLINT_MTIME);
}
else
{
current = getreg64(K210_CLINT_MTIMECMP);
}
uint64_t tick = TICK_COUNT;
next = current + tick;
putreg64(next, K210_CLINT_MTIMECMP);
spin_unlock_irqrestore(NULL, flags);
}
/****************************************************************************
* Name: k210_timerisr
****************************************************************************/
static int k210_timerisr(int irq, void *context, FAR void *arg)
{
k210_reload_mtimecmp();
/* Process timer interrupt */
nxsched_process_timer();
return 0;
}
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: up_timer_initialize
*
* Description:
* This function is called during start-up to initialize
* the timer interrupt.
*
****************************************************************************/
void up_timer_initialize(void)
{
#if 1
/* Attach timer interrupt handler */
irq_attach(K210_IRQ_MTIMER, k210_timerisr, NULL);
/* Reload CLINT mtimecmp */
k210_reload_mtimecmp();
/* And enable the timer interrupt */
up_enable_irq(K210_IRQ_MTIMER);
#endif
}
| 1.039063 | 1 |
apps/umve/jobqueue.h | lemony-fresh/mve | 1 | 84 | /*
* Copyright (C) 2015, <NAME>
* 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 JOB_QUEUE_HEADER
#define JOB_QUEUE_HEADER
#include <QBoxLayout>
#include <QDockWidget>
#include <QListWidget>
#include <QPushButton>
#include <QTimer>
#include <vector>
struct JobProgress
{
virtual ~JobProgress (void) {}
virtual char const* get_name (void) = 0;
virtual char const* get_message (void) = 0;
virtual bool is_completed (void) = 0;
virtual bool has_progress (void) = 0;
virtual float get_progress (void) = 0;
virtual void cancel_job (void) = 0;
};
/* ---------------------------------------------------------------- */
struct JobQueueEntry
{
JobProgress* progress;
QListWidgetItem* item;
int finished;
JobQueueEntry (void) : progress(nullptr), item(nullptr), finished(0) {}
};
/* ---------------------------------------------------------------- */
class JobQueue : public QWidget
{
Q_OBJECT
/* Singleton implementation. */
public:
static JobQueue* get (void);
protected slots:
void on_update (void);
void on_item_activated(QListWidgetItem* item);
void add_fake_job (void);
void update_job (JobQueueEntry& job);
protected:
JobQueue (void);
private:
typedef std::vector<JobQueueEntry> JobQueueList;
QListWidget* jobs_list;
QDockWidget* dock;
QTimer* update_timer;
JobQueueList jobs;
public:
/* Note: job object is deleted when queue entry is removed. */
void add_job (JobProgress* job);
/* QT stuff. */
QSize sizeHint (void) const;
void set_dock_widget (QDockWidget* dock);
bool is_empty (void) const;
};
/* -------------------------- Implementation ---------------------- */
inline QSize
JobQueue::sizeHint (void) const
{
return QSize(175, 0);
}
inline void
JobQueue::set_dock_widget (QDockWidget* dock)
{
this->dock = dock;
}
inline bool
JobQueue::is_empty (void) const
{
bool empty = true;
for (std::size_t i = 0; i < this->jobs.size(); ++i)
if (this->jobs[i].finished == 0)
empty = false;
return empty;
}
#endif /* JOB_QUEUE_HEADER */
| 1.742188 | 2 |
src/common.c | testnetopeer/libyang | 0 | 92 | /**
* @file common.c
* @author <NAME> <<EMAIL>>
* @brief common internal definitions for libyang
*
* Copyright (c) 2018 CESNET, z.s.p.o.
*
* This source code is licensed under BSD 3-Clause License (the "License").
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*/
#define _GNU_SOURCE
#include "common.h"
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <inttypes.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include "compat.h"
#include "tree_schema_internal.h"
void *
ly_realloc(void *ptr, size_t size)
{
void *new_mem;
new_mem = realloc(ptr, size);
if (!new_mem) {
free(ptr);
}
return new_mem;
}
char *
ly_strnchr(const char *s, int c, size_t len)
{
for ( ; len && (*s != (char)c); ++s, --len) {}
return len ? (char *)s : NULL;
}
int
ly_strncmp(const char *refstr, const char *str, size_t str_len)
{
int rc = strncmp(refstr, str, str_len);
if (!rc && (refstr[str_len] == '\0')) {
return 0;
} else {
return rc ? rc : 1;
}
}
#define LY_OVERFLOW_ADD(MAX, X, Y) ((X > MAX - Y) ? 1 : 0)
#define LY_OVERFLOW_MUL(MAX, X, Y) ((X > MAX / Y) ? 1 : 0)
LY_ERR
ly_strntou8(const char *nptr, size_t len, uint8_t *ret)
{
uint8_t num = 0, dig, dec_pow;
if (len > 3) {
/* overflow for sure */
return LY_EDENIED;
}
dec_pow = 1;
for ( ; len && isdigit(nptr[len - 1]); --len) {
dig = nptr[len - 1] - 48;
if (LY_OVERFLOW_MUL(UINT8_MAX, dig, dec_pow)) {
return LY_EDENIED;
}
dig *= dec_pow;
if (LY_OVERFLOW_ADD(UINT8_MAX, num, dig)) {
return LY_EDENIED;
}
num += dig;
dec_pow *= 10;
}
if (len) {
return LY_EVALID;
}
*ret = num;
return LY_SUCCESS;
}
LY_ERR
ly_value_prefix_next(const char *str_begin, const char *str_end, uint32_t *len, ly_bool *is_prefix, const char **str_next)
{
const char *stop, *prefix;
size_t bytes_read;
uint32_t c;
ly_bool prefix_found;
LY_ERR ret = LY_SUCCESS;
assert(len && is_prefix && str_next);
#define IS_AT_END(PTR, STR_END) (STR_END ? PTR == STR_END : !(*PTR))
*str_next = NULL;
*is_prefix = 0;
*len = 0;
if (!str_begin || !(*str_begin) || (str_begin == str_end)) {
return ret;
}
stop = str_begin;
prefix = NULL;
prefix_found = 0;
do {
/* look for the beginning of the YANG value */
do {
LY_CHECK_RET(ly_getutf8(&stop, &c, &bytes_read));
} while (!is_xmlqnamestartchar(c) && !IS_AT_END(stop, str_end));
if (IS_AT_END(stop, str_end)) {
break;
}
/* maybe the prefix was found */
prefix = stop - bytes_read;
/* look for the the end of the prefix */
do {
LY_CHECK_RET(ly_getutf8(&stop, &c, &bytes_read));
} while (is_xmlqnamechar(c) && !IS_AT_END(stop, str_end));
prefix_found = c == ':' ? 1 : 0;
/* if it wasn't the prefix, keep looking */
} while (!IS_AT_END(stop, str_end) && !prefix_found);
if ((str_begin == prefix) && prefix_found) {
/* prefix found at the beginning of the input string */
*is_prefix = 1;
*str_next = IS_AT_END(stop, str_end) ? NULL : stop;
*len = (stop - bytes_read) - str_begin;
} else if ((str_begin != prefix) && (prefix_found)) {
/* there is a some string before prefix */
*str_next = prefix;
*len = prefix - str_begin;
} else {
/* no prefix found */
*len = stop - str_begin;
}
#undef IS_AT_END
return ret;
}
LY_ERR
ly_getutf8(const char **input, uint32_t *utf8_char, size_t *bytes_read)
{
uint32_t c, aux;
size_t len;
if (bytes_read) {
(*bytes_read) = 0;
}
c = (*input)[0];
LY_CHECK_RET(!c, LY_EINVAL);
if (!(c & 0x80)) {
/* one byte character */
len = 1;
if ((c < 0x20) && (c != 0x9) && (c != 0xa) && (c != 0xd)) {
return LY_EINVAL;
}
} else if ((c & 0xe0) == 0xc0) {
/* two bytes character */
len = 2;
aux = (*input)[1];
if ((aux & 0xc0) != 0x80) {
return LY_EINVAL;
}
c = ((c & 0x1f) << 6) | (aux & 0x3f);
if (c < 0x80) {
return LY_EINVAL;
}
} else if ((c & 0xf0) == 0xe0) {
/* three bytes character */
len = 3;
c &= 0x0f;
for (uint64_t i = 1; i <= 2; i++) {
aux = (*input)[i];
if ((aux & 0xc0) != 0x80) {
return LY_EINVAL;
}
c = (c << 6) | (aux & 0x3f);
}
if ((c < 0x800) || ((c > 0xd7ff) && (c < 0xe000)) || (c > 0xfffd)) {
return LY_EINVAL;
}
} else if ((c & 0xf8) == 0xf0) {
/* four bytes character */
len = 4;
c &= 0x07;
for (uint64_t i = 1; i <= 3; i++) {
aux = (*input)[i];
if ((aux & 0xc0) != 0x80) {
return LY_EINVAL;
}
c = (c << 6) | (aux & 0x3f);
}
if ((c < 0x1000) || (c > 0x10ffff)) {
return LY_EINVAL;
}
} else {
return LY_EINVAL;
}
(*utf8_char) = c;
(*input) += len;
if (bytes_read) {
(*bytes_read) = len;
}
return LY_SUCCESS;
}
LY_ERR
ly_pututf8(char *dst, uint32_t value, size_t *bytes_written)
{
if (value < 0x80) {
/* one byte character */
if ((value < 0x20) &&
(value != 0x09) &&
(value != 0x0a) &&
(value != 0x0d)) {
return LY_EINVAL;
}
dst[0] = value;
(*bytes_written) = 1;
} else if (value < 0x800) {
/* two bytes character */
dst[0] = 0xc0 | (value >> 6);
dst[1] = 0x80 | (value & 0x3f);
(*bytes_written) = 2;
} else if (value < 0xfffe) {
/* three bytes character */
if (((value & 0xf800) == 0xd800) ||
((value >= 0xfdd0) && (value <= 0xfdef))) {
/* exclude surrogate blocks %xD800-DFFF */
/* exclude noncharacters %xFDD0-FDEF */
return LY_EINVAL;
}
dst[0] = 0xe0 | (value >> 12);
dst[1] = 0x80 | ((value >> 6) & 0x3f);
dst[2] = 0x80 | (value & 0x3f);
(*bytes_written) = 3;
} else if (value < 0x10fffe) {
if ((value & 0xffe) == 0xffe) {
/* exclude noncharacters %xFFFE-FFFF, %x1FFFE-1FFFF, %x2FFFE-2FFFF, %x3FFFE-3FFFF, %x4FFFE-4FFFF,
* %x5FFFE-5FFFF, %x6FFFE-6FFFF, %x7FFFE-7FFFF, %x8FFFE-8FFFF, %x9FFFE-9FFFF, %xAFFFE-AFFFF,
* %xBFFFE-BFFFF, %xCFFFE-CFFFF, %xDFFFE-DFFFF, %xEFFFE-EFFFF, %xFFFFE-FFFFF, %x10FFFE-10FFFF */
return LY_EINVAL;
}
/* four bytes character */
dst[0] = 0xf0 | (value >> 18);
dst[1] = 0x80 | ((value >> 12) & 0x3f);
dst[2] = 0x80 | ((value >> 6) & 0x3f);
dst[3] = 0x80 | (value & 0x3f);
(*bytes_written) = 4;
} else {
return LY_EINVAL;
}
return LY_SUCCESS;
}
/**
* @brief Static table of the UTF8 characters lengths according to their first byte.
*/
static const unsigned char utf8_char_length_table[] = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 1, 1
};
size_t
ly_utf8len(const char *str, size_t bytes)
{
size_t len = 0;
const char *ptr = str;
while (((size_t)(ptr - str) < bytes) && *ptr) {
++len;
ptr += utf8_char_length_table[((unsigned char)(*ptr))];
}
return len;
}
size_t
LY_VCODE_INSTREXP_len(const char *str)
{
size_t len = 0;
if (!str) {
return len;
} else if (!str[0]) {
return 1;
}
for (len = 1; len < LY_VCODE_INSTREXP_MAXLEN && str[len]; ++len) {}
return len;
}
LY_ERR
ly_mmap(struct ly_ctx *ctx, int fd, size_t *length, void **addr)
{
struct stat sb;
long pagesize;
size_t m;
assert(length);
assert(addr);
assert(fd >= 0);
if (fstat(fd, &sb) == -1) {
LOGERR(ctx, LY_ESYS, "Failed to stat the file descriptor (%s) for the mmap().", strerror(errno));
return LY_ESYS;
}
if (!S_ISREG(sb.st_mode)) {
LOGERR(ctx, LY_EINVAL, "File to mmap() is not a regular file.");
return LY_ESYS;
}
if (!sb.st_size) {
*addr = NULL;
return LY_SUCCESS;
}
pagesize = sysconf(_SC_PAGESIZE);
m = sb.st_size % pagesize;
if (m && (pagesize - m >= 1)) {
/* there will be enough space (at least 1 byte) after the file content mapping to provide zeroed NULL-termination byte */
*length = sb.st_size + 1;
*addr = mmap(NULL, *length, PROT_READ, MAP_PRIVATE, fd, 0);
} else {
/* there will not be enough bytes after the file content mapping for the additional bytes and some of them
* would overflow into another page that would not be zerroed and any access into it would generate SIGBUS.
* Therefore we have to do the following hack with double mapping. First, the required number of bytes
* (including the additinal bytes) is required as anonymous and thus they will be really provided (actually more
* because of using whole pages) and also initialized by zeros. Then, the file is mapped to the same address
* where the anonymous mapping starts. */
*length = sb.st_size + pagesize;
*addr = mmap(NULL, *length, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
*addr = mmap(*addr, sb.st_size, PROT_READ, MAP_PRIVATE | MAP_FIXED, fd, 0);
}
if (*addr == MAP_FAILED) {
LOGERR(ctx, LY_ESYS, "mmap() failed (%s).", strerror(errno));
return LY_ESYS;
}
return LY_SUCCESS;
}
LY_ERR
ly_munmap(void *addr, size_t length)
{
if (munmap(addr, length)) {
return LY_ESYS;
}
return LY_SUCCESS;
}
LY_ERR
ly_strcat(char **dest, const char *format, ...)
{
va_list fp;
char *addition = NULL;
size_t len;
va_start(fp, format);
len = vasprintf(&addition, format, fp);
len += (*dest ? strlen(*dest) : 0) + 1;
if (*dest) {
*dest = ly_realloc(*dest, len);
if (!*dest) {
va_end(fp);
return LY_EMEM;
}
*dest = strcat(*dest, addition);
free(addition);
} else {
*dest = addition;
}
va_end(fp);
return LY_SUCCESS;
}
LY_ERR
ly_parse_int(const char *val_str, size_t val_len, int64_t min, int64_t max, int base, int64_t *ret)
{
LY_ERR rc = LY_SUCCESS;
char *ptr, *str;
int64_t i;
LY_CHECK_ARG_RET(NULL, val_str, val_str[0], val_len, LY_EINVAL);
/* duplicate the value */
str = strndup(val_str, val_len);
LY_CHECK_RET(!str, LY_EMEM);
/* parse the value to avoid accessing following bytes */
errno = 0;
i = strtoll(str, &ptr, base);
if (errno || (ptr == str)) {
/* invalid string */
rc = LY_EVALID;
} else if ((i < min) || (i > max)) {
/* invalid number */
rc = LY_EDENIED;
} else if (*ptr) {
while (isspace(*ptr)) {
++ptr;
}
if (*ptr) {
/* invalid characters after some number */
rc = LY_EVALID;
}
}
/* cleanup */
free(str);
if (!rc) {
*ret = i;
}
return rc;
}
LY_ERR
ly_parse_uint(const char *val_str, size_t val_len, uint64_t max, int base, uint64_t *ret)
{
LY_ERR rc = LY_SUCCESS;
char *ptr, *str;
uint64_t u;
LY_CHECK_ARG_RET(NULL, val_str, val_str[0], val_len, LY_EINVAL);
/* duplicate the value to avoid accessing following bytes */
str = strndup(val_str, val_len);
LY_CHECK_RET(!str, LY_EMEM);
/* parse the value */
errno = 0;
u = strtoull(str, &ptr, base);
if (errno || (ptr == str)) {
/* invalid string */
rc = LY_EVALID;
} else if ((u > max) || (u && (str[0] == '-'))) {
/* invalid number */
rc = LY_EDENIED;
} else if (*ptr) {
while (isspace(*ptr)) {
++ptr;
}
if (*ptr) {
/* invalid characters after some number */
rc = LY_EVALID;
}
}
/* cleanup */
free(str);
if (!rc) {
*ret = u;
}
return rc;
}
/**
* @brief Parse an identifier.
*
* ;; An identifier MUST NOT start with (('X'|'x') ('M'|'m') ('L'|'l'))
* identifier = (ALPHA / "_")
* *(ALPHA / DIGIT / "_" / "-" / ".")
*
* @param[in,out] id Identifier to parse. When returned, it points to the first character which is not part of the identifier.
* @return LY_ERR value: LY_SUCCESS or LY_EINVAL in case of invalid starting character.
*/
static LY_ERR
lys_parse_id(const char **id)
{
assert(id && *id);
if (!is_yangidentstartchar(**id)) {
return LY_EINVAL;
}
++(*id);
while (is_yangidentchar(**id)) {
++(*id);
}
return LY_SUCCESS;
}
LY_ERR
ly_parse_nodeid(const char **id, const char **prefix, size_t *prefix_len, const char **name, size_t *name_len)
{
assert(id && *id);
assert(prefix && prefix_len);
assert(name && name_len);
*prefix = *id;
*prefix_len = 0;
*name = NULL;
*name_len = 0;
LY_CHECK_RET(lys_parse_id(id));
if (**id == ':') {
/* there is prefix */
*prefix_len = *id - *prefix;
++(*id);
*name = *id;
LY_CHECK_RET(lys_parse_id(id));
*name_len = *id - *name;
} else {
/* there is no prefix, so what we have as prefix now is actually the name */
*name = *prefix;
*name_len = *id - *name;
*prefix = NULL;
}
return LY_SUCCESS;
}
LY_ERR
ly_parse_instance_predicate(const char **pred, size_t limit, LYD_FORMAT format,
const char **prefix, size_t *prefix_len, const char **id, size_t *id_len, const char **value, size_t *value_len,
const char **errmsg)
{
LY_ERR ret = LY_EVALID;
const char *in = *pred;
size_t offset = 1;
uint8_t expr = 0; /* 0 - position predicate; 1 - leaf-list-predicate; 2 - key-predicate */
char quot;
assert(in[0] == '[');
*prefix = *id = *value = NULL;
*prefix_len = *id_len = *value_len = 0;
/* leading *WSP */
for ( ; isspace(in[offset]); offset++) {}
if (isdigit(in[offset])) {
/* pos: "[" *WSP positive-integer-value *WSP "]" */
if (in[offset] == '0') {
/* zero */
*errmsg = "The position predicate cannot be zero.";
goto error;
}
/* positive-integer-value */
*value = &in[offset++];
for ( ; isdigit(in[offset]); offset++) {}
*value_len = &in[offset] - *value;
} else if (in[offset] == '.') {
/* leaf-list-predicate: "[" *WSP "." *WSP "=" *WSP quoted-string *WSP "]" */
*id = &in[offset];
*id_len = 1;
offset++;
expr = 1;
} else if (in[offset] == '-') {
/* typically negative value */
*errmsg = "Invalid instance predicate format (negative position or invalid node-identifier).";
goto error;
} else {
/* key-predicate: "[" *WSP node-identifier *WSP "=" *WSP quoted-string *WSP "]" */
in = &in[offset];
if (ly_parse_nodeid(&in, prefix, prefix_len, id, id_len)) {
*errmsg = "Invalid node-identifier.";
goto error;
}
if ((format == LYD_XML) && !(*prefix)) {
/* all node names MUST be qualified with explicit namespace prefix */
*errmsg = "Missing prefix of a node name.";
goto error;
}
offset = in - *pred;
in = *pred;
expr = 2;
}
if (expr) {
/* *WSP "=" *WSP quoted-string *WSP "]" */
for ( ; isspace(in[offset]); offset++) {}
if (in[offset] != '=') {
if (expr == 1) {
*errmsg = "Unexpected character instead of \'=\' in leaf-list-predicate.";
} else { /* 2 */
*errmsg = "Unexpected character instead of \'=\' in key-predicate.";
}
goto error;
}
offset++;
for ( ; isspace(in[offset]); offset++) {}
/* quoted-string */
quot = in[offset++];
if ((quot != '\'') && (quot != '\"')) {
*errmsg = "String value is not quoted.";
goto error;
}
*value = &in[offset];
for ( ; offset < limit && (in[offset] != quot || (offset && in[offset - 1] == '\\')); offset++) {}
if (in[offset] == quot) {
*value_len = &in[offset] - *value;
offset++;
} else {
*errmsg = "Value is not terminated quoted-string.";
goto error;
}
}
/* *WSP "]" */
for ( ; isspace(in[offset]); offset++) {}
if (in[offset] != ']') {
if (expr == 0) {
*errmsg = "Predicate (pos) is not terminated by \']\' character.";
} else if (expr == 1) {
*errmsg = "Predicate (leaf-list-predicate) is not terminated by \']\' character.";
} else { /* 2 */
*errmsg = "Predicate (key-predicate) is not terminated by \']\' character.";
}
goto error;
}
offset++;
if (offset <= limit) {
*pred = &in[offset];
return LY_SUCCESS;
}
/* we read after the limit */
*errmsg = "Predicate is incomplete.";
*prefix = *id = *value = NULL;
*prefix_len = *id_len = *value_len = 0;
offset = limit;
ret = LY_EINVAL;
error:
*pred = &in[offset];
return ret;
}
| 1.507813 | 2 |
src/test/kc/switch-2.c | jbrandwood/kickc | 2 | 100 | // Tests simple switch()-statement - not inside a loop
void main() {
char* SCREEN = (char*)0x0400;
char b=0;
char v64 = 0;
switch(v64){
case 0: b = 1;
}
SCREEN[0] = b;
} | 1.257813 | 1 |
src/phi/region.h | learning/phi | 1 | 108 | /*
* phi/region.h
*
* Represent a text region in a text view
*/
#ifndef __PHI_REGION__
#define __PHI_REGION__
#include <stdlib.h>
typedef struct phi_region_t {
unsigned int start_pos; // The start position of region
unsigned int end_pos; // The end position of region
struct phi_region_t *next; // So, it's a linked list
} PhiRegion;
/*
* Function: phi_region_new
* ----------------------
* Create a region for view
*
* start_pos: the start position of text in the view
* end_pos: the end position of text in the view
*/
PhiRegion *phi_region_new(unsigned int start_pos, unsigned int end_pos);
/*
* Function: phi_region_destroy
* ----------------------
* Destroy a phi region
*
* region: the region of the view
*/
void phi_region_destroy(PhiRegion *region);
#endif
| 1.664063 | 2 |
C/chelloworld.c | kennethsequeira/Hello-world | 1,428 | 116 | /*
Created by <NAME>
github.com/singh96aman
*/
#include <stdio.h>
int main(){
printf("\n Hello World in C Language !");
} | 1.226563 | 1 |
be/src/exec/vectorized/aggregate/aggregate_blocking_node.h | lokax/starrocks | 1 | 124 | // This file is licensed under the Elastic License 2.0. Copyright 2021 StarRocks Limited.
#pragma once
#include "exec/exec_node.h"
#include "exec/pipeline/operator.h"
#include "exec/vectorized/aggregate/aggregate_base_node.h"
// Aggregate means this node handle query with aggregate functions.
// Blocking means this node will consume all input and build hash map in open phase.
namespace starrocks::vectorized {
class AggregateBlockingNode final : public AggregateBaseNode {
public:
AggregateBlockingNode(ObjectPool* pool, const TPlanNode& tnode, const DescriptorTbl& descs)
: AggregateBaseNode(pool, tnode, descs) {
_aggr_phase = AggrPhase2;
};
Status open(RuntimeState* state) override;
Status get_next(RuntimeState* state, ChunkPtr* chunk, bool* eos) override;
std::vector<std::shared_ptr<pipeline::OperatorFactory>> decompose_to_pipeline(
pipeline::PipelineBuilderContext* context) override;
};
} // namespace starrocks::vectorized
| 1.4375 | 1 |
Code/GraphMol/MolStandardize/TransformCatalog/TransformCatalogUtils.h | Andy-Wilkinson/rdkit | 4 | 132 | //
// Copyright (C) 2018 <NAME>
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#include <RDGeneral/export.h>
#ifndef __RD_TRANSFORM_CATALOG_UTILS_H__
#define __RD_TRANSFORM_CATALOG_UTILS_H__
#include <GraphMol/RDKitBase.h>
#include "TransformCatalogParams.h"
#include <GraphMol/Substruct/SubstructMatch.h>
#include <GraphMol/ChemReactions/Reaction.h>
#include <iostream>
namespace RDKit {
class ROMol;
namespace MolStandardize {
class TransformCatalogParams;
RDKIT_MOLSTANDARDIZE_EXPORT std::vector<std::shared_ptr<ChemicalReaction>>
readTransformations(std::string fileName);
RDKIT_MOLSTANDARDIZE_EXPORT std::vector<std::shared_ptr<ChemicalReaction>>
readTransformations(std::istream &inStream, int nToRead = -1);
} // namespace MolStandardize
} // namespace RDKit
#endif
| 1.03125 | 1 |
utr-application/imu.c | gregbreen/uncannier-thunderboard-react | 1 | 140 | /***************************************************************************//**
* @file
* @brief Inertial Measurement Unit
*******************************************************************************
* # License
* <b>Copyright 2018 Silicon Laboratories Inc. www.silabs.com</b>
*******************************************************************************
*
* The licensor of this software is Silicon Laboratories Inc. Your use of this
* software is governed by the terms of Silicon Labs Master Software License
* Agreement (MSLA) available at
* www.silabs.com/about-us/legal/master-software-license-agreement. This
* software is distributed to you in Source Code format and is governed by the
* sections of the MSLA applicable to Source Code.
*
******************************************************************************/
#include "imu.h"
#include <math.h>
/***************************************************************************************************
* Local Macros and Definitions
**************************************************************************************************/
#define MAX_ACCEL_FOR_ANGLE 0.9848
/***************************************************************************************************
* Local Function Definitions
**************************************************************************************************/
static void matrixMultiply(ImuFloat_t out[3][3], ImuFloat_t in_a[3][3], ImuFloat_t in_b[3][3])
{
ImuFloat_t op[3];
for (uint8_t x = 0; x < 3; x++) {
for (uint8_t y = 0; y < 3; y++) {
for (uint8_t w = 0; w < 3; w++) {
op[w] = in_a[x][w] * in_b[w][y];
}
out[x][y] = op[0] + op[1] + op[2];
}
}
}
static ImuFloat_t vectorDotProduct(ImuFloat_t in_a[3], ImuFloat_t in_b[3])
{
ImuFloat_t op = 0;
for (uint8_t x = 0; x < 3; x++) {
op += in_a[x] * in_b[x];
}
return op;
}
/***************************************************************************************************
* Public Function Definitions
**************************************************************************************************/
void imuAngleNormalize(ImuFloat_t *a)
{
while (*a >= IMU_PI) {
*a -= (2 * IMU_PI);
}
while (*a < -IMU_PI) {
*a += (2 * IMU_PI);
}
}
void imuVectorReset(ImuFloat_t inout[3])
{
for (uint8_t x = 0; x < 3; x++) {
inout[x] = 0.0;
}
}
void imuVectorAngleNormalize(ImuFloat_t inout[3])
{
for (uint8_t x = 0; x < 3; x++) {
imuAngleNormalize(&inout[x]);
}
}
void imuVectorAdd(ImuFloat_t out[3], ImuFloat_t in_a[3], ImuFloat_t in_b[3])
{
for (uint8_t x = 0; x < 3; x++) {
out[x] = in_a[x] + in_b[x];
}
}
void imuVectorSubtract(ImuFloat_t out[3], ImuFloat_t in_a[3], ImuFloat_t in_b[3])
{
for (uint8_t x = 0; x < 3; x++) {
out[x] = in_a[x] - in_b[x];
}
}
void imuVectorCopyAndScale(ImuFloat_t out[3], ImuFloat_t in[3], ImuFloat_t scale)
{
for (uint8_t x = 0; x < 3; x++) {
out[x] = in[x] * scale;
}
}
void imuVectorScale(ImuFloat_t inout[3], ImuFloat_t scale)
{
for (uint8_t x = 0; x < 3; x++) {
inout[x] *= scale;
}
}
void imuVectorCrossProduct(ImuFloat_t out[3], ImuFloat_t in_a[3], ImuFloat_t in_b[3])
{
out[0] = (in_a[1] * in_b[2]) - (in_a[2] * in_b[1]);
out[1] = (in_a[2] * in_b[0]) - (in_a[0] * in_b[2]);
out[2] = (in_a[0] * in_b[1]) - (in_a[1] * in_b[0]);
}
void imuDcmReset(ImuFloat_t dcmMatrix[3][3])
{
for (uint8_t y = 0; y < 3; y++) {
for (uint8_t x = 0; x < 3; x++) {
dcmMatrix[y][x] = (x == y) ? 1 : 0;
}
}
}
void imuDcmResetZ(ImuFloat_t dcmMatrix[3][3])
{
dcmMatrix[0][0] = 1;
dcmMatrix[0][1] = 0;
dcmMatrix[0][2] = 0;
imuVectorCrossProduct(&dcmMatrix[1][0], &dcmMatrix[0][0], &dcmMatrix[2][0]);
imuVectorScale(&dcmMatrix[1][0], -1.0);
imuVectorCrossProduct(&dcmMatrix[0][0], &dcmMatrix[1][0], &dcmMatrix[2][0]);
}
void imuDcmRotate(ImuFloat_t dcmMatrix[3][3], ImuFloat_t ang[3])
{
ImuFloat_t um[3][3];
ImuFloat_t tm[3][3];
um[0][0] = 0;
um[0][1] = -ang[2];
um[0][2] = ang[1];
um[1][0] = ang[2];
um[1][1] = 0;
um[1][2] = -ang[0];
um[2][0] = -ang[1];
um[2][1] = ang[0];
um[2][2] = 0;
matrixMultiply(tm, dcmMatrix, um);
for (uint8_t y = 0; y < 3; y++) {
for (uint8_t x = 0; x < 3; x++) {
dcmMatrix[y][x] += tm[y][x];
}
}
}
void imuDcmNormalize(ImuFloat_t dcmMatrix[3][3])
{
ImuFloat_t error = 0;
ImuFloat_t temporary[3][3];
ImuFloat_t renorm = 0;
error = -vectorDotProduct(&dcmMatrix[0][0], &dcmMatrix[1][0]) * .5;
imuVectorCopyAndScale(&temporary[0][0], &dcmMatrix[1][0], error);
imuVectorCopyAndScale(&temporary[1][0], &dcmMatrix[0][0], error);
imuVectorAdd(&temporary[0][0], &temporary[0][0], &dcmMatrix[0][0]);
imuVectorAdd(&temporary[1][0], &temporary[1][0], &dcmMatrix[1][0]);
imuVectorCrossProduct(&temporary[2][0], &temporary[0][0], &temporary[1][0]);
renorm = .5 * (3 - vectorDotProduct(&temporary[0][0], &temporary[0][0]));
imuVectorCopyAndScale(&dcmMatrix[0][0], &temporary[0][0], renorm);
renorm = .5 * (3 - vectorDotProduct(&temporary[1][0], &temporary[1][0]));
imuVectorCopyAndScale(&dcmMatrix[1][0], &temporary[1][0], renorm);
renorm = .5 * (3 - vectorDotProduct(&temporary[2][0], &temporary[2][0]));
imuVectorCopyAndScale(&dcmMatrix[2][0], &temporary[2][0], renorm);
}
void imuDcmGetAngles(ImuFloat_t dcmMatrix[3][3], ImuFloat_t ang[3])
{
// Roll
ang[0] = imuAtan2(dcmMatrix[2][1], dcmMatrix[2][2]);
// Pitch
ang[1] = -imuAsin(dcmMatrix[2][0]);
// Yaw
ang[2] = imuAtan2(dcmMatrix[1][0], dcmMatrix[0][0]);
}
void imuSensorFusionGyroCorrClr(ImuSensorFusion_t *fus)
{
imuVectorReset(fus->fusionAngleCorrection);
}
void imuSensorFusionGyroCorrDo(ImuSensorFusion_t *fus, ImuFloat_t gyr[3])
{
imuVectorAdd(gyr, gyr, fus->fusionAngleCorrection);
}
void imuSensorFusionGyroCorrCalc(ImuSensorFusion_t *fus, ImuFloat_t ori[3],
bool accValid, ImuFloat_t accVec[3],
bool dirValid, ImuFloat_t dirZ,
int16_t freq)
{
ImuFloat_t accAng[3];
imuSensorFusionGyroCorrClr(fus);
if (accValid
&& (accVec[0] >= -MAX_ACCEL_FOR_ANGLE) && (accVec[0] <= MAX_ACCEL_FOR_ANGLE)
&& (accVec[1] >= -MAX_ACCEL_FOR_ANGLE) && (accVec[1] <= MAX_ACCEL_FOR_ANGLE)) {
if (accVec[2] >= 0) {
accAng[0] = imuAsin(accVec[1]);
accAng[1] = -imuAsin(accVec[0]);
accAng[2] = dirZ;
imuVectorSubtract(fus->fusionAngleCorrection, accAng, ori);
imuVectorAngleNormalize(fus->fusionAngleCorrection);
} else {
accAng[0] = IMU_PI - imuAsin(accVec[1]);
accAng[1] = -imuAsin(accVec[0]);
accAng[2] = IMU_PI + dirZ;
imuVectorAngleNormalize(accAng);
imuVectorSubtract(fus->fusionAngleCorrection, accAng, ori);
imuVectorAngleNormalize(fus->fusionAngleCorrection);
fus->fusionAngleCorrection[1] = -fus->fusionAngleCorrection[1];
}
if (!dirValid) {
fus->fusionAngleCorrection[2] = 0;
}
imuVectorScale(fus->fusionAngleCorrection, 0.5 / freq);
}
}
| 1.023438 | 1 |
src/mac/region/RegionRU864.c | MysticChan/LoRaMac-node | 1 | 148 | /*!
* \file RegionRU864.c
*
* \brief Region implementation for RU864
*
* \copyright Revised BSD License, see section \ref LICENSE.
*
* \code
* ______ _
* / _____) _ | |
* ( (____ _____ ____ _| |_ _____ ____| |__
* \____ \| ___ | (_ _) ___ |/ ___) _ \
* _____) ) ____| | | || |_| ____( (___| | | |
* (______/|_____)_|_|_| \__)_____)\____)_| |_|
* (C)2013-2017 Semtech
*
* ___ _____ _ ___ _ _____ ___ ___ ___ ___
* / __|_ _/_\ / __| |/ / __/ _ \| _ \/ __| __|
* \__ \ | |/ _ \ (__| ' <| _| (_) | / (__| _|
* |___/ |_/_/ \_\___|_|\_\_| \___/|_|_\\___|___|
* embedded.connectivity.solutions===============
*
* \endcode
*
* \author <NAME> ( Semtech )
*
* \author <NAME> ( Semtech )
*
* \author <NAME> ( STACKFORCE )
*/
#include "utilities.h"
#include "RegionCommon.h"
#include "RegionRU864.h"
// Definitions
#define CHANNELS_MASK_SIZE 1
/*!
* Region specific context
*/
typedef struct sRegionRU864NvmCtx
{
/*!
* LoRaMAC channels
*/
ChannelParams_t Channels[ RU864_MAX_NB_CHANNELS ];
/*!
* LoRaMac bands
*/
Band_t Bands[ RU864_MAX_NB_BANDS ];
/*!
* LoRaMac channels mask
*/
uint16_t ChannelsMask[ CHANNELS_MASK_SIZE ];
/*!
* LoRaMac channels default mask
*/
uint16_t ChannelsDefaultMask[ CHANNELS_MASK_SIZE ];
}RegionRU864NvmCtx_t;
/*
* Non-volatile module context.
*/
static RegionRU864NvmCtx_t NvmCtx;
// Static functions
static int8_t GetNextLowerTxDr( int8_t dr, int8_t minDr )
{
uint8_t nextLowerDr = 0;
if( dr == minDr )
{
nextLowerDr = minDr;
}
else
{
nextLowerDr = dr - 1;
}
return nextLowerDr;
}
static uint32_t GetBandwidth( uint32_t drIndex )
{
switch( BandwidthsRU864[drIndex] )
{
default:
case 125000:
return 0;
case 250000:
return 1;
case 500000:
return 2;
}
}
static int8_t LimitTxPower( int8_t txPower, int8_t maxBandTxPower, int8_t datarate, uint16_t* channelsMask )
{
int8_t txPowerResult = txPower;
// Limit tx power to the band max
txPowerResult = MAX( txPower, maxBandTxPower );
return txPowerResult;
}
static bool VerifyRfFreq( uint32_t freq )
{
// Check radio driver support
if( Radio.CheckRfFrequency( freq ) == false )
{
return false;
}
// Check frequency bands
if( ( freq < 864000000 ) || ( freq > 870000000 ) )
{
return false;
}
return true;
}
static uint8_t CountNbOfEnabledChannels( bool joined, uint8_t datarate, uint16_t* channelsMask, ChannelParams_t* channels, Band_t* bands, uint8_t* enabledChannels, uint8_t* delayTx )
{
uint8_t nbEnabledChannels = 0;
uint8_t delayTransmission = 0;
for( uint8_t i = 0, k = 0; i < RU864_MAX_NB_CHANNELS; i += 16, k++ )
{
for( uint8_t j = 0; j < 16; j++ )
{
if( ( channelsMask[k] & ( 1 << j ) ) != 0 )
{
if( channels[i + j].Frequency == 0 )
{ // Check if the channel is enabled
continue;
}
if( joined == false )
{
if( ( RU864_JOIN_CHANNELS & ( 1 << j ) ) == 0 )
{
continue;
}
}
if( RegionCommonValueInRange( datarate, channels[i + j].DrRange.Fields.Min,
channels[i + j].DrRange.Fields.Max ) == false )
{ // Check if the current channel selection supports the given datarate
continue;
}
if( bands[channels[i + j].Band].TimeOff > 0 )
{ // Check if the band is available for transmission
delayTransmission++;
continue;
}
enabledChannels[nbEnabledChannels++] = i + j;
}
}
}
*delayTx = delayTransmission;
return nbEnabledChannels;
}
PhyParam_t RegionRU864GetPhyParam( GetPhyParams_t* getPhy )
{
PhyParam_t phyParam = { 0 };
switch( getPhy->Attribute )
{
case PHY_MIN_RX_DR:
{
phyParam.Value = RU864_RX_MIN_DATARATE;
break;
}
case PHY_MIN_TX_DR:
{
phyParam.Value = RU864_TX_MIN_DATARATE;
break;
}
case PHY_DEF_TX_DR:
{
phyParam.Value = RU864_DEFAULT_DATARATE;
break;
}
case PHY_NEXT_LOWER_TX_DR:
{
phyParam.Value = GetNextLowerTxDr( getPhy->Datarate, RU864_TX_MIN_DATARATE );
break;
}
case PHY_DEF_TX_POWER:
{
phyParam.Value = RU864_DEFAULT_TX_POWER;
break;
}
case PHY_DEF_ADR_ACK_LIMIT:
{
phyParam.Value = RU864_ADR_ACK_LIMIT;
break;
}
case PHY_DEF_ADR_ACK_DELAY:
{
phyParam.Value = RU864_ADR_ACK_DELAY;
break;
}
case PHY_MAX_PAYLOAD:
{
phyParam.Value = MaxPayloadOfDatarateRU864[getPhy->Datarate];
break;
}
case PHY_MAX_PAYLOAD_REPEATER:
{
phyParam.Value = MaxPayloadOfDatarateRepeaterRU864[getPhy->Datarate];
break;
}
case PHY_DUTY_CYCLE:
{
phyParam.Value = RU864_DUTY_CYCLE_ENABLED;
break;
}
case PHY_MAX_RX_WINDOW:
{
phyParam.Value = RU864_MAX_RX_WINDOW;
break;
}
case PHY_RECEIVE_DELAY1:
{
phyParam.Value = RU864_RECEIVE_DELAY1;
break;
}
case PHY_RECEIVE_DELAY2:
{
phyParam.Value = RU864_RECEIVE_DELAY2;
break;
}
case PHY_JOIN_ACCEPT_DELAY1:
{
phyParam.Value = RU864_JOIN_ACCEPT_DELAY1;
break;
}
case PHY_JOIN_ACCEPT_DELAY2:
{
phyParam.Value = RU864_JOIN_ACCEPT_DELAY2;
break;
}
case PHY_ACK_TIMEOUT:
{
phyParam.Value = ( RU864_ACKTIMEOUT + randr( -RU864_ACK_TIMEOUT_RND, RU864_ACK_TIMEOUT_RND ) );
break;
}
case PHY_DEF_DR1_OFFSET:
{
phyParam.Value = RU864_DEFAULT_RX1_DR_OFFSET;
break;
}
case PHY_DEF_RX2_FREQUENCY:
{
phyParam.Value = RU864_RX_WND_2_FREQ;
break;
}
case PHY_DEF_RX2_DR:
{
phyParam.Value = RU864_RX_WND_2_DR;
break;
}
case PHY_CHANNELS_MASK:
{
phyParam.ChannelsMask = NvmCtx.ChannelsMask;
break;
}
case PHY_CHANNELS_DEFAULT_MASK:
{
phyParam.ChannelsMask = NvmCtx.ChannelsDefaultMask;
break;
}
case PHY_MAX_NB_CHANNELS:
{
phyParam.Value = RU864_MAX_NB_CHANNELS;
break;
}
case PHY_CHANNELS:
{
phyParam.Channels = NvmCtx.Channels;
break;
}
case PHY_DEF_UPLINK_DWELL_TIME:
case PHY_DEF_DOWNLINK_DWELL_TIME:
{
phyParam.Value = 0;
break;
}
case PHY_DEF_MAX_EIRP:
{
phyParam.fValue = RU864_DEFAULT_MAX_EIRP;
break;
}
case PHY_DEF_ANTENNA_GAIN:
{
phyParam.fValue = RU864_DEFAULT_ANTENNA_GAIN;
break;
}
case PHY_BEACON_CHANNEL_FREQ:
{
phyParam.Value = RU864_BEACON_CHANNEL_FREQ;
break;
}
case PHY_BEACON_FORMAT:
{
phyParam.BeaconFormat.BeaconSize = RU864_BEACON_SIZE;
phyParam.BeaconFormat.Rfu1Size = RU864_RFU1_SIZE;
phyParam.BeaconFormat.Rfu2Size = RU864_RFU2_SIZE;
break;
}
case PHY_BEACON_CHANNEL_DR:
{
phyParam.Value = RU864_BEACON_CHANNEL_DR;
break;
}
default:
{
break;
}
}
return phyParam;
}
void RegionRU864SetBandTxDone( SetBandTxDoneParams_t* txDone )
{
RegionCommonSetBandTxDone( txDone->Joined, &NvmCtx.Bands[NvmCtx.Channels[txDone->Channel].Band], txDone->LastTxDoneTime );
}
void RegionRU864InitDefaults( InitDefaultsParams_t* params )
{
Band_t bands[RU864_MAX_NB_BANDS] =
{
RU864_BAND0
};
switch( params->Type )
{
case INIT_TYPE_INIT:
{
// Initialize bands
memcpy1( ( uint8_t* )NvmCtx.Bands, ( uint8_t* )bands, sizeof( Band_t ) * RU864_MAX_NB_BANDS );
// Channels
NvmCtx.Channels[0] = ( ChannelParams_t ) RU864_LC1;
NvmCtx.Channels[1] = ( ChannelParams_t ) RU864_LC2;
// Initialize the channels default mask
NvmCtx.ChannelsDefaultMask[0] = LC( 1 ) + LC( 2 );
// Update the channels mask
RegionCommonChanMaskCopy( NvmCtx.ChannelsMask, NvmCtx.ChannelsDefaultMask, 1 );
break;
}
case INIT_TYPE_RESTORE_CTX:
{
if( params->NvmCtx != 0 )
{
memcpy1( (uint8_t*) &NvmCtx, (uint8_t*) params->NvmCtx, sizeof( NvmCtx ) );
}
break;
}
case INIT_TYPE_RESTORE_DEFAULT_CHANNELS:
{
// Restore channels default mask
NvmCtx.ChannelsMask[0] |= NvmCtx.ChannelsDefaultMask[0];
break;
}
default:
{
break;
}
}
}
void* RegionRU864GetNvmCtx( GetNvmCtxParams_t* params )
{
params->nvmCtxSize = sizeof( RegionRU864NvmCtx_t );
return &NvmCtx;
}
bool RegionRU864Verify( VerifyParams_t* verify, PhyAttribute_t phyAttribute )
{
switch( phyAttribute )
{
case PHY_TX_DR:
{
return RegionCommonValueInRange( verify->DatarateParams.Datarate, RU864_TX_MIN_DATARATE, RU864_TX_MAX_DATARATE );
}
case PHY_DEF_TX_DR:
{
return RegionCommonValueInRange( verify->DatarateParams.Datarate, DR_0, DR_5 );
}
case PHY_RX_DR:
{
return RegionCommonValueInRange( verify->DatarateParams.Datarate, RU864_RX_MIN_DATARATE, RU864_RX_MAX_DATARATE );
}
case PHY_DEF_TX_POWER:
case PHY_TX_POWER:
{
// Remark: switched min and max!
return RegionCommonValueInRange( verify->TxPower, RU864_MAX_TX_POWER, RU864_MIN_TX_POWER );
}
case PHY_DUTY_CYCLE:
{
return RU864_DUTY_CYCLE_ENABLED;
}
default:
return false;
}
}
void RegionRU864ApplyCFList( ApplyCFListParams_t* applyCFList )
{
ChannelParams_t newChannel;
ChannelAddParams_t channelAdd;
ChannelRemoveParams_t channelRemove;
// Setup default datarate range
newChannel.DrRange.Value = ( DR_5 << 4 ) | DR_0;
// Size of the optional CF list
if( applyCFList->Size != 16 )
{
return;
}
// Last byte CFListType must be 0 to indicate the CFList contains a list of frequencies
if( applyCFList->Payload[15] != 0 )
{
return;
}
// Last byte is RFU, don't take it into account
for( uint8_t i = 0, chanIdx = RU864_NUMB_DEFAULT_CHANNELS; chanIdx < RU864_MAX_NB_CHANNELS; i+=3, chanIdx++ )
{
if( chanIdx < ( RU864_NUMB_CHANNELS_CF_LIST + RU864_NUMB_DEFAULT_CHANNELS ) )
{
// Channel frequency
newChannel.Frequency = (uint32_t) applyCFList->Payload[i];
newChannel.Frequency |= ( (uint32_t) applyCFList->Payload[i + 1] << 8 );
newChannel.Frequency |= ( (uint32_t) applyCFList->Payload[i + 2] << 16 );
newChannel.Frequency *= 100;
// Initialize alternative frequency to 0
newChannel.Rx1Frequency = 0;
}
else
{
newChannel.Frequency = 0;
newChannel.DrRange.Value = 0;
newChannel.Rx1Frequency = 0;
}
if( newChannel.Frequency != 0 )
{
channelAdd.NewChannel = &newChannel;
channelAdd.ChannelId = chanIdx;
// Try to add all channels
RegionRU864ChannelAdd( &channelAdd );
}
else
{
channelRemove.ChannelId = chanIdx;
RegionRU864ChannelsRemove( &channelRemove );
}
}
}
bool RegionRU864ChanMaskSet( ChanMaskSetParams_t* chanMaskSet )
{
switch( chanMaskSet->ChannelsMaskType )
{
case CHANNELS_MASK:
{
RegionCommonChanMaskCopy( NvmCtx.ChannelsMask, chanMaskSet->ChannelsMaskIn, 1 );
break;
}
case CHANNELS_DEFAULT_MASK:
{
RegionCommonChanMaskCopy( NvmCtx.ChannelsDefaultMask, chanMaskSet->ChannelsMaskIn, 1 );
break;
}
default:
return false;
}
return true;
}
void RegionRU864ComputeRxWindowParameters( int8_t datarate, uint8_t minRxSymbols, uint32_t rxError, RxConfigParams_t *rxConfigParams )
{
double tSymbol = 0.0;
// Get the datarate, perform a boundary check
rxConfigParams->Datarate = MIN( datarate, RU864_RX_MAX_DATARATE );
rxConfigParams->Bandwidth = GetBandwidth( rxConfigParams->Datarate );
if( rxConfigParams->Datarate == DR_7 )
{ // FSK
tSymbol = RegionCommonComputeSymbolTimeFsk( DataratesRU864[rxConfigParams->Datarate] );
}
else
{ // LoRa
tSymbol = RegionCommonComputeSymbolTimeLoRa( DataratesRU864[rxConfigParams->Datarate], BandwidthsRU864[rxConfigParams->Datarate] );
}
RegionCommonComputeRxWindowParameters( tSymbol, minRxSymbols, rxError, Radio.GetWakeupTime( ), &rxConfigParams->WindowTimeout, &rxConfigParams->WindowOffset );
}
bool RegionRU864RxConfig( RxConfigParams_t* rxConfig, int8_t* datarate )
{
RadioModems_t modem;
int8_t dr = rxConfig->Datarate;
uint8_t maxPayload = 0;
int8_t phyDr = 0;
uint32_t frequency = rxConfig->Frequency;
if( Radio.GetStatus( ) != RF_IDLE )
{
return false;
}
if( rxConfig->RxSlot == RX_SLOT_WIN_1 )
{
// Apply window 1 frequency
frequency = NvmCtx.Channels[rxConfig->Channel].Frequency;
// Apply the alternative RX 1 window frequency, if it is available
if( NvmCtx.Channels[rxConfig->Channel].Rx1Frequency != 0 )
{
frequency = NvmCtx.Channels[rxConfig->Channel].Rx1Frequency;
}
}
// Read the physical datarate from the datarates table
phyDr = DataratesRU864[dr];
Radio.SetChannel( frequency );
// Radio configuration
if( dr == DR_7 )
{
modem = MODEM_FSK;
Radio.SetRxConfig( modem, 50000, phyDr * 1000, 0, 83333, 5, rxConfig->WindowTimeout, false, 0, true, 0, 0, false, rxConfig->RxContinuous );
}
else
{
modem = MODEM_LORA;
Radio.SetRxConfig( modem, rxConfig->Bandwidth, phyDr, 1, 0, 8, rxConfig->WindowTimeout, false, 0, false, 0, 0, true, rxConfig->RxContinuous );
}
if( rxConfig->RepeaterSupport == true )
{
maxPayload = MaxPayloadOfDatarateRepeaterRU864[dr];
}
else
{
maxPayload = MaxPayloadOfDatarateRU864[dr];
}
Radio.SetMaxPayloadLength( modem, maxPayload + LORA_MAC_FRMPAYLOAD_OVERHEAD );
*datarate = (uint8_t) dr;
return true;
}
bool RegionRU864TxConfig( TxConfigParams_t* txConfig, int8_t* txPower, TimerTime_t* txTimeOnAir )
{
RadioModems_t modem;
int8_t phyDr = DataratesRU864[txConfig->Datarate];
int8_t txPowerLimited = LimitTxPower( txConfig->TxPower, NvmCtx.Bands[NvmCtx.Channels[txConfig->Channel].Band].TxMaxPower, txConfig->Datarate, NvmCtx.ChannelsMask );
uint32_t bandwidth = GetBandwidth( txConfig->Datarate );
int8_t phyTxPower = 0;
// Calculate physical TX power
phyTxPower = RegionCommonComputeTxPower( txPowerLimited, txConfig->MaxEirp, txConfig->AntennaGain );
// Setup the radio frequency
Radio.SetChannel( NvmCtx.Channels[txConfig->Channel].Frequency );
if( txConfig->Datarate == DR_7 )
{ // High Speed FSK channel
modem = MODEM_FSK;
Radio.SetTxConfig( modem, phyTxPower, 25000, bandwidth, phyDr * 1000, 0, 5, false, true, 0, 0, false, 3000 );
}
else
{
modem = MODEM_LORA;
Radio.SetTxConfig( modem, phyTxPower, 0, bandwidth, phyDr, 1, 8, false, true, 0, 0, false, 3000 );
}
// Setup maximum payload lenght of the radio driver
Radio.SetMaxPayloadLength( modem, txConfig->PktLen );
// Get the time-on-air of the next tx frame
*txTimeOnAir = Radio.TimeOnAir( modem, txConfig->PktLen );
*txPower = txPowerLimited;
return true;
}
uint8_t RegionRU864LinkAdrReq( LinkAdrReqParams_t* linkAdrReq, int8_t* drOut, int8_t* txPowOut, uint8_t* nbRepOut, uint8_t* nbBytesParsed )
{
uint8_t status = 0x07;
RegionCommonLinkAdrParams_t linkAdrParams;
uint8_t nextIndex = 0;
uint8_t bytesProcessed = 0;
uint16_t chMask = 0;
GetPhyParams_t getPhy;
PhyParam_t phyParam;
RegionCommonLinkAdrReqVerifyParams_t linkAdrVerifyParams;
while( bytesProcessed < linkAdrReq->PayloadSize )
{
// Get ADR request parameters
nextIndex = RegionCommonParseLinkAdrReq( &( linkAdrReq->Payload[bytesProcessed] ), &linkAdrParams );
if( nextIndex == 0 )
break; // break loop, since no more request has been found
// Update bytes processed
bytesProcessed += nextIndex;
// Revert status, as we only check the last ADR request for the channel mask KO
status = 0x07;
// Setup temporary channels mask
chMask = linkAdrParams.ChMask;
// Verify channels mask
if( ( linkAdrParams.ChMaskCtrl == 0 ) && ( chMask == 0 ) )
{
status &= 0xFE; // Channel mask KO
}
else if( ( ( linkAdrParams.ChMaskCtrl >= 1 ) && ( linkAdrParams.ChMaskCtrl <= 5 )) ||
( linkAdrParams.ChMaskCtrl >= 7 ) )
{
// RFU
status &= 0xFE; // Channel mask KO
}
else
{
for( uint8_t i = 0; i < RU864_MAX_NB_CHANNELS; i++ )
{
if( linkAdrParams.ChMaskCtrl == 6 )
{
if( NvmCtx.Channels[i].Frequency != 0 )
{
chMask |= 1 << i;
}
}
else
{
if( ( ( chMask & ( 1 << i ) ) != 0 ) &&
( NvmCtx.Channels[i].Frequency == 0 ) )
{// Trying to enable an undefined channel
status &= 0xFE; // Channel mask KO
}
}
}
}
}
// Get the minimum possible datarate
getPhy.Attribute = PHY_MIN_TX_DR;
getPhy.UplinkDwellTime = linkAdrReq->UplinkDwellTime;
phyParam = RegionRU864GetPhyParam( &getPhy );
linkAdrVerifyParams.Status = status;
linkAdrVerifyParams.AdrEnabled = linkAdrReq->AdrEnabled;
linkAdrVerifyParams.Datarate = linkAdrParams.Datarate;
linkAdrVerifyParams.TxPower = linkAdrParams.TxPower;
linkAdrVerifyParams.NbRep = linkAdrParams.NbRep;
linkAdrVerifyParams.CurrentDatarate = linkAdrReq->CurrentDatarate;
linkAdrVerifyParams.CurrentTxPower = linkAdrReq->CurrentTxPower;
linkAdrVerifyParams.CurrentNbRep = linkAdrReq->CurrentNbRep;
linkAdrVerifyParams.NbChannels = RU864_MAX_NB_CHANNELS;
linkAdrVerifyParams.ChannelsMask = &chMask;
linkAdrVerifyParams.MinDatarate = ( int8_t )phyParam.Value;
linkAdrVerifyParams.MaxDatarate = RU864_TX_MAX_DATARATE;
linkAdrVerifyParams.Channels = NvmCtx.Channels;
linkAdrVerifyParams.MinTxPower = RU864_MIN_TX_POWER;
linkAdrVerifyParams.MaxTxPower = RU864_MAX_TX_POWER;
linkAdrVerifyParams.Version = linkAdrReq->Version;
// Verify the parameters and update, if necessary
status = RegionCommonLinkAdrReqVerifyParams( &linkAdrVerifyParams, &linkAdrParams.Datarate, &linkAdrParams.TxPower, &linkAdrParams.NbRep );
// Update channelsMask if everything is correct
if( status == 0x07 )
{
// Set the channels mask to a default value
memset1( ( uint8_t* ) NvmCtx.ChannelsMask, 0, sizeof( NvmCtx.ChannelsMask ) );
// Update the channels mask
NvmCtx.ChannelsMask[0] = chMask;
}
// Update status variables
*drOut = linkAdrParams.Datarate;
*txPowOut = linkAdrParams.TxPower;
*nbRepOut = linkAdrParams.NbRep;
*nbBytesParsed = bytesProcessed;
return status;
}
uint8_t RegionRU864RxParamSetupReq( RxParamSetupReqParams_t* rxParamSetupReq )
{
uint8_t status = 0x07;
// Verify radio frequency
if( VerifyRfFreq( rxParamSetupReq->Frequency ) == false )
{
status &= 0xFE; // Channel frequency KO
}
// Verify datarate
if( RegionCommonValueInRange( rxParamSetupReq->Datarate, RU864_RX_MIN_DATARATE, RU864_RX_MAX_DATARATE ) == false )
{
status &= 0xFD; // Datarate KO
}
// Verify datarate offset
if( RegionCommonValueInRange( rxParamSetupReq->DrOffset, RU864_MIN_RX1_DR_OFFSET, RU864_MAX_RX1_DR_OFFSET ) == false )
{
status &= 0xFB; // Rx1DrOffset range KO
}
return status;
}
uint8_t RegionRU864NewChannelReq( NewChannelReqParams_t* newChannelReq )
{
uint8_t status = 0x03;
ChannelAddParams_t channelAdd;
ChannelRemoveParams_t channelRemove;
if( newChannelReq->NewChannel->Frequency == 0 )
{
channelRemove.ChannelId = newChannelReq->ChannelId;
// Remove
if( RegionRU864ChannelsRemove( &channelRemove ) == false )
{
status &= 0xFC;
}
}
else
{
channelAdd.NewChannel = newChannelReq->NewChannel;
channelAdd.ChannelId = newChannelReq->ChannelId;
switch( RegionRU864ChannelAdd( &channelAdd ) )
{
case LORAMAC_STATUS_OK:
{
break;
}
case LORAMAC_STATUS_FREQUENCY_INVALID:
{
status &= 0xFE;
break;
}
case LORAMAC_STATUS_DATARATE_INVALID:
{
status &= 0xFD;
break;
}
case LORAMAC_STATUS_FREQ_AND_DR_INVALID:
{
status &= 0xFC;
break;
}
default:
{
status &= 0xFC;
break;
}
}
}
return status;
}
int8_t RegionRU864TxParamSetupReq( TxParamSetupReqParams_t* txParamSetupReq )
{
return -1;
}
uint8_t RegionRU864DlChannelReq( DlChannelReqParams_t* dlChannelReq )
{
uint8_t status = 0x03;
// Verify if the frequency is supported
if( VerifyRfFreq( dlChannelReq->Rx1Frequency ) == false )
{
status &= 0xFE;
}
// Verify if an uplink frequency exists
if( NvmCtx.Channels[dlChannelReq->ChannelId].Frequency == 0 )
{
status &= 0xFD;
}
// Apply Rx1 frequency, if the status is OK
if( status == 0x03 )
{
NvmCtx.Channels[dlChannelReq->ChannelId].Rx1Frequency = dlChannelReq->Rx1Frequency;
}
return status;
}
int8_t RegionRU864AlternateDr( int8_t currentDr, AlternateDrType_t type )
{
return currentDr;
}
void RegionRU864CalcBackOff( CalcBackOffParams_t* calcBackOff )
{
RegionCommonCalcBackOffParams_t calcBackOffParams;
calcBackOffParams.Channels = NvmCtx.Channels;
calcBackOffParams.Bands = NvmCtx.Bands;
calcBackOffParams.LastTxIsJoinRequest = calcBackOff->LastTxIsJoinRequest;
calcBackOffParams.Joined = calcBackOff->Joined;
calcBackOffParams.DutyCycleEnabled = calcBackOff->DutyCycleEnabled;
calcBackOffParams.Channel = calcBackOff->Channel;
calcBackOffParams.ElapsedTime = calcBackOff->ElapsedTime;
calcBackOffParams.TxTimeOnAir = calcBackOff->TxTimeOnAir;
RegionCommonCalcBackOff( &calcBackOffParams );
}
LoRaMacStatus_t RegionRU864NextChannel( NextChanParams_t* nextChanParams, uint8_t* channel, TimerTime_t* time, TimerTime_t* aggregatedTimeOff )
{
uint8_t nbEnabledChannels = 0;
uint8_t delayTx = 0;
uint8_t enabledChannels[RU864_MAX_NB_CHANNELS] = { 0 };
TimerTime_t nextTxDelay = 0;
if( RegionCommonCountChannels( NvmCtx.ChannelsMask, 0, 1 ) == 0 )
{ // Reactivate default channels
NvmCtx.ChannelsMask[0] |= LC( 1 ) + LC( 2 );
}
if( nextChanParams->AggrTimeOff <= TimerGetElapsedTime( nextChanParams->LastAggrTx ) )
{
// Reset Aggregated time off
*aggregatedTimeOff = 0;
// Update bands Time OFF
nextTxDelay = RegionCommonUpdateBandTimeOff( nextChanParams->Joined, nextChanParams->DutyCycleEnabled, NvmCtx.Bands, RU864_MAX_NB_BANDS );
// Search how many channels are enabled
nbEnabledChannels = CountNbOfEnabledChannels( nextChanParams->Joined, nextChanParams->Datarate,
NvmCtx.ChannelsMask, NvmCtx.Channels,
NvmCtx.Bands, enabledChannels, &delayTx );
}
else
{
delayTx++;
nextTxDelay = nextChanParams->AggrTimeOff - TimerGetElapsedTime( nextChanParams->LastAggrTx );
}
if( nbEnabledChannels > 0 )
{
// We found a valid channel
*channel = enabledChannels[randr( 0, nbEnabledChannels - 1 )];
*time = 0;
return LORAMAC_STATUS_OK;
}
else
{
if( delayTx > 0 )
{
// Delay transmission due to AggregatedTimeOff or to a band time off
*time = nextTxDelay;
return LORAMAC_STATUS_DUTYCYCLE_RESTRICTED;
}
// Datarate not supported by any channel, restore defaults
NvmCtx.ChannelsMask[0] |= LC( 1 ) + LC( 2 );
*time = 0;
return LORAMAC_STATUS_NO_CHANNEL_FOUND;
}
}
LoRaMacStatus_t RegionRU864ChannelAdd( ChannelAddParams_t* channelAdd )
{
bool drInvalid = false;
bool freqInvalid = false;
uint8_t id = channelAdd->ChannelId;
if( id < RU864_NUMB_DEFAULT_CHANNELS )
{
return LORAMAC_STATUS_FREQ_AND_DR_INVALID;
}
if( id >= RU864_MAX_NB_CHANNELS )
{
return LORAMAC_STATUS_PARAMETER_INVALID;
}
// Validate the datarate range
if( RegionCommonValueInRange( channelAdd->NewChannel->DrRange.Fields.Min, RU864_TX_MIN_DATARATE, RU864_TX_MAX_DATARATE ) == false )
{
drInvalid = true;
}
if( RegionCommonValueInRange( channelAdd->NewChannel->DrRange.Fields.Max, RU864_TX_MIN_DATARATE, RU864_TX_MAX_DATARATE ) == false )
{
drInvalid = true;
}
if( channelAdd->NewChannel->DrRange.Fields.Min > channelAdd->NewChannel->DrRange.Fields.Max )
{
drInvalid = true;
}
// Check frequency
if( freqInvalid == false )
{
if( VerifyRfFreq( channelAdd->NewChannel->Frequency ) == false )
{
freqInvalid = true;
}
}
// Check status
if( ( drInvalid == true ) && ( freqInvalid == true ) )
{
return LORAMAC_STATUS_FREQ_AND_DR_INVALID;
}
if( drInvalid == true )
{
return LORAMAC_STATUS_DATARATE_INVALID;
}
if( freqInvalid == true )
{
return LORAMAC_STATUS_FREQUENCY_INVALID;
}
memcpy1( ( uint8_t* ) &(NvmCtx.Channels[id]), ( uint8_t* ) channelAdd->NewChannel, sizeof( NvmCtx.Channels[id] ) );
NvmCtx.Channels[id].Band = 0;
NvmCtx.ChannelsMask[0] |= ( 1 << id );
return LORAMAC_STATUS_OK;
}
bool RegionRU864ChannelsRemove( ChannelRemoveParams_t* channelRemove )
{
uint8_t id = channelRemove->ChannelId;
if( id < RU864_NUMB_DEFAULT_CHANNELS )
{
return false;
}
// Remove the channel from the list of channels
NvmCtx.Channels[id] = ( ChannelParams_t ){ 0, 0, { 0 }, 0 };
return RegionCommonChanDisable( NvmCtx.ChannelsMask, id, RU864_MAX_NB_CHANNELS );
}
void RegionRU864SetContinuousWave( ContinuousWaveParams_t* continuousWave )
{
int8_t txPowerLimited = LimitTxPower( continuousWave->TxPower, NvmCtx.Bands[NvmCtx.Channels[continuousWave->Channel].Band].TxMaxPower, continuousWave->Datarate, NvmCtx.ChannelsMask );
int8_t phyTxPower = 0;
uint32_t frequency = NvmCtx.Channels[continuousWave->Channel].Frequency;
// Calculate physical TX power
phyTxPower = RegionCommonComputeTxPower( txPowerLimited, continuousWave->MaxEirp, continuousWave->AntennaGain );
Radio.SetTxContinuousWave( frequency, phyTxPower, continuousWave->Timeout );
}
uint8_t RegionRU864ApplyDrOffset( uint8_t downlinkDwellTime, int8_t dr, int8_t drOffset )
{
int8_t datarate = dr - drOffset;
if( datarate < 0 )
{
datarate = DR_0;
}
return datarate;
}
void RegionRU864RxBeaconSetup( RxBeaconSetup_t* rxBeaconSetup, uint8_t* outDr )
{
RegionCommonRxBeaconSetupParams_t regionCommonRxBeaconSetup;
regionCommonRxBeaconSetup.Datarates = DataratesRU864;
regionCommonRxBeaconSetup.Frequency = rxBeaconSetup->Frequency;
regionCommonRxBeaconSetup.BeaconSize = RU864_BEACON_SIZE;
regionCommonRxBeaconSetup.BeaconDatarate = RU864_BEACON_CHANNEL_DR;
regionCommonRxBeaconSetup.BeaconChannelBW = RU864_BEACON_CHANNEL_BW;
regionCommonRxBeaconSetup.RxTime = rxBeaconSetup->RxTime;
regionCommonRxBeaconSetup.SymbolTimeout = rxBeaconSetup->SymbolTimeout;
RegionCommonRxBeaconSetup( ®ionCommonRxBeaconSetup );
// Store downlink datarate
*outDr = RU864_BEACON_CHANNEL_DR;
}
| 0.914063 | 1 |
cache_lat.c | mdr78/cpu_tools | 0 | 156 | /*
* https://stackoverflow.com/questions/21369381/measuring-cache-latencies
*/
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
int i386_cpuid_caches(size_t *data_caches) {
int i;
int num_data_caches = 0;
for (i = 0; i < 32; i++) {
// Variables to hold the contents of the 4 i386 legacy registers
uint32_t eax, ebx, ecx, edx;
eax = 4; // get cache info
ecx = i; // cache id
asm("cpuid" // call i386 cpuid instruction
: "+a"(eax) // contains the cpuid command code, 4 for cache query
,
"=b"(ebx), "+c"(ecx) // contains the cache id
,
"=d"(edx)); // generates output in 4 registers eax, ebx, ecx and edx
// taken from http://download.intel.com/products/processor/manual/325462.pdf
// Vol. 2A 3-149
int cache_type = eax & 0x1F;
if (cache_type == 0) // end of valid cache identifiers
break;
char *cache_type_string;
switch (cache_type) {
case 1:
cache_type_string = "Data Cache";
break;
case 2:
cache_type_string = "Instruction Cache";
break;
case 3:
cache_type_string = "Unified Cache";
break;
default:
cache_type_string = "Unknown Type Cache";
break;
}
int cache_level = (eax >>= 5) & 0x7;
int cache_is_self_initializing =
(eax >>= 3) & 0x1; // does not need SW initialization
int cache_is_fully_associative = (eax >>= 1) & 0x1;
// taken from http://download.intel.com/products/processor/manual/325462.pdf
// 3-166 Vol. 2A ebx contains 3 integers of 10, 10 and 12 bits respectively
unsigned int cache_sets = ecx + 1;
unsigned int cache_coherency_line_size = (ebx & 0xFFF) + 1;
unsigned int cache_physical_line_partitions = ((ebx >>= 12) & 0x3FF) + 1;
unsigned int cache_ways_of_associativity = ((ebx >>= 10) & 0x3FF) + 1;
// Total cache size is the product
size_t cache_total_size = cache_ways_of_associativity *
cache_physical_line_partitions *
cache_coherency_line_size * cache_sets;
if (cache_type == 1 || cache_type == 3) {
data_caches[num_data_caches++] = cache_total_size;
}
printf("Cache ID %d:\n"
"- Level: %d\n"
"- Type: %s\n"
"- Sets: %d\n"
"- System Coherency Line Size: %d bytes\n"
"- Physical Line partitions: %d\n"
"- Ways of associativity: %d\n"
"- Total Size: %zu bytes (%zu kb)\n"
"- Is fully associative: %s\n"
"- Is Self Initializing: %s\n"
"\n",
i, cache_level, cache_type_string, cache_sets,
cache_coherency_line_size, cache_physical_line_partitions,
cache_ways_of_associativity, cache_total_size,
cache_total_size >> 10,
cache_is_fully_associative ? "true" : "false",
cache_is_self_initializing ? "true" : "false");
}
return num_data_caches;
}
int test_cache(size_t attempts, size_t lower_cache_size, int *latencies,
size_t max_latency) {
int fd = open("/dev/urandom", O_RDONLY);
if (fd < 0) {
perror("open");
abort();
}
char *random_data = mmap(NULL, lower_cache_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANON // | MAP_POPULATE
,
-1, 0); // get some random data
if (random_data == MAP_FAILED) {
perror("mmap");
abort();
}
size_t i;
for (i = 0; i < lower_cache_size; i += sysconf(_SC_PAGESIZE)) {
random_data[i] = 1;
}
int64_t random_offset = 0;
while (attempts--) {
// use processor clock timer for exact measurement
random_offset += rand();
random_offset %= lower_cache_size;
int32_t cycles_used, edx, temp1, temp2;
asm("mfence\n\t" // memory fence
"rdtsc\n\t" // get cpu cycle count
"mov %%edx, %2\n\t"
"mov %%eax, %3\n\t"
"mfence\n\t" // memory fence
"mov %4, %%al\n\t" // load data
"mfence\n\t"
"rdtsc\n\t"
"sub %2, %%edx\n\t" // substract cycle count
"sbb %3, %%eax" // substract cycle count
: "=&a"(cycles_used), "=&d"(edx), "=&r"(temp1), "=&r"(temp2)
: "m"(random_data[random_offset]));
// printf("%d\n", cycles_used);
if (cycles_used < max_latency)
latencies[cycles_used]++;
else
latencies[max_latency - 1]++;
}
munmap(random_data, lower_cache_size);
return 0;
}
int main() {
size_t cache_sizes[32];
int num_data_caches = i386_cpuid_caches(cache_sizes);
int latencies[0x400];
memset(latencies, 0, sizeof(latencies));
int empty_cycles = 0;
int i;
int attempts = 1000000;
for (i = 0; i < attempts;
i++) { // measure how much overhead we have for counting cyscles
int32_t cycles_used, edx, temp1, temp2;
asm("mfence\n\t" // memory fence
"rdtsc\n\t" // get cpu cycle count
"mov %%edx, %2\n\t"
"mov %%eax, %3\n\t"
"mfence\n\t" // memory fence
"mfence\n\t"
"rdtsc\n\t"
"sub %2, %%edx\n\t" // substract cycle count
"sbb %3, %%eax" // substract cycle count
: "=a"(cycles_used), "=&d"(edx), "=&r"(temp1), "=&r"(temp2)
:);
if (cycles_used < sizeof(latencies) / sizeof(*latencies))
latencies[cycles_used]++;
else
latencies[sizeof(latencies) / sizeof(*latencies) - 1]++;
}
{
int j;
size_t sum = 0;
for (j = 0; j < sizeof(latencies) / sizeof(*latencies); j++) {
sum += latencies[j];
}
size_t sum2 = 0;
for (j = 0; j < sizeof(latencies) / sizeof(*latencies); j++) {
sum2 += latencies[j];
if (sum2 >= sum * .75) {
empty_cycles = j;
fprintf(stderr, "Empty counting takes %d cycles\n", empty_cycles);
break;
}
}
}
for (i = 0; i < num_data_caches; i++) {
test_cache(attempts, cache_sizes[i] * 4, latencies,
sizeof(latencies) / sizeof(*latencies));
int j;
size_t sum = 0;
for (j = 0; j < sizeof(latencies) / sizeof(*latencies); j++) {
sum += latencies[j];
}
size_t sum2 = 0;
for (j = 0; j < sizeof(latencies) / sizeof(*latencies); j++) {
sum2 += latencies[j];
if (sum2 >= sum * .75) {
fprintf(stderr, "Cache ID %i has latency %d cycles\n", i,
j - empty_cycles);
break;
}
}
}
return 0;
}
| 2.328125 | 2 |
third_party/hdf5-1.10.6/test/external_common.c | bradosia/fasta5-viewer | 0 | 164 | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright by The HDF Group. *
* Copyright by the Board of Trustees of the University of Illinois. *
* All rights reserved. *
* *
* This file is part of HDF5. The full HDF5 copyright notice, including *
* terms governing use, modification, and redistribution, is contained in *
* the COPYING file, which can be found at the root of the source code *
* distribution tree, or in https://support.hdfgroup.org/ftp/HDF5/releases. *
* If you do not have access to either file, you may request a copy from *
* <EMAIL>. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*
* Programmer: <NAME> <<EMAIL>>
* April, 2019
*
* Purpose: Private function for external.c and external_env.c
*/
#include "external_common.h"
/*-------------------------------------------------------------------------
* Function: reset_raw_data_files
*
* Purpose: Resets the data in the raw data files for tests that
* perform dataset I/O on a set of files.
*
* Return: SUCCEED/FAIL
*
* Programmer: <NAME>
* February 2016
*
*-------------------------------------------------------------------------
*/
herr_t
reset_raw_data_files(hbool_t is_env)
{
int fd = 0; /* external file descriptor */
size_t i, j; /* iterators */
hssize_t n; /* bytes of I/O */
char filename[1024]; /* file name */
int data[PART_SIZE]; /* raw data buffer */
uint8_t *garbage = NULL; /* buffer of garbage data */
size_t garbage_count; /* size of garbage buffer */
size_t garbage_bytes; /* # of garbage bytes written to file */
/* Set up garbage buffer */
garbage_count = N_EXT_FILES * GARBAGE_PER_FILE;
if(NULL == (garbage = (uint8_t *)HDcalloc(garbage_count, sizeof(uint8_t))))
goto error;
for(i = 0; i < garbage_count; i++)
garbage[i] = 0xFF;
/* The *r files are pre-filled with data and are used to
* verify that read operations work correctly.
*/
for(i = 0; i < N_EXT_FILES; i++) {
/* Open file */
if(is_env)
HDsprintf(filename, "extern_env_dir%sextern_env_%lur.raw", H5_DIR_SEPS, (unsigned long)i + 1);
else
HDsprintf(filename, "extern_%lur.raw", (unsigned long)i + 1);
if((fd = HDopen(filename, O_RDWR|O_CREAT|O_TRUNC, H5_POSIX_CREATE_MODE_RW)) < 0)
goto error;
/* Write garbage data to the file. This allows us to test the
* the ability to set an offset in the raw data file.
*/
garbage_bytes = i * 10;
n = HDwrite(fd, garbage, garbage_bytes);
if(n < 0 || (size_t)n != garbage_bytes)
goto error;
/* Fill array with data */
for(j = 0; j < PART_SIZE; j++) {
data[j] = (int)(i * 25 + j);
} /* end for */
/* Write raw data to the file. */
n = HDwrite(fd, data, sizeof(data));
if(n != sizeof(data))
goto error;
/* Close this file */
HDclose(fd);
} /* end for */
/* The *w files are only pre-filled with the garbage data and are
* used to verify that write operations work correctly. The individual
* tests fill in the actual data.
*/
for(i = 0; i < N_EXT_FILES; i++) {
/* Open file */
if(is_env)
HDsprintf(filename, "extern_env_dir%sextern_env_%luw.raw", H5_DIR_SEPS, (unsigned long)i + 1);
else
HDsprintf(filename, "extern_%luw.raw", (unsigned long)i + 1);
if((fd = HDopen(filename, O_RDWR|O_CREAT|O_TRUNC, H5_POSIX_CREATE_MODE_RW)) < 0)
goto error;
/* Write garbage data to the file. This allows us to test the
* the ability to set an offset in the raw data file.
*/
garbage_bytes = i * 10;
n = HDwrite(fd, garbage, garbage_bytes);
if(n < 0 || (size_t)n != garbage_bytes)
goto error;
/* Close this file */
HDclose(fd);
} /* end for */
HDfree(garbage);
return SUCCEED;
error:
if(fd)
HDclose(fd);
if(garbage)
HDfree(garbage);
return FAIL;
}
| 1.28125 | 1 |
System/Library/Frameworks/CoreData.framework/NSSQLModel.h | lechium/tvOS135Headers | 2 | 172 | /*
* This header is generated by classdump-dyld 1.0
* on Sunday, June 7, 2020 at 11:12:51 AM Mountain Standard Time
* Operating System: Version 13.4.5 (Build 17L562)
* Image Source: /System/Library/Frameworks/CoreData.framework/CoreData
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>.
*/
#import <CoreData/NSStoreMapping.h>
@class NSString, NSManagedObjectModel, NSKnownKeysDictionary, NSMutableArray;
@interface NSSQLModel : NSStoreMapping {
NSString* _configuration;
NSManagedObjectModel* _mom;
NSKnownKeysDictionary* _entitiesByName;
NSMutableArray* _entities;
id* _entityDescriptionToSQLMap;
unsigned long long _brokenHashVersion;
BOOL _retainLeopardStyleDictionaries;
BOOL _modelHasPrecomputedKeyOrder;
BOOL _hasVirtualToOnes;
unsigned _entityIDOffset;
unsigned _lastEntityID;
}
-(void)dealloc;
-(void)finalize;
-(id)configurationName;
-(id)entityForID:(unsigned long long)arg1 ;
-(id)managedObjectModel;
-(id)entities;
-(id)initWithManagedObjectModel:(id)arg1 configurationName:(id)arg2 ;
-(id)entitiesByName;
-(unsigned)_entityOffset;
-(id)initWithManagedObjectModel:(id)arg1 configurationName:(id)arg2 retainHashHack:(BOOL)arg3 ;
-(id)entityNamed:(id)arg1 ;
-(unsigned long long)entityIDForName:(id)arg1 ;
-(id)initWithManagedObjectModel:(id)arg1 configurationName:(id)arg2 brokenHashVersion:(unsigned long long)arg3 ;
-(BOOL)_modelHasPrecomputedKeyOrder;
-(void)_recordHasVirtualToOnes;
-(BOOL)_useLeopardStyleHashing;
-(BOOL)_useSnowLeopardStyleHashing;
-(id)_precomputedKeyOrderForEntity:(id)arg1 ;
-(void)_addIndexedEntity:(id)arg1 ;
-(BOOL)_generateModel:(id)arg1 error:(id*)arg2 ;
-(id)initWithManagedObjectModel:(id)arg1 configurationName:(id)arg2 retainHashHack:(BOOL)arg3 brokenHashVersion:(unsigned long long)arg4 ;
-(id)_entityMapping;
-(id)_sqlEntityWithRenamingIdentifier:(id)arg1 ;
-(unsigned)_lastEntityID;
-(BOOL)_retainHashHack;
@end
| 0.804688 | 1 |
blast/include/corelib/mswin_no_popup.h | mycolab/ncbi-blast | 0 | 180 | #ifndef CORELIB___MSWIN_NO_POPUP__H
#define CORELIB___MSWIN_NO_POPUP__H
/* $Id: mswin_no_popup.h 607865 2020-05-08 12:35:14Z ivanov $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: <NAME>
*
* File Description: Suppress popup messages on execution errors.
* MS Windows specific.
*
* Include this header only to applications, not libraries.
*
*/
#include <ncbiconf.h>
/* To avoid code duplication reuse code from <common/test_assert[_impl].h>.
This preprocessor macro turn OFF all assert-related tune-ups and turn ON
suppress popup messages code. Environment variable DIAG_SILENT_ABORT
must be set to "Y" or "y" to suppress popup messages.
*/
#define NCBI_MSWIN_NO_POPUP
/* In case anyone needs to always disable the popup messages (regardless of DIAG_SILENT_ABDORT)
another pre-processor macro can be defined before #include'ing either
<corelib/mswin_no_popup.h> (or <common/test_assert.h>).
*/
/* #define NCBI_MSWIN_NO_POPUP_EVER */
#include <common/test_assert.h>
#endif /* CORELIB___MSWIN_NO_POPUP__H */
| 0.902344 | 1 |
termsrv/drivers/rdp/rdpwd/hotkey.c | npocmaka/Windows-Server-2003 | 17 | 188 | /****************************************************************************/
/* hotkey.c */
/* */
/* RDP Shadow hotkey handling functions. */
/* */
/* Copyright(C) Microsoft Corporation 1997-2000 */
/****************************************************************************/
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#define TRC_FILE "hotkey"
#include <precomp.h>
#pragma hdrstop
#define pTRCWd pWd
#include <adcg.h>
#include <nwdwapi.h>
#include <nwdwint.h>
#include "kbd.h" //TODO: Good Grief!
typedef struct {
DWORD dwVersion;
DWORD dwFlags;
DWORD dwMapCount;
DWORD dwMap[0];
} SCANCODEMAP, *PSCANCODEMAP;
/***************************************************************************\
* How some Virtual Key values change when a SHIFT key is held down.
\***************************************************************************/
#define VK_MULTIPLY 0x6A
#define VK_SNAPSHOT 0x2C
const ULONG aulShiftCvt_VK[] = {
MAKELONG(VK_MULTIPLY, VK_SNAPSHOT),
MAKELONG(0,0)
};
/***************************************************************************\
* How some Virtual Key values change when a CONTROL key is held down.
\***************************************************************************/
#define VK_LSHIFT 0xA0
#define VK_RSHIFT 0xA1
#define VK_LCONTROL 0xA2
#define VK_RCONTROL 0xA3
#define VK_LMENU 0xA4
#define VK_RMENU 0xA5
#define VK_NUMLOCK 0x90
#define VK_SCROLL 0x91
#define VK_PAUSE 0x13
#define VK_CANCEL 0x03
//#define KBDEXT (USHORT)0x0100
const ULONG aulControlCvt_VK[] = {
MAKELONG(VK_NUMLOCK, VK_PAUSE | KBDEXT),
MAKELONG(VK_SCROLL, VK_CANCEL),
MAKELONG(0,0)
};
/***************************************************************************\
* How some Virtual Key values change when an ALT key is held down.
* The SHIFT and ALT keys both alter VK values the same way!!
\***************************************************************************/
#define aulAltCvt_VK aulShiftCvt_VK
/***************************************************************************\
* This table list keys that may affect Virtual Key values when held down.
*
* See kbd.h for a full description.
*
* 101/102key keyboard (type 4):
* Virtual Key values vary only if CTRL is held down.
* 84-86 key keyboards (type 3):
* Virtual Key values vary if one of SHIFT, CTRL or ALT is held down.
\***************************************************************************/
#define VK_SHIFT 0x10
#define VK_CONTROL 0x11
#define VK_MENU 0x12
//#define KBDSHIFT 1
//#define KBDCTRL 2
//#define KBDALT 4
const VK_TO_BIT aVkToBits_VK[] = {
{ VK_SHIFT, KBDSHIFT }, // 0x01
{ VK_CONTROL, KBDCTRL }, // 0x02
{ VK_MENU, KBDALT }, // 0x04
{ 0, 0 }
};
/***************************************************************************\
* Tables defining how some Virtual Key values are modified when other keys
* are held down.
* Translates key combinations into indices for gapulCvt_VK_101[] or for
* gapulCvt_VK_84[] or for
*
* See kbd.h for a full description.
*
\***************************************************************************/
//#define SHFT_INVALID 0x0F
const MODIFIERS Modifiers_VK = {
(PVK_TO_BIT)&aVkToBits_VK[0],
4, // Maximum modifier bitmask/index
{
SHFT_INVALID, // no keys held down (no VKs are modified)
0, // SHIFT held down 84-86 key kbd
1, // CTRL held down 101/102 key kbd
SHFT_INVALID, // CTRL-SHIFT held down (no VKs are modified)
2 // ALT held down 84-86 key kbd
}
};
/***************************************************************************\
* A tables of pointers indexed by the number obtained from Modify_VK.
* If a pointer is non-NULL then the table it points to is searched for
* Virtual Key that should have their values changed.
* There are two versions: one for 84-86 key kbds, one for 101/102 key kbds.
* gapulCvt_VK is initialized with the default (101/102 key kbd).
\***************************************************************************/
const ULONG *const gapulCvt_VK_101[] = {
NULL, // No VKs are changed by SHIFT being held down
aulControlCvt_VK, // Some VKs are changed by CTRL being held down
NULL // No VKs are changed by ALT being held down
};
const ULONG *const gapulCvt_VK_84[] = {
aulShiftCvt_VK, // Some VKs are changed by SHIFT being held down
aulControlCvt_VK, // Some VKs are changed by CTRL being held down
aulAltCvt_VK // Some VKs are changed by ALT being held down
};
/*
* Determine the state of all the Modifier Keys (a Modifier Key
* is any key that may modify values produced by other keys: these are
* commonly SHIFT, CTRL and/or ALT)
* Build a bit-mask (wModBits) to encode which modifier keys are depressed.
*/
#define KEY_BYTE(pb, vk) pb[((BYTE)(vk)) >> 2]
#define KEY_DOWN_BIT(vk) (1 << ((((BYTE)(vk)) & 3) << 1))
#define KEY_TOGGLE_BIT(vk) (1 << (((((BYTE)(vk)) & 3) << 1) + 1))
#define TestKeyDownBit(pb, vk) (KEY_BYTE(pb,vk) & KEY_DOWN_BIT(vk))
#define SetKeyDownBit(pb, vk) (KEY_BYTE(pb,vk) |= KEY_DOWN_BIT(vk))
#define ClearKeyDownBit(pb, vk) (KEY_BYTE(pb,vk) &= ~KEY_DOWN_BIT(vk))
#define TestKeyToggleBit(pb, vk) (KEY_BYTE(pb,vk) & KEY_TOGGLE_BIT(vk))
#define SetKeyToggleBit(pb, vk) (KEY_BYTE(pb,vk) |= KEY_TOGGLE_BIT(vk))
#define ClearKeyToggleBit(pb, vk) (KEY_BYTE(pb,vk) &= ~KEY_TOGGLE_BIT(vk))
#define ToggleKeyToggleBit(pb, vk) (KEY_BYTE(pb,vk) ^= KEY_TOGGLE_BIT(vk))
WORD GetModifierBits(
PMODIFIERS pModifiers,
LPBYTE afKeyState)
{
PVK_TO_BIT pVkToBit = pModifiers->pVkToBit;
WORD wModBits = 0;
while (pVkToBit->Vk) {
if (TestKeyDownBit(afKeyState, pVkToBit->Vk)) {
wModBits |= pVkToBit->ModBits;
}
pVkToBit++;
}
return wModBits;
}
/***************************************************************************\
* MapScancode
*
* Converts a scancode (and it's prefix, if any) to a different scancode
* and prefix.
*
* Parameters:
* pbScanCode = address of Scancode byte, the scancode may be changed
* pbPrefix = address of Prefix byte, The prefix may be changed
*
* Return value:
* TRUE - mapping was found, scancode was altered.
* FALSE - no mapping fouind, scancode was not altered.
*
* Note on scancode map table format:
* A table entry DWORD of 0xE0450075 means scancode 0x45, prefix 0xE0
* gets mapped to scancode 0x75, no prefix
*
* History:
* 96-04-18 IanJa Created.
\***************************************************************************/
BOOL
MapScancode(
PSCANCODEMAP gpScancodeMap,
PBYTE pbScanCode,
PBYTE pbPrefix
)
{
DWORD *pdw;
WORD wT = MAKEWORD(*pbScanCode, *pbPrefix);
ASSERT(gpScancodeMap != NULL);
for (pdw = &(gpScancodeMap->dwMap[0]); *pdw; pdw++) {
if (HIWORD(*pdw) == wT) {
wT = LOWORD(*pdw);
*pbScanCode = LOBYTE(wT);
*pbPrefix = HIBYTE(wT);
return TRUE;
}
}
return FALSE;
}
/*
* Given modifier bits, return the modification number.
*/
WORD GetModificationNumber(
PMODIFIERS pModifiers,
WORD wModBits)
{
if (wModBits > pModifiers->wMaxModBits) {
return SHFT_INVALID;
}
return pModifiers->ModNumber[wModBits];
}
/***************************************************************************\
* UpdatePhysKeyState
*
* A helper routine for KeyboardApcProcedure.
* Based on a VK and a make/break flag, this function will update the physical
* keystate table.
*
* History:
* 10-13-91 IanJa Created.
\***************************************************************************/
void UpdatePhysKeyState(
BYTE Vk,
BOOL fBreak,
LPBYTE gafPhysKeyState )
{
if (fBreak) {
ClearKeyDownBit(gafPhysKeyState, Vk);
} else {
/*
* This is a key make. If the key was not already down, update the
* physical toggle bit.
*/
if (!TestKeyDownBit(gafPhysKeyState, Vk)) {
if (TestKeyToggleBit(gafPhysKeyState, Vk)) {
ClearKeyToggleBit(gafPhysKeyState, Vk);
} else {
SetKeyToggleBit(gafPhysKeyState, Vk);
}
}
/*
* This is a make, so turn on the physical key down bit.
*/
SetKeyDownBit(gafPhysKeyState, Vk);
}
}
/*****************************************************************************\
* VKFromVSC
*
* This function is called from KeyEvent() after each call to VSCFromSC. The
* keyboard input data passed in is translated to a virtual key code.
* This translation is dependent upon the currently depressed modifier keys.
*
* For instance, scan codes representing the number pad keys may be
* translated into VK_NUMPAD codes or cursor movement codes depending
* upon the state of NumLock and the modifier keys.
*
* History:
*
\*****************************************************************************/
BYTE WD_VKFromVSC(
PKBDTABLES pKbdTbl,
PKE pke,
BYTE bPrefix,
LPBYTE gafPhysKeyState,
BOOLEAN KeyboardType101 )
{
USHORT usVKey = 0xFF;
PVSC_VK pVscVk = NULL;
static BOOL fVkPause;
PULONG *gapulCvt_VK;
// DBG_UNREFERENCED_PARAMETER(afKeyState);
if (pke->bScanCode == 0xFF) {
/*
* Kbd overrun (kbd hardware and/or keyboard driver) : Beep!
* (some DELL keyboards send 0xFF if keys are hit hard enough,
* presumably due to keybounce)
*/
// xxxMessageBeep(0);
return 0;
}
pke->bScanCode &= 0x7F;
// if (gptiForeground == NULL) {
// RIPMSG0(RIP_VERBOSE, "VKFromVSC: NULL gptiForeground\n");
// pKbdTbl = gpKbdTbl;
// } else {
// if (gptiForeground->spklActive) {
// pKbdTbl = gptiForeground->spklActive->spkf->pKbdTbl;
// } else {
// RIPMSG0(RIP_VERBOSE, "VKFromVSC: NULL spklActive\n");
// pKbdTbl = gpKbdTbl;
// }
// }
if (bPrefix == 0) {
if (pke->bScanCode < pKbdTbl->bMaxVSCtoVK) {
/*
* direct index into non-prefix table
*/
usVKey = pKbdTbl->pusVSCtoVK[pke->bScanCode];
if (usVKey == 0) {
return 0xFF;
}
} else {
/*
* unexpected scancode
*/
// RIPMSG2(RIP_VERBOSE, "unrecognized scancode 0x%x, prefix %x",
// pke->bScanCode, bPrefix);
return 0xFF;
}
} else {
/*
* Scan the E0 or E1 prefix table for a match
*/
if (bPrefix == 0xE0) {
/*
* Ignore the SHIFT keystrokes generated by the hardware
*/
if ((pke->bScanCode == SCANCODE_LSHIFT) ||
(pke->bScanCode == SCANCODE_RSHIFT)) {
return 0;
}
pVscVk = pKbdTbl->pVSCtoVK_E0;
} else if (bPrefix == 0xE1) {
pVscVk = pKbdTbl->pVSCtoVK_E1;
}
while (pVscVk != NULL && pVscVk->Vk) {
if (pVscVk->Vsc == pke->bScanCode) {
usVKey = pVscVk->Vk;
break;
}
pVscVk++;
}
}
/*
* Scancode set 1 returns PAUSE button as E1 1D 45 (E1 Ctrl NumLock)
* so convert E1 Ctrl to VK_PAUSE, and remember to discard the NumLock
*/
if (fVkPause) {
/*
* This is the "45" part of the Pause scancode sequence.
* Discard this key event: it is a false NumLock
*/
fVkPause = FALSE;
return 0;
}
if (usVKey == VK_PAUSE) {
/*
* This is the "E1 1D" part of the Pause scancode sequence.
* Alter the scancode to the value Windows expects for Pause,
* and remember to discard the "45" scancode that will follow
*/
pke->bScanCode = 0x45;
fVkPause = TRUE;
}
/*
* Convert to a different VK if some modifier keys are depressed.
*/
if (usVKey & KBDMULTIVK) {
WORD nMod;
PULONG pul;
nMod = GetModificationNumber(
(MODIFIERS *)&Modifiers_VK,
GetModifierBits((MODIFIERS *)&Modifiers_VK,
gafPhysKeyState));
/*
* Scan gapulCvt_VK[nMod] for matching VK.
*/
if ( KeyboardType101 )
gapulCvt_VK = (PULONG *)gapulCvt_VK_101;
else
gapulCvt_VK = (PULONG *)gapulCvt_VK_84;
if ((nMod != SHFT_INVALID) && ((pul = gapulCvt_VK[nMod]) != NULL)) {
while (*pul != 0) {
if (LOBYTE(*pul) == LOBYTE(usVKey)) {
pke->usFlaggedVk = (USHORT)HIWORD(*pul);
return (BYTE)pke->usFlaggedVk;
}
pul++;
}
}
}
pke->usFlaggedVk = usVKey;
return (BYTE)usVKey;
}
/***************************************************************************\
* KeyboardHotKeyProcedure
*
* return TRUE if the hotkey is detected, false otherwise
*
* HotkeyVk (input)
* - hotkey to look for
* HotkeyModifiers (input)
* - hotkey to look for
* pkei (input)
* - scan code
* gpScancodeMap (input)
* - scan code map from WIN32K
* pKbdTbl (input)
* - keyboard layout from WIN32K
* KeyboardType101 (input)
* - keyboard type from WIN32K
* gafPhysKeyState (input/output)
* - key states
*
\***************************************************************************/
BOOLEAN KeyboardHotKeyProcedure(
BYTE HotkeyVk,
USHORT HotkeyModifiers,
PKEYBOARD_INPUT_DATA pkei,
PVOID gpScancodeMap,
PVOID pKbdTbl,
BOOLEAN KeyboardType101,
PVOID gafPhysKeyState )
{
BYTE Vk;
BYTE bPrefix;
KE ke;
WORD ModBits;
if ( !pKbdTbl || !gafPhysKeyState ) {
return FALSE;
}
if (pkei->Flags & KEY_E0) {
bPrefix = 0xE0;
} else if (pkei->Flags & KEY_E1) {
bPrefix = 0xE1;
} else {
bPrefix = 0;
}
ke.bScanCode = (BYTE)(pkei->MakeCode & 0x7F);
if (gpScancodeMap) {
MapScancode(gpScancodeMap, &ke.bScanCode, &bPrefix);
}
Vk = WD_VKFromVSC(pKbdTbl, &ke, bPrefix, gafPhysKeyState, KeyboardType101);
if ((Vk == 0) || (Vk == VK__none_)) {
return FALSE;
}
if (pkei->Flags & KEY_BREAK) {
ke.usFlaggedVk |= KBDBREAK;
}
// Vk = (BYTE)ke.usFlaggedVk;
UpdatePhysKeyState(Vk, ke.usFlaggedVk & KBDBREAK, gafPhysKeyState);
/*
* Convert Left/Right Ctrl/Shift/Alt key to "unhanded" key.
* ie: if VK_LCONTROL or VK_RCONTROL, convert to VK_CONTROL etc.
*/
if ((Vk >= VK_LSHIFT) && (Vk <= VK_RMENU)) {
Vk = (BYTE)((Vk - VK_LSHIFT) / 2 + VK_SHIFT);
UpdatePhysKeyState(Vk, ke.usFlaggedVk & KBDBREAK, gafPhysKeyState);
}
/*
* Now check if the shadow hotkey has been hit
*/
if ( Vk == HotkeyVk && !(ke.usFlaggedVk & KBDBREAK) ) {
ModBits = GetModifierBits( (MODIFIERS *)&Modifiers_VK, gafPhysKeyState );
if ( ModBits == HotkeyModifiers )
return( TRUE );
}
return( FALSE );
}
/*******************************************************************************
*
* KeyboardSetKeyState
*
* Initialize keyboard state
*
* ENTRY:
* pgafPhysKeyState (input/output)
* - buffer to allocate or clear
*
*
* EXIT:
* STATUS_SUCCESS - no error
*
******************************************************************************/
#define CVKKEYSTATE 256
#define CBKEYSTATE (CVKKEYSTATE >> 2)
NTSTATUS
KeyboardSetKeyState( PTSHARE_WD pWd, PVOID *pgafPhysKeyState )
{
NTSTATUS Status = STATUS_SUCCESS;
if ( *pgafPhysKeyState == NULL ) {
*pgafPhysKeyState = COM_Malloc(CBKEYSTATE);
if ( *pgafPhysKeyState == NULL )
return STATUS_NO_MEMORY;
}
RtlZeroMemory( *pgafPhysKeyState, CBKEYSTATE );
return Status;
}
/*******************************************************************************
*
* KeyboardFixupLayout
*
* Fixup the pointers inside the keyboard layout
*
* ENTRY:
* pLayout (input/output)
* - buffer to fixup
* pOriginal (input)
* - pointer to original layout buffer
* Length (input)
* - length of layout buffer
* pKbdTblOriginal (input)
* - pointer to original KbdTbl table
* ppKbdTbl (output)
* - pointer to location to save ptr to new KbdTbl table
*
*
* EXIT:
* STATUS_SUCCESS - no error
*
******************************************************************************/
#define FIXUP_PTR(p, pBase, pOldBase) ((p) ? (p) = (PVOID) ( (PBYTE)pBase + (ULONG) ( (PBYTE)p - (PBYTE)pOldBase ) ) : 0)
//#define CHECK_PTR( p, Limit) { if ( (PVOID)p > Limit ) { ASSERT(FALSE); return STATUS_BUFFER_TOO_SMALL; } }
#define CHECK_PTR( ptr, Limit) \
{ if ( (PBYTE) (ptr) > (PBYTE) (Limit) ) { \
KdPrint(("Bad Ptr, Line %ld: %p > %p \n", __LINE__, ptr, Limit)); \
/* ASSERT(FALSE); */ \
/* return STATUS_BUFFER_TOO_SMALL; */ } }
NTSTATUS
KeyboardFixupLayout( PVOID pKbdLayout, PVOID pOriginal, ULONG Length,
PVOID pKbdTblOrig, PVOID *ppKbdTbl )
{
NTSTATUS Status = STATUS_SUCCESS;
VK_TO_WCHAR_TABLE *pVkToWcharTable;
VSC_LPWSTR *pKeyName;
LPWSTR *lpDeadKey;
PKBDTABLES pKbdTbl;
PVOID pLimit;
if ( Length < sizeof(KBDTABLES) ) {
Status = STATUS_BUFFER_TOO_SMALL;
goto error;
}
pLimit = (PBYTE)pKbdLayout + Length;
pKbdTbl = pKbdTblOrig;
FIXUP_PTR(pKbdTbl, pKbdLayout, pOriginal);
FIXUP_PTR(pKbdTbl->pCharModifiers, pKbdLayout, pOriginal);
CHECK_PTR(pKbdTbl->pCharModifiers, pLimit);
FIXUP_PTR(pKbdTbl->pCharModifiers->pVkToBit, pKbdLayout, pOriginal);
CHECK_PTR(pKbdTbl->pCharModifiers->pVkToBit, pLimit);
if (FIXUP_PTR(pKbdTbl->pVkToWcharTable, pKbdLayout, pOriginal)) {
CHECK_PTR(pKbdTbl->pVkToWcharTable, pLimit);
for (pVkToWcharTable = pKbdTbl->pVkToWcharTable;
pVkToWcharTable->pVkToWchars != NULL; pVkToWcharTable++) {
FIXUP_PTR(pVkToWcharTable->pVkToWchars, pKbdLayout, pOriginal);
CHECK_PTR(pVkToWcharTable->pVkToWchars, pLimit);
}
}
FIXUP_PTR(pKbdTbl->pDeadKey, pKbdLayout, pOriginal);
CHECK_PTR(pKbdTbl->pDeadKey, pLimit);
if (FIXUP_PTR(pKbdTbl->pKeyNames, pKbdLayout, pOriginal)) {
CHECK_PTR(pKbdTbl->pKeyNames, pLimit);
for (pKeyName = pKbdTbl->pKeyNames; pKeyName->vsc != 0; pKeyName++) {
FIXUP_PTR(pKeyName->pwsz, pKbdLayout, pOriginal);
CHECK_PTR(pKeyName->pwsz, pLimit);
}
}
if (FIXUP_PTR(pKbdTbl->pKeyNamesExt, pKbdLayout, pOriginal)) {
CHECK_PTR(pKbdTbl->pKeyNamesExt, pLimit);
for (pKeyName = pKbdTbl->pKeyNamesExt; pKeyName->vsc != 0; pKeyName++) {
FIXUP_PTR(pKeyName->pwsz, pKbdLayout, pOriginal);
CHECK_PTR(pKeyName->pwsz, pLimit);
}
}
if (FIXUP_PTR(pKbdTbl->pKeyNamesDead, pKbdLayout, pOriginal)) {
CHECK_PTR(pKbdTbl->pKeyNamesDead, pLimit);
for (lpDeadKey = pKbdTbl->pKeyNamesDead; *lpDeadKey != NULL;
lpDeadKey++) {
FIXUP_PTR(*lpDeadKey, pKbdLayout, pOriginal);
CHECK_PTR(*lpDeadKey, pLimit);
}
}
FIXUP_PTR(pKbdTbl->pusVSCtoVK, pKbdLayout, pOriginal);
CHECK_PTR(pKbdTbl->pusVSCtoVK, pLimit);
FIXUP_PTR(pKbdTbl->pVSCtoVK_E0, pKbdLayout, pOriginal);
CHECK_PTR(pKbdTbl->pVSCtoVK_E0, pLimit);
FIXUP_PTR(pKbdTbl->pVSCtoVK_E1, pKbdLayout, pOriginal);
CHECK_PTR(pKbdTbl->pVSCtoVK_E1, pLimit);
*ppKbdTbl = pKbdTbl;
error:
return( Status );
}
#ifdef __cplusplus
}
#endif /* __cplusplus */
| 1.21875 | 1 |
src/lib/corelib/refstring.h | millimoji/ribbon | 0 | 196 | #pragma once
#ifndef _RIBBON_REFSTRING_H_
#define _RIBBON_REFSTRING_H_
namespace Ribbon {
namespace RefStringInternal {
struct StringMemoryImage final
{
std::atomic_uint m_refCount; // 4
uint16_t m_length; // 2
char16_t m_str[1]; // 10(=4), 26(=12), 42(=20)
uint32_t DecrementReference();
uint32_t IncrementReference() { return ++m_refCount; }
StringMemoryImage() = delete;
StringMemoryImage(const StringMemoryImage&) = delete;
StringMemoryImage(StringMemoryImage&&) = delete;
StringMemoryImage& operator = (const StringMemoryImage&) = delete;
};
} // namespace RefStringInternal
class RefString final
{
private:
static char16_t Length0Text[];
RefStringInternal::StringMemoryImage* m_ptr;
public:
RefString() : m_ptr(nullptr) {}
// copy context
RefString(const RefString& src) {
m_ptr = src.m_ptr;
if (m_ptr != nullptr) m_ptr->IncrementReference();
}
RefString& operator = (const RefString& src) {
if (m_ptr != nullptr) m_ptr->DecrementReference();
// do not touch m_ptr content after DecrementReference
m_ptr = src.m_ptr;
if (m_ptr != nullptr) m_ptr->IncrementReference();
return *this;
}
// move context
RefString(RefString&& src) {
m_ptr = src.m_ptr;
src.m_ptr = nullptr;
}
RefString& operator = (RefString&& src) {
if (m_ptr != nullptr) m_ptr->DecrementReference();
// do not touch m_ptr content after DecrementReference
m_ptr = src.m_ptr;
src.m_ptr = nullptr;
return *this;
}
// destructor
~RefString() {
if (m_ptr != nullptr) m_ptr->DecrementReference();
// do not touch m_ptr content after DecrementReference
}
// constructors
RefString(const char16_t* src, size_t length);
RefString(const char16_t* src) :
RefString(src, textlen(src))
{}
RefString(const std::u16string& src) :
RefString(src.c_str(), src.length())
{}
RefString& operator = (const char16_t* src) {
return (*this = RefString(src));
}
RefString(const std::string& src)
: RefString(to_utf16(src))
{}
RefString(const char* src)
: RefString(to_utf16(src))
{}
RefString& operator = (const std::u16string& src) {
return (*this = RefString(src));
}
// Accessor
const std::string u8str() const {
return to_utf8(m_ptr ? m_ptr->m_str : Length0Text);
}
const char16_t* u16ptr() const {
return m_ptr ? m_ptr->m_str : Length0Text;
}
std::u16string u16str() const {
return m_ptr ? std::u16string(m_ptr->m_str, m_ptr->m_length) : std::u16string();
}
size_t length() const {
return m_ptr ? static_cast<size_t>(m_ptr->m_length) : 0;
}
char16_t& operator [] (size_t idx) {
char16_t* ptr = m_ptr ? m_ptr->m_str : Length0Text;
return ptr[idx];
}
const char16_t& operator [] (size_t idx) const {
return u16ptr()[idx];
}
// Compare
int Compare(const RefString& rhs) const {
return (m_ptr == rhs.m_ptr) ? 0 :
(m_ptr == nullptr) ? -1 :
(rhs.m_ptr == nullptr) ? 1 :
textcmp(m_ptr->m_str, rhs.m_ptr->m_str);
}
bool operator < (const RefString& rhs) const {
return Compare(rhs) < 0;
}
bool operator > (const RefString& rhs) const {
return Compare(rhs) > 0;
}
bool operator == (const RefString& rhs) const {
return Compare(rhs) == 0;
}
operator bool () const {
return m_ptr != nullptr;
}
// others
void clear() {
if (m_ptr != nullptr) m_ptr->DecrementReference();
m_ptr = nullptr;
}
// for diagnotics
uint32_t GetReferenceCount() { return m_ptr ? (uint32_t)m_ptr->m_refCount : 0; }
static uint32_t GetActiveInstanceCount();
};
} // Ribbon
#endif // _RIBBON_REFSTRING_H_
| 1.25 | 1 |
source/glbinding/include/glbinding/gl43core/values.h | cpp-pm/glbinding | 632 | 204 |
#pragma once
#include <glbinding/nogl.h>
#include <glbinding/gl/values.h>
namespace gl43core
{
// import values to namespace
using gl::GL_INVALID_INDEX;
using gl::GL_TIMEOUT_IGNORED;
} // namespace gl43core | 0.490234 | 0 |
ComponentKit/Core/ComponentTree/CKScopeTreeNode.h | hanton/componentkit | 1 | 212 | /*
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#import <ComponentKit/CKScopeTreeNodeProtocol.h>
#import "CKTreeNode.h"
extern NSUInteger const kTreeNodeParentBaseKey;
extern NSUInteger const kTreeNodeOwnerBaseKey;
@protocol CKTreeNodeProtocol;
/**
This object is a bridge between CKComponentScope and CKTreeNode.
It represents a node with children in the component tree.
*/
@interface CKScopeTreeNode : CKTreeNode <CKScopeTreeNodeProtocol>
{
@package
std::vector<std::tuple<CKScopeNodeKey, id<CKTreeNodeProtocol>>> _children;
}
@end
| 0.796875 | 1 |
vowpalwabbit/parser/flatbuffer/parse_example_flatbuffer.h | mrucker/vowpal_wabbit | 2 | 220 | // Copyright (c) by respective owners including Yahoo!, Microsoft, and
// individual contributors. All rights reserved. Released under a BSD (revised)
// license as described in the file LICENSE.
#pragma once
#include "../../vw.h"
VW_WARNING_STATE_PUSH
VW_WARNING_DISABLE_BADLY_FORMED_XML
#include "generated/example_generated.h"
VW_WARNING_STATE_POP
namespace VW
{
namespace parsers
{
namespace flatbuffer
{
int flatbuffer_to_examples(vw* all, v_array<example*>& examples);
class parser
{
public:
parser() = default;
const VW::parsers::flatbuffer::ExampleRoot* data();
bool parse_examples(vw* all, v_array<example*>& examples, uint8_t* buffer_pointer = nullptr);
private:
const VW::parsers::flatbuffer::ExampleRoot* _data;
uint8_t* _flatbuffer_pointer;
flatbuffers::uoffset_t _object_size = 0;
bool _active_collection = false;
uint32_t _example_index = 0;
uint32_t _multi_ex_index = 0;
bool _active_multi_ex = false;
const VW::parsers::flatbuffer::MultiExample* _multi_example_object = nullptr;
uint32_t _labeled_action = 0;
uint64_t _c_hash = 0;
bool parse(vw* all, uint8_t* buffer_pointer = nullptr);
void process_collection_item(vw* all, v_array<example*>& examples);
void parse_example(vw* all, example* ae, const Example* eg);
void parse_multi_example(vw* all, example* ae, const MultiExample* eg);
void parse_namespaces(vw* all, example* ae, const Namespace* ns);
void parse_features(vw* all, features& fs, const Feature* feature, const flatbuffers::String* ns);
void parse_flat_label(shared_data* sd, example* ae, const Example* eg);
void parse_simple_label(shared_data* sd, polylabel* l, reduction_features* red_features, const SimpleLabel* label);
void parse_cb_label(polylabel* l, const CBLabel* label);
void parse_ccb_label(polylabel* l, const CCBLabel* label);
void parse_cs_label(polylabel* l, const CS_Label* label);
void parse_cb_eval_label(polylabel* l, const CB_EVAL_Label* label);
void parse_mc_label(shared_data* sd, polylabel* l, const MultiClass* label);
void parse_multi_label(polylabel* l, const MultiLabel* label);
void parse_slates_label(polylabel* l, const Slates_Label* label);
void parse_continuous_action_label(polylabel* l, const ContinuousLabel* label);
};
} // namespace flatbuffer
} // namespace parsers
} // namespace VW | 1.023438 | 1 |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
Use the Edit dataset card button to edit it.
- Downloads last month
- 2,262