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
50066fef6e9cea0e228d026671333b621e437406
442
c
C
nitan/d/huangshan/npc/obj/qin.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
1
2019-03-27T07:25:16.000Z
2019-03-27T07:25:16.000Z
nitan/d/huangshan/npc/obj/qin.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
null
null
null
nitan/d/huangshan/npc/obj/qin.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
null
null
null
// qin.c #include <weapon.h> inherit HAMMER; void create() { set_name("古木琴", ({ "gumu qin", "qin" }) ); set_weight(7000); if( clonep() ) set_default_object(__FILE__); else { set("unit", "把"); set("long", "這是一把外表古色古香,但是內包精鐵的六絃琴。\n"); set("value", 3); set("material", "iron"); } init_hammer(16); setup(); }
22.1
56
0.434389
0a2425f681262e7e4f66bb554e7e539fc4168876
845
h
C
src/server/myserver.h
miguelggaspar/Abaqus-simulator
0de56fafd3ce2952288fad97107880b5dbe67c39
[ "MIT" ]
null
null
null
src/server/myserver.h
miguelggaspar/Abaqus-simulator
0de56fafd3ce2952288fad97107880b5dbe67c39
[ "MIT" ]
null
null
null
src/server/myserver.h
miguelggaspar/Abaqus-simulator
0de56fafd3ce2952288fad97107880b5dbe67c39
[ "MIT" ]
null
null
null
/** * @file myserver.h * @brief * * Detailed description starts here. * * @author Vitor Santos, vitor@ua.pt * * @internal * Created 09-Dez-2014 * Copyright Copyright (c) 2014, Vitor Santos, 2016 * * ===================================================================================== */ #include <arpa/inet.h> #include <netinet/in.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <time.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #ifdef _MAIN_C_ int infinite_loopG=1; const int BUFFSIZE=1024; /*If this is small, enlarge it or use dynamic allocation */ #else extern int infinite_loopG; extern const int BUFFSIZE; #endif typedef struct { int hora, minutos;} tempo; #include "prototypes.h"
20.609756
88
0.6
f717617119022bf74b0720289dfef8d519c52a15
4,636
h
C
include/nuttx/contactless/ioctl.h
baggio63446333/incubator-nuttx
c6ed7dd7606e7e00599f857e6731a99d073c45a4
[ "Apache-2.0" ]
null
null
null
include/nuttx/contactless/ioctl.h
baggio63446333/incubator-nuttx
c6ed7dd7606e7e00599f857e6731a99d073c45a4
[ "Apache-2.0" ]
null
null
null
include/nuttx/contactless/ioctl.h
baggio63446333/incubator-nuttx
c6ed7dd7606e7e00599f857e6731a99d073c45a4
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** * include/contactless/ioctl.h * * Copyright(C) 2016 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <gnutt@nuttx.org> * * 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 NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES(INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __INCLUDE_NUTTX_CONTACTLESS_IOCTL_H #define __INCLUDE_NUTTX_CONTACTLESS_IOCTL_H /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <nuttx/fs/ioctl.h> /**************************************************************************** * Pre-Processor Definitions ****************************************************************************/ /* MFRC522 IOCTL Commands ***************************************************/ #define MFRC522IOC_GET_PICC_UID _CLIOC(0x0001) #define MFRC522IOC_GET_STATE _CLIOC(0x0002) /* PN532 IOCTL Commands *****************************************************/ #define PN532IOC_SET_SAM_CONF _CLIOC(0x0003) #define PN532IOC_READ_PASSIVE _CLIOC(0x0004) #define PN532IOC_SET_RF_CONF _CLIOC(0x0005) #define PN532IOC_SEND_CMD_READ_PASSIVE _CLIOC(0x0006) #define PN532IOC_GET_DATA_READY _CLIOC(0x0007) #define PN532IOC_GET_TAG_ID _CLIOC(0x0008) #define PN532IOC_GET_STATE _CLIOC(0x0009) #define PN532IOC_READ_TAG_DATA _CLIOC(0x000a) #define PN532IOC_WRITE_TAG_DATA _CLIOC(0x000b) /* Contactless common IOCTL Commands ****************************************/ #define CLIOC_READ_MIFARE_DATA _CLIOC(0x000c) #define CLIOC_WRITE_MIFARE_DATA _CLIOC(0x000d) /**************************************************************************** * Public Types ****************************************************************************/ struct picc_uid_s { uint8_t size; /* Number of bytes in the UID. 4, 7 or 10 */ uint8_t uid_data[10]; uint8_t sak; /* The SAK (Select Acknowledge) return by the PICC */ }; /* Coding of Select Acknowledge (SAK) according to: * http://www.nxp.com/documents/application_note/AN10833.pdf */ enum picc_cardid_e { PICC_TYPE_NOT_COMPLETE = 0x04, /* UID not complete */ PICC_TYPE_ISO_14443_4 = 0x20, /* PICC compliant with ISO/IEC 14443-4 */ PICC_TYPE_ISO_18092 = 0x40, /* PICC compliant with ISO/IEC 18092 (NFC) */ PICC_TYPE_MIFARE_MINI = 0x09, PICC_TYPE_MIFARE_1K = 0x08, PICC_TYPE_MIFARE_4K = 0x18, PICC_TYPE_MIFARE_UL = 0x00, PICC_TYPE_MIFARE_PLUS = 0x11, PICC_TYPE_TNP3XXX = 0x01 }; struct mifare_tag_data_s { uint8_t data[16]; uint8_t address; }; /**************************************************************************** * Public Functions Definitions ****************************************************************************/ #ifdef __cplusplus #define EXTERN extern "C" extern "C" { #else #define EXTERN extern #endif #undef EXTERN #ifdef __cplusplus } #endif #endif /* __INCLUDE_NUTTX_CONTACTLESS_IOCTL_H */
37.387097
78
0.589517
dd9a46a4c9732b46806b7824bd81986c7db51cdd
530
h
C
keil/UART.h
Anshuman-UCSB/ECE153B-website
be5573ea6b11581782198e24c2a0d0341095e151
[ "CC0-1.0" ]
null
null
null
keil/UART.h
Anshuman-UCSB/ECE153B-website
be5573ea6b11581782198e24c2a0d0341095e151
[ "CC0-1.0" ]
null
null
null
keil/UART.h
Anshuman-UCSB/ECE153B-website
be5573ea6b11581782198e24c2a0d0341095e151
[ "CC0-1.0" ]
null
null
null
#ifndef __STM32L476R_NUCLEO_UART_H #define __STM32L476R_NUCLEO_UART_H #include "stm32l476xx.h" #define BufferSize 32 void UART1_Init(void); void UART2_Init(void); void UART1_GPIO_Init(void); void UART2_GPIO_Init(void); void Init_USARTx(int x); void USART_Init(USART_TypeDef* USARTx); void USART1_IRQHandler(void); void USART2_IRQHandler(void); void USART_Write(USART_TypeDef * USARTx, uint8_t *buffer, uint32_t nBytes); uint8_t USART_Read(USART_TypeDef * USARTx); void USART_Delay(uint32_t us); #endif
23.043478
76
0.777358
de6896adee4975d9c10c514e6022ed55bd17a904
418
h
C
Engine2_0/GUI/CEGUIWrapper.h
Lemmibl/Lemmi-Engine-2.0
38f6466b7d40d2a2d2528e2ae788622ce5c91f01
[ "MIT" ]
1
2017-01-10T19:37:23.000Z
2017-01-10T19:37:23.000Z
Engine2_0/GUI/CEGUIWrapper.h
Lemmibl/Lemmi-Engine-2.0
38f6466b7d40d2a2d2528e2ae788622ce5c91f01
[ "MIT" ]
null
null
null
Engine2_0/GUI/CEGUIWrapper.h
Lemmibl/Lemmi-Engine-2.0
38f6466b7d40d2a2d2528e2ae788622ce5c91f01
[ "MIT" ]
null
null
null
#pragma once #include <GLFW/glfw3.h> #include <string> //Will handle everything CEGUI. Initialization, lifetime, updating. class CEGUIWrapper { public: CEGUIWrapper(); ~CEGUIWrapper(); //Cleanup void Shutdown(); //Set up all subsystems, initialize renderer, load fonts etc bool Initialize(); //Inject stuff like deltaTime into CEGUI void Update(double deltaTime); //Draw CEGUI elements void Render(); };
18.173913
67
0.736842
ee89385768e2140031d8aed552bc6443410311a0
244
h
C
ToolApp/ToolApp/zh/view/ZhTableView.h
ke112/bookish-fiesta
acdb2d85adf4766169714cc74dc5debf48279b16
[ "MIT" ]
null
null
null
ToolApp/ToolApp/zh/view/ZhTableView.h
ke112/bookish-fiesta
acdb2d85adf4766169714cc74dc5debf48279b16
[ "MIT" ]
null
null
null
ToolApp/ToolApp/zh/view/ZhTableView.h
ke112/bookish-fiesta
acdb2d85adf4766169714cc74dc5debf48279b16
[ "MIT" ]
null
null
null
// // BaseTableView.h // GoodLife_New // // Created by hshs on 2021/1/5. // Copyright © 2021 好生活. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface ZhTableView : UITableView @end NS_ASSUME_NONNULL_END
12.842105
46
0.717213
ee33d58f79ed49d186d2db770f90dcdfdf10b991
970
c
C
ft_bzero.c
joshgelbard/libft
5e73cba84a6519a2b685f789f3cc541368418887
[ "Unlicense" ]
null
null
null
ft_bzero.c
joshgelbard/libft
5e73cba84a6519a2b685f789f3cc541368418887
[ "Unlicense" ]
null
null
null
ft_bzero.c
joshgelbard/libft
5e73cba84a6519a2b685f789f3cc541368418887
[ "Unlicense" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_bzero.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jgelbard <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/02/19 16:23:54 by jgelbard #+# #+# */ /* Updated: 2018/03/26 12:37:14 by jgelbard ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" void ft_bzero(void *s, size_t n) { ft_memset(s, 0, n); }
51.052632
80
0.146392
f6d8ccff97f30d6f0626e46c347829c3630162b0
4,001
c
C
kernel/sqtconf/conf.c
Prajna/mach
9c2e1a8d77f84256568f604f74311f23ccce2d9e
[ "BSD-4-Clause", "BSD-3-Clause" ]
27
2015-03-06T06:47:58.000Z
2021-11-06T02:01:26.000Z
kernel/sqtconf/conf.c
Prajna/mach
9c2e1a8d77f84256568f604f74311f23ccce2d9e
[ "BSD-4-Clause", "BSD-3-Clause" ]
null
null
null
kernel/sqtconf/conf.c
Prajna/mach
9c2e1a8d77f84256568f604f74311f23ccce2d9e
[ "BSD-4-Clause", "BSD-3-Clause" ]
11
2015-08-16T02:07:39.000Z
2020-06-02T17:42:14.000Z
/* * Mach Operating System * Copyright (c) 1993 Carnegie Mellon University * Copyright (c) 1991 Carnegie Mellon University * Copyright (c) 1991 Sequent Computer Systems * All Rights Reserved. * * Permission to use, copy, modify and distribute this software and its * documentation is hereby granted, provided that both the copyright * notice and this permission notice appear in all copies of the * software, derivative works or modified versions, and any portions * thereof, and that both notices appear in supporting documentation. * * CARNEGIE MELLON AND SEQUENT COMPUTER SYSTEMS ALLOW FREE USE OF * THIS SOFTWARE IN ITS "AS IS" CONDITION. CARNEGIE MELLON AND * SEQUENT COMPUTER SYSTEMS DISCLAIM ANY LIABILITY OF ANY KIND FOR * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. * * Carnegie Mellon requests users of this software to return to * * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU * School of Computer Science * Carnegie Mellon University * Pittsburgh PA 15213-3890 * * any improvements or extensions that they make and grant Carnegie Mellon * the rights to redistribute these changes. */ /* * HISTORY * $Log: conf.c,v $ * Revision 2.8 93/05/18 11:12:13 rvb * Revision 2.8 93/05/17 16:33:27 rvb * Type casts, etc to quiet gcc 2.3.3 warnings * [93/05/18 rvb] * * Revision 2.7 93/02/05 08:18:37 danner * Fixed include. * [93/02/04 danner] * * Revision 2.6 92/08/03 18:21:19 jfriedl * Add "zd_devinfo" to "zd" disk driver description record. * [92/08/03 14:34:21 jms] * * Revision 2.5 92/02/23 22:45:11 elf * Added getstat routine for sd and zd drivers. * [92/02/22 19:54:46 af] * * Revision 2.4 91/08/28 11:16:51 jsb * Added entries for new dev_info field. * [91/08/27 17:56:16 jsb] * * Revision 2.3 91/07/31 18:05:01 dbg * Changed copyright. * [91/07/31 dbg] * * Revision 2.2 91/05/08 13:01:48 dbg * Created. * [90/10/04 dbg] * */ /* * Device table for Sequent. */ #include <mach/machine/vm_types.h> #include <device/conf.h> extern vm_offset_t block_io_mmap(); extern int timeopen(),timeclose(); extern vm_offset_t timemmap(); #define timename "time" extern int coopen(),coclose(),coread(),cowrite(); extern int cogetstat(),cosetstat(), coportdeath(); #define coname "co" #include <sd.h> #if NSD > 0 extern int sdopen(), sdread(), sdwrite(), sdgetstat(); #define sdname "sd" #endif #include <zd.h> #if NZD > 0 extern int zdopen(), zdclose(), zdread(), zdwrite(), zdgetstat(), zd_devinfo(); #define zdname "zd" #endif #include <se.h> #if NSE > 0 extern int se_open(), se_output(), se_getstat(), se_setstat(); extern int se_setinput(); #define sename "se" #endif /* * List of devices. Console must be at slot 0. */ struct dev_ops dev_name_list[] = { /*name, open, close, read, write, getstat, setstat, mmap, async_in, reset, port_death, subdev, dev_info */ { coname, coopen, coclose, coread, cowrite, cogetstat, cosetstat, nomap, nodev, nulldev, coportdeath, 0, nodev }, { timename, timeopen, timeclose, nulldev, nulldev, nulldev, nulldev, timemmap, nodev, nulldev, nulldev, 0, nodev }, #if NSD > 0 { sdname, sdopen, nulldev, sdread, sdwrite, sdgetstat, nulldev, block_io_mmap, nulldev, nulldev, nulldev, 8, nodev }, #endif #if NZD > 0 { zdname, zdopen, zdclose, zdread, zdwrite, zdgetstat, nulldev, block_io_mmap, nodev, nulldev, nulldev, 8, zd_devinfo }, #endif #if NSE > 0 { sename, se_open, nulldev, nulldev, se_output, se_getstat, se_setstat, nomap, se_setinput, nulldev, nulldev, 0, nodev }, #endif }; int dev_name_count = sizeof(dev_name_list)/sizeof(dev_name_list[0]); /* * Indirect list. */ struct dev_indirect dev_indirect_list[] = { /* console */ { "console", &dev_name_list[0], 0 } }; int dev_indirect_count = sizeof(dev_indirect_list) / sizeof(dev_indirect_list[0]);
25.980519
79
0.67808
f6e74a4793605590df9e7c09e32d6ff9d02d964e
1,116
h
C
src/stim.h
ephxyscj1996/Stim
1f35e36c33a6dba244318e904c35b63a3d82977a
[ "Apache-2.0" ]
2
2021-07-24T13:56:07.000Z
2021-11-17T11:03:51.000Z
src/stim.h
ephxyscj1996/Stim
1f35e36c33a6dba244318e904c35b63a3d82977a
[ "Apache-2.0" ]
null
null
null
src/stim.h
ephxyscj1996/Stim
1f35e36c33a6dba244318e904c35b63a3d82977a
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2021 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef STIM_H #define STIM_H #include "simulators/frame_simulator.h" #include "simulators/tableau_simulator.h" #include "stabilizers/pauli_string.h" #include "stabilizers/tableau.h" namespace stim { using Tableau = stim_internal::Tableau; using TableauSimulator = stim_internal::TableauSimulator; using FrameSimulator = stim_internal::FrameSimulator; using Circuit = stim_internal::Circuit; using PauliString = stim_internal::PauliString; const auto &GATE_DATA = stim_internal::GATE_DATA; } // namespace stim #endif
32.823529
75
0.768817
9198443d67aee4416f5d6d57374d68326ef66b04
499
h
C
oreon.engine/oreon.engine/engine/math/Vec2f.h
antarezz/Oreon.Engine-OpenGL-Cpp
6a36a3138fe291f114be25ee69a0d5ac96edd2f0
[ "MIT" ]
4
2017-08-27T07:44:05.000Z
2018-09-02T07:27:31.000Z
oreon.engine/oreon.engine/engine/math/Vec2f.h
antarezz/Oreon.Engine-OpenGL-Cpp
6a36a3138fe291f114be25ee69a0d5ac96edd2f0
[ "MIT" ]
null
null
null
oreon.engine/oreon.engine/engine/math/Vec2f.h
antarezz/Oreon.Engine-OpenGL-Cpp
6a36a3138fe291f114be25ee69a0d5ac96edd2f0
[ "MIT" ]
2
2020-02-18T15:44:23.000Z
2020-12-13T19:49:25.000Z
#pragma once #include <math.h> class Vec2f { public: Vec2f(); Vec2f(float x, float y); float length() const; float dot(const Vec2f &r); Vec2f normalize(); Vec2f add(const Vec2f &r); Vec2f add(float r); Vec2f sub(const Vec2f &r); Vec2f sub(float r); Vec2f mul(const Vec2f &r); Vec2f mul(float r); Vec2f div(const Vec2f &r); Vec2f div(float r); float getX() const; float getY() const; void setX(float x); void setY(float y); void toString() const; private: float x; float y; };
16.633333
27
0.667335
f409557d33de80bcb5a51024c6fa9603792e0bc3
71,701
c
C
meh.c
he110world/libmeh
6696363ed79fcd2a8d9bf9a6f88774d0d0861731
[ "MIT" ]
2
2015-03-05T12:46:29.000Z
2019-09-10T04:47:44.000Z
meh.c
he110world/libmeh
6696363ed79fcd2a8d9bf9a6f88774d0d0861731
[ "MIT" ]
null
null
null
meh.c
he110world/libmeh
6696363ed79fcd2a8d9bf9a6f88774d0d0861731
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <string.h> #include <GL/gl.h> #include "math2.h" #include "meh.h" #include "camera.h" #include "cd.h" static struct{ sp_t *sp; sctr_t *sctrlist; int nsctrs; obj_t *objlist; } map; /* engine variables are stored here, and can be accessed by external functions by including the meh.h file. */ static unsigned short meh_touchers[1024]; float meh_wallthickness = 0.2f; /* a bound is invalid if it collides with any sector */ #define BND_TOO_TINY 0.1f static inline int bndok(float bnd[2][3]) { return (bnd[1][0]-bnd[0][0]>BND_TOO_TINY || bnd[1][1]-bnd[0][1]>BND_TOO_TINY || bnd[1][2]-bnd[0][2]>BND_TOO_TINY); } static inline int bndbnd(const float a[2][3], const float b[2][3]) { return (a[0][0]<b[1][0] && a[1][0]>b[0][0] && a[0][1]<b[1][1] && a[1][1]>b[0][1] && a[0][2]<b[1][2] && a[1][2]>b[0][2]); } #if 0 /* tests whether a bound touches a sector */ static int bndsctr(const float bnd[2][3], const sctr_t*sctr) { if(!bndbnd(bnd,sctr->bnd)) return 0; } #endif /* tries to add a new sector to the current map. */ #if 0 int bnd2sctr(float bnd[2][3]) { if(!bndok(bnd)) return 0; int n = rngqry(map.sp, bnd, meh_touchers); for(int i=0;i<n;i++){ sctr_t *sctr = getowner(map.sp, meh_touchers[i]); if(bndsctr(bnd,sctr)) return 0; } sctr_t *sctr = malloc(sizeof(sctr_t)); if(map.sctrlist){ map.sctrlist->prev = sctr; } sctr->next = map.sctrlist; sctr->prev = NULL; map.sctrlist = sctr; /* find portals */ } #endif /* are p and p2 separate? */ static inline int plnsep(plane_t *p, plane_t *p2) { if(dot(p->n,p2->n)<-0.99){ float d = p->d + p2->d; if(d<0 && d>-0.01){ return 0; } } return 1; #if 0 if(fabs(p->n.x-p2->n.x)<0.01 && fabs(p->n.y-p2->n.y)<0.01 && fabs(p->n.z-p2->n.z)<0.01){ float d = p->d + p2->d; if(d<0 && d>-0.01){ return 0; } } return 1; #endif } /* Editing sectors constrained/unconstrained add/move/rotate sectors; constrained/unconstrained move/rotate walls */ /* whether two __coplannar__ polygons intersct */ static int polyintx(phd_t *phd, int pid, phd_t *phd2, int pid2, v3_t intx[]) { poly_t *p,*p2; p = phd->polys + pid; p2 = phd2->polys + pid2; for(int i=0;i<p->nv;i++){ intx[i] = phd->verts[p->v[i]]; } int nv = p->nv; for(int i=0;i<p2->nv;i++){ plane_t pln; v3_t *v,*v2; int i2 = (i+1)%p2->nv; v = phd2->verts + p2->v[i]; v2 = phd2->verts + p2->v[i2]; pln.n = cross(p2->plane.n, sub(*v2,*v)); pln.d = dot(pln.n, *v); nv = splitpoly(intx, nv, &pln); if(!nv) return 0; } } /* portal generation adding/removing brushes may affect portals how to store portals, and efficiently update them? */ static void add2mptllist(metaptl_t *mp, metaptl_t *twin, sctr_t *sctr, int wallid, v3_t *verts, int ccw, int nverts) { mp->prev = NULL; mp->next = sctr->walls[wallid].mptllist; if(mp->next){ mp->next->prev = mp; } sctr->walls[wallid].mptllist = mp; mp->twin = twin; mp->verts = verts; mp->nverts = nverts; mp->sctr = sctr; mp->wallid = wallid; mp->ccw = ccw; } static void addsctr2map(sctr_t *sctr) { sctr->prev = map.sctrlist; if(sctr->prev){ sctr->next = sctr->prev->next; sctr->prev->next = sctr; } else{ map.sctrlist = sctr; sctr->next = NULL; } map.nsctrs++; } static int genmptls(sctr_t *sctr) { phd_t *phd = sctr->phd; float loosebnd[2][3]; for(int a=0;a<3;a++){ loosebnd[0][a] = phd->bnd[0][a]-0.01; loosebnd[1][a] = phd->bnd[1][a]+0.01; } int ntouchers = rngqry(map.sp, loosebnd, meh_touchers); int seppoly[32]; for(int i=0;i<ntouchers;i++){ sctr_t *s=SP_GETOWNER(map.sp,meh_touchers[i]); if(s==sctr) continue; seppoly[i] = phdqry(phd, s->phd); if(seppoly[i]<0) return -1; } /* find metaportals */ v3_t ptlverts[32]; int nmptls=0; for(int t=0;t<ntouchers;t++){ sctr_t *s=SP_GETOWNER(map.sp,meh_touchers[t]); if(s==sctr) continue; if(seppoly[t]>=phd->npolys) continue; int pid = -1; for(int j=seppoly[t];j<phd->npolys;j++){ if(phdabovepln(s->phd, &phd->polys[j].plane)){ pid = j; break; } } assert(pid>=0); plane_t *p = &phd->polys[pid].plane; for(int j=0; j<s->phd->npolys; j++){ plane_t *p2 = &s->phd->polys[j].plane; if(plnsep(p,p2)) continue; int nptlverts = polyintx(phd, pid, s->phd, j, ptlverts); if(nptlverts){ printf("sctr=%x\n"); void *mem = malloc(2*sizeof(metaptl_t) + 32*sizeof(v3_t)); /* mp,mp2 allocated using a single malloc */ metaptl_t *mp = mem; metaptl_t *mp2 = mp+1; v3_t *verts = mp2 + 1; memcpy(verts, ptlverts, nptlverts*sizeof(v3_t)); add2mptllist(mp,mp2,sctr,pid,verts,0,nptlverts); add2mptllist(mp2,mp,s,j,verts,1,nptlverts); nmptls++; break; } } } return nmptls; } int phd2sctr(phd_t *phd) { sctr_t *sctr; int nptls; sctr = malloc(sizeof(sctr_t)); sctr->phd = phd; memset(sctr->walls, 0, phd->npolys*sizeof(wall_t)); nptls = genmptls(sctr); if(nptls<0){ free(sctr); return 1; } printf("hello\n"); /* the phd is valid */ sctr->sp = allocsp(128); sctr->brushlist = NULL; addbnd(map.sp, phd->bnd, 1, sctr, &sctr->spid); flushsp(map.sp); addsctr2map(sctr); for(int j=0;j<phd->nedges;j++){ printf("edge->p[0]=%i, edge->p[1]=%i\n", phd->edges[j].p[0], phd->edges[j].p[1]); } /* generate wall brushes */ sctr->nwalls = phd->npolys; plane_t wallplns[32]; for(int i=0;i<sctr->nwalls;i++){ /* extrude polys inward */ brush_t *b = malloc(sizeof(brush_t)); b->type = BRUSH_TYPE; b->prev = b->next = NULL; b->wallid = i; b->phd = poly2phd(phd, i, meh_wallthickness); sctr->walls[i].brushlist = b; addbnd(sctr->sp, b->phd->bnd, 0, b, &b->spid); } flushsp(sctr->sp); return 0; } int bnd2sctr(float bnd[2][3]) { phd_t *phd = allocphd(); plane_t planes[6]; bnd2planes(bnd,planes); addplns(phd,planes,6); phd2sctr(phd); } /* adding brush, with collision detection */ int addbrush(sctr_t *sctr, plane_t plns[], int np, int cd) { int stuck=0; phd_t *phd = allocphd(); addplns(phd, plns, np); /* is the brush inside the sctr? */ { int a=phdqry(phd, sctr->phd); if(a>=0){ freephd(phd); return 1; } } /* detection collisions. if collide with other stuff, add nothing and return "stuck" */ int n = rngqry(sctr->sp, phd->bnd, meh_touchers); if(cd){ for(int i=0; i<n; i++){ stuff_t *stuff = SP_GETOWNER(sctr->sp, meh_touchers[i]); if(stuff->type != OBJ_TYPE) continue; int a=phdqry(phd, stuff->common.phd); if(a>=0){ stuck=1; break; } } if(stuck){ freephd(phd); return 1; } } else{ for(int i=0; i<n; i++){ stuff_t *stuff = SP_GETOWNER(sctr->sp, meh_touchers[i]); if(stuff->type != OBJ_TYPE) continue; int a=phdqry(phd, stuff->common.phd); if(a>=0){ obj_t *obj = stuff; obj->flag |= OBJ_PHANTOM; } } } /* TODO: clip brush against sctr & portal stuff */ brush_t *b = malloc(sizeof(brush_t)); b->prev = NULL; b->next = sctr->brushlist; if(b->next) { b->next->prev = b;} sctr->brushlist = b; b->type = BRUSH_TYPE; b->phd = phd; b->wallid = -1; addbnd(sctr->sp, b->phd->bnd, 0, b, &b->spid); flushsp(sctr->sp); return 0; } void rmbrush(sctr_t *sctr, brush_t *b) { if(b->prev){ b->prev->next = b->next; } else{ if(b->wallid>=0){ sctr->walls[b->wallid].brushlist = b->next; } else{ sctr->brushlist = b->next; } } if(b->next){ b->next->prev = b->prev; } freephd(b->phd); rmbnd(sctr->sp, b->spid); flushsp(sctr->sp); free(b); } static void rmbrushlist_bat(sctr_t *sctr, brush_t *blist) { brush_t *next; for(brush_t *b=blist; b; b=next){ next = b->next; freephd(b->phd); rmbnd(sctr->sp, b->spid); free(b); } } /* should be used only by rmsctr(): no rmbnd() stuff */ static void rmsctr_rmbrushlist(brush_t *blist) { brush_t *next; for(brush_t *b=blist; b; b=next){ next = b->next; freephd(b->phd); free(b); } } static void rmmptllist(metaptl_t *mlist) { printf("mlist=0x%x\n",mlist); metaptl_t *next; if(mlist && !mlist->prev){ mlist->sctr->walls[mlist->wallid].mptllist = NULL; } for(metaptl_t *m=mlist; m; m=next){ metaptl_t *t = m->twin; next = m->next; if(t->prev){ t->prev->next = t->next; } else{ printf("t->wallid=%i, t->next=%i\n",t->wallid,t->next); t->sctr->walls[t->wallid].mptllist = t->next; } if(t->next){ t->next->prev = t->prev; } if(m->ccw)free(t); else free(m); } } void rmsctr(sctr_t *s) { if(s->prev){ s->prev->next = s->next; } else{ map.sctrlist = s->next; } if(s->next){ s->next->prev = s->prev; } freephd(s->phd); rmbnd(map.sp, s->spid); flushsp(map.sp); freesp(s->sp); for(int i=0;i<s->nwalls;i++){ rmsctr_rmbrushlist(s->walls[i].brushlist); rmmptllist(s->walls[i].mptllist); } rmsctr_rmbrushlist(s->brushlist); free(s); } static void rmallsctrs() { sctr_t *next; for(sctr_t *s=map.sctrlist; s; s=next){ next = s->next; freephd(s->phd); freesp(s->sp); for(int i=0;i<s->nwalls;i++){ rmsctr_rmbrushlist(s->walls[i].brushlist); rmmptllist(s->walls[i].mptllist); } rmsctr_rmbrushlist(s->brushlist); free(s); } } /* set the wall's normal. returnsfalse and keeps the sector unchanged if the sector with the new normal collides with other sectors (static cd) */ int setwalln(sctr_t *s, wall_t *w, const v3_t *n) { } void poly2bnd(phd_t *phd, int pid, float bnd[2][3]) { bnd[0][0]=bnd[0][1]=bnd[0][2]=1.0e20f; bnd[1][0]=bnd[1][1]=bnd[1][2]=1.0e-20f; poly_t *p=phd->polys+pid; for(int i=0; i<p->nv; i++){ v3_t *v = phd->verts + p->v[i]; if(v->x<bnd[0][0]) bnd[0][0]=v->x; else if(v->x>bnd[1][0]) bnd[1][0]=v->x; if(v->y<bnd[0][1]) bnd[0][1]=v->y; else if(v->y>bnd[1][1]) bnd[1][1]=v->y; if(v->z<bnd[0][2]) bnd[0][2]=v->z; else if(v->z>bnd[1][2]) bnd[1][2]=v->z; } } /* 1. find affected brushes 2. extrude them to infinite 3. clip them against borders of the wall */ int rotwall2d(sctr_t *sctr, int wallid, float deg) { } int xlatwall2d(sctr_t *sctr, int wallid, v3_t xlat) { } v3_t polycntr(phd_t *phd, int pid) { v3_t cntr = {0,0,0}; poly_t *poly = phd->polys + pid; for(int i=0; i<poly->nv; i++){ cntr = add(cntr, phd->verts[poly->v[i]]); } return scale(cntr, 1.0f/poly->nv); } #define SAME_VEC(v,v2) (dot((v),(v2))>0.99) #define Y_VEC(p) (fabs((p)->y>0.999)) #define PLN_XLAT 1 #define PLN_ROT 2 int getplntransf(phd_t *oldphd, phd_t *newphd, int pid, v3_t rightvec[2], v3_t *xlat, float rot[3][3]) { int transf=0; v3_t oldcenter={0,0,0}, newcenter={0,0,0}; plane_t *oldpln, *newpln; oldpln = &oldphd->polys[pid].plane; newpln = &newphd->polys[pid].plane; /* extract the transformation of the plane */ /* 1. translation */ if(SAME_PLN(oldpln, newpln)){ return 0; } else{ newcenter = polycntr(newphd, pid); oldcenter = polycntr(oldphd, pid); *xlat = sub(newcenter, oldcenter); if(dot(*xlat, *xlat)>0.0001){transf |= PLN_XLAT; }; } /* 2. rotation */ if(!SAME_VEC(oldpln->n, newpln->n)){ v3_t y={0,1,0}; v3_t right[2], up[2], depth[2]; v3_t x; transf |= PLN_ROT; depth[0] = oldpln->n; depth[1] = newpln->n; x = Y_VEC(depth) ? rightvec[depth[0].y>0] : normalize(cross(depth[0],y)); up[0] = cross(x, depth[0]); right[0] = cross(depth[0], up[0]); x = Y_VEC(depth+1) ? rightvec[depth[1].y>0] = right[0] : normalize(cross(depth[1], y)); up[1] = cross(x, depth[1]); right[1] = cross(depth[1], up[1]); if(Y_VEC(depth)){ float proj[2]; proj[0] = dot(right[0], right[1]); proj[1] = dot(up[0], right[1]); if(fabs(proj[1]) > fabs(proj[0])){ /* swap right and up vectors */ if(proj[0]<0){ up[0] = scale(right[0], -1.0f); } } else{ if(proj[1]<0){ up[0] = scale(up[0], -1.0f);} } right[0] = cross(depth[0], up[0]); } /* rot = R_new * R_old^-1 = R_new * R_old^T */ rot[0][0] = right[1].x*right[0].x + up[1].x*up[0].x + depth[1].x*depth[0].x; rot[0][1] = right[1].x*right[0].y + up[1].x*up[0].y + depth[1].x*depth[0].y; rot[0][2] = right[1].x*right[0].z + up[1].x*up[0].z + depth[1].x*depth[0].z; rot[1][0] = right[1].y*right[0].x + up[1].y*up[0].x + depth[1].y*depth[0].x; rot[1][1] = right[1].y*right[0].y + up[1].y*up[0].y + depth[1].y*depth[0].y; rot[1][2] = right[1].y*right[0].z + up[1].y*up[0].z + depth[1].y*depth[0].z; rot[2][0] = right[1].z*right[0].x + up[1].z*up[0].x + depth[1].z*depth[0].x; rot[2][1] = right[1].z*right[0].y + up[1].z*up[0].y + depth[1].z*depth[0].y; rot[2][2] = right[1].z*right[0].z + up[1].z*up[0].z + depth[1].z*depth[0].z; *xlat = sub(newcenter, matv3(rot, oldcenter)); } return transf; } static phd_t *replacepln(phd_t *phd, plane_t *oldpln, int pid) { phd_t *rphd; plane_t *newpln = &phd->polys[pid].plane; if(SAME_PLN(oldpln, newpln)) return NULL; /* reconstruct the old sector */ plane_t plns[32]; for(int i=0; i<phd->npolys; i++){ plns[i] = phd->polys[i].plane; } plns[pid] = *oldpln; rphd = allocphd(); addplns(rphd, plns, phd->npolys); return rphd; } static int poly2borderplns(phd_t *phd, int pid, plane_t borderplns[]) { poly_t *poly = phd->polys + pid; for(int i=0; i<poly->nv; i++){ edge_t *e = phd->edges + poly->e[i]; borderplns[i] = phd->polys[e->p[e->p[0]==pid]].plane; } return poly->nv; } static void mvborderplns_updbrush(sctr_t *sctr, brush_t *b, int intx) { if(intx == PHD_ABOVE_PLN){ b->type = NULL_BRUSH_TYPE; rmbnd(sctr->sp, b->spid); } else{ if(b->type == NULL_BRUSH_TYPE){ b->type = BRUSH_TYPE; addbnd(sctr->sp, b->phd->bnd, 0, b, &b->spid); } else{ updbnd(sctr->sp, b->spid, b->phd->bnd); } } } /* don't expect this function to run in real-time when the sctr is very complex */ /* can be used only when no walls have been added/removed */ int updsctr(sctr_t *sctr, phd_t *oldsctrphd, int wallid) { plane_t *oldpln = &oldsctrphd->polys[wallid].plane; plane_t *newpln = &sctr->phd->polys[wallid].plane; /* for each brush in the neighbouring walls: 1. find & remove the old border pln 2. clipped by the new border pln */ /* first we'd find which walls are going to be discarded/clipped/kept untouched */ char above[64]; memset(above,0,oldsctrphd->nverts); for(int i=0; i<oldsctrphd->nverts; i++){ above[i] = dot(oldsctrphd->verts[i], newpln->n) > newpln->d; } for(int i=0; i<oldsctrphd->npolys; i++){ if(i==wallid) continue; poly_t *wallpoly = oldsctrphd->polys + i; int nf=0; for(int j=0; j<wallpoly->nv; j++){ nf += above[wallpoly->v[j]];} if(nf>0 && nf<wallpoly->nv){ /* clip */ for(brush_t *b=sctr->walls[i].brushlist; b; b=b->next){ int intx = mvborderpln(b->phd, oldpln, newpln); mvborderplns_updbrush(sctr, b, intx); } } else if(nf == wallpoly->nv){/* the wall is totally behind some other walls, hence should be discarded */ rmbrushlist_bat(sctr, sctr->walls[i].brushlist); } /* else: no clipping is needed */ } /* extrude the wall's brushes */ if(sctr->phd->polys[wallid].nv < 3){ rmbrushlist_bat(sctr, sctr->walls[wallid].brushlist); } else{ if(!sctr->walls[wallid].brushlist){ brush_t *b = malloc(sizeof(brush_t)); b->type = BRUSH_TYPE; b->phd = poly2phd(sctr->phd, wallid, meh_wallthickness); b->wallid = wallid; addbnd(sctr->sp, b->phd->bnd, 0, b, &b->spid); } else{ /* for each brush in the moved wall: 1. find & remove old border plns 2. translate/rotate 3. clipped by new border plns */ plane_t borderplns[16], newborderplns[16]; int nb,nnb; nb = poly2borderplns(oldsctrphd, wallid, borderplns); nnb = poly2borderplns(sctr->phd, wallid, newborderplns); v3_t xlat; float rotmat[3][3]; int transf; transf = getplntransf(oldsctrphd, sctr->phd, wallid, sctr->rightvec, &xlat, rotmat); void *rot = (transf & PLN_ROT) ? rotmat : NULL; for(brush_t *b=sctr->walls[wallid].brushlist; b; b=b->next){ int intx=mvborderplns_n_phd(b->phd, rot, xlat, borderplns, newborderplns, nb, nnb); mvborderplns_updbrush(sctr, b, intx); } } } /* clean up */ flushsp(sctr->sp); } int updsctr_lock(sctr_t *sctr, phd_t *oldsctrphd, float rot[3][3], v3_t xlat, int lockids[], int nlocks) { char locked[32]; memset(locked, 0, sctr->phd->npolys); for(int i=0; i<nlocks; i++){ locked[i]=1;} for(int i=0; i<sctr->phd->npolys; i++){ if(locked[i]){ v3_t oldcntr, newcntr; plane_t borderplns[16], newborderplns[16]; int nb,nnb; oldcntr = polycntr(oldsctrphd, i); newcntr = polycntr(sctr->phd, i); nb = poly2borderplns(oldsctrphd, i, borderplns); nnb = poly2borderplns(sctr->phd, i, newborderplns); /* the new phd is already transformed */ for(brush_t *b=sctr->walls[i].brushlist; b; b=b->next){ int intx = mvborderplns_n_phd(sctr->phd, NULL, sub(newcntr, oldcntr), borderplns, newborderplns, nb, nnb); mvborderplns_updbrush(sctr, b, intx); } } else{ poly_t *oldpoly, *newpoly; plane_t borderplns[16], newborderplns[16]; int nb=0,nnb=0; oldpoly = oldsctrphd->polys + i; newpoly = sctr->phd->polys + i; for(int j=0; j<oldpoly->nv; j++){ edge_t *e = oldsctrphd->edges + oldpoly->e[j]; int adj = e->p[e->p[0]==i]; if(locked[adj]){ borderplns[nb++] = oldsctrphd->polys[adj].plane; } } for(int j=0; j<newpoly->nv; j++){ edge_t *e = sctr->phd->edges + newpoly->e[j]; int adj = e->p[e->p[0]==i]; if(locked[adj]){ newborderplns[nnb++] = sctr->phd->polys[adj].plane; } } for(brush_t *b=sctr->walls[i].brushlist; b; b=b->next){ int intx = mvborderplns_n_phd(sctr->phd, rot, xlat,borderplns, newborderplns, nb, nnb); mvborderplns_updbrush(sctr, b, intx); } } } flushsp(sctr->sp); } int addwalls(sctr_t *sctr, plane_t wallplns[], int nwalls) { int np = 0; plane_t plns[32]; int oldnp = sctr->phd->npolys; /* check whether these added walls already exist */ for(int i=0; i<sctr->nwalls; i++){ for(int j=0; j<nwalls; j++){ if(!SAME_PLN(&sctr->phd->polys[i].plane, wallplns+j)){ plns[np++] = wallplns[j]; } } } if(!np) return 0; addplns(sctr->phd, plns, np); for(int i=0; i<sctr->nwalls; i++){ if(sctr->phd->polys[i].nv<3){ sctr->phd->polys[i].nv = 0; rmbrushlist_bat(sctr, sctr->walls[i].brushlist); } } sctr->nwalls = sctr->phd->npolys; for(int i=0; i<oldnp; i++){ poly_t *poly = sctr->phd->polys + i; plane_t newplns[32]; int newnp=0; int nf=0; for(int j=0; j<poly->nv; j++){ edge_t *e = sctr->phd->edges + poly->e[j]; int adj = e->p[e->p[0]==i]; if(adj>=oldnp){ newplns[newnp++] = sctr->phd->polys[adj].plane; } } for(brush_t *b=sctr->walls[i].brushlist; b; b=b->next){ int intx = addborderplns(b->phd, newplns, newnp); mvborderplns_updbrush(sctr, b, intx); } } for(int i=oldnp; i<oldnp+np; i++){ brush_t *b = malloc(sizeof(brush_t)); b->type = BRUSH_TYPE; b->prev = b->next = NULL; b->wallid = i; b->phd = poly2phd(sctr->phd, i, meh_wallthickness); sctr->walls[i].brushlist = b; addbnd(sctr->sp, b->phd->bnd, 0, b, &b->spid); } flushsp(sctr->sp); } int rmdeadwalls(sctr_t *sctr) { } /* 1. xlat sctr (only xlat) 2. rot sctr (only rot) 3. xlat walls ((1)xlat + change border plns -- xlat wall; (2)only change border plns -- locked walls; (3)change nothing at all -- locked walls) 4. rot walls ((1)rot + change border plns; (2)only change border plns; (3)change nothing at all) 5. xlat sctr while some walls are locked ((1)xlat + change border plns -- xlat walls; (2)only change border plns -- locked walls; (3)only xlat -- xlat walls) 6. rot sctr while some walls are locked ((1)xlat + change border plns; (2)only change border plns; (3)only rot) 3 == xlat walls relative to sctr (lock sctr (==some walls), xlat walls) == lock some walls, xlat other walls 5 == xlat sctr relative to walls (xlat sctr (==some walls), lock others)== lock some walls, xlat other walls 4 == rot walls relative to sctr (lock walls, xlat sctr (==some walls)) == lock some walls, rot other walls 6 == rot sctr relative to walls ========================================= lock some walls, rot other walls ==> xlat/rot some walls 7. add new walls ((1)only change border plns (2)change nothing) 8. remove walls ((1)only change border plns (2)change nothing) 9. split sctr ((1)only change border plns (2)change nothing) 10. xlat wall 2d ((1)only change border plns (2)change nothing) 11. rot wall 2d ((1)only change border plns (2)change nothing) all operations above use ccd to avoid penetration */ static int updwall(sctr_t *sctr, phd_t *oldphd, int wallid) { } /* removing a wall == move it far away, instead of really deleting it adding a wall == really add it but after the updating, those quite far away walls (not only those "deleted" walls, but also walls which will unlikely be useful again) will be actually deleted, and wallid of the affected brushes are updated */ int xlatwall_cd() { } int xlatwall_rearrange() { } int xlatwall(sctr_t *sctr, int wallid, v3_t x, v3_t *xdone) { } void csgsub() { } static void updmptls(sctr_t *sctr) { /* remove all old metaptls */ for(int i=0;i<sctr->nwalls;i++){ wall_t *w = sctr->walls+i; rmmptllist(w->mptllist); /* w->mptllist = NULL; */ } genmptls(sctr); } static inline int bndcol(float b[2][3], float b2[2][3]) { } #define BNDINTX(b,b2) ((b)[0][0]<=(b2)[1][0] && (b)[1][0]>=(b2)[0][0] && \ (b)[0][1]<=(b2)[1][1] && (b)[1][1]>=(b2)[0][1] && \ (b)[0][2]<=(b2)[1][2] && (b)[1][2]>=(b2)[0][2]) static float findtoi(phd_t *phd, void (*phdfunc)(phd_t *phd, void *data), void (*step)(void *data, float dt), void *data, phd_t *touchers[], int n, float len, float threshold) { float dt=1.0f; int col; float t = 0.0f; float validt = 0.0f; /* v3_t d=dx; */ float dlen=len; float curlen=0; float validlen=0; float invalidlen=1; v3_t validx={0,0,0}; int iii=0; do{ iii++; /* xlatphdpln(phd, wallid, d); */ phdfunc(phd, data); t+=dt; /* x = add(x,d); */ curlen += dlen; col = 0; for(int i=0;i<n;i++){ if(BNDINTX(phd->bnd, touchers[i]->bnd)){ printf("jj\n"); col=1; break; } int a=phdqry(phd, touchers[i]); if(a<0){ printf("kk\n"); col=1; break; } } if(col){ dt = -.5*fabs(dt); if(curlen<invalidlen) invalidlen = curlen; } else{ if(iii==1) break; /* move from start to the end, without any collision */ dt = .5*fabs(dt); if(curlen>validlen) validlen = curlen; /* validx=x; */ validt = t; } /* d = scale(dx,dt); */ step(data, dt); dlen = dt*len; }while(invalidlen-validlen>threshold); printf("invalid=%f, valid=%f, threshold=%f, t=%f\n",invalidlen,validlen,threshold,t); return validt; } static struct xlatphdpln_data_s{ int wallid; v3_t d; v3_t dx; }; static void xlatphdpln_wrap(phd_t *phd, struct xlatphdpln_data_s *data) { xlatphdpln(phd, data->wallid, data->d); } static void xlatphdpln_step(struct xlatphdpln_data_s *data, float dt) { data->d = scale(data->dx, dt); } static struct xlatphd_data_s{ v3_t d; v3_t dx; }; static void xlatphd_wrap(phd_t *phd, struct xlatphd_data_s *data) { xlatphd(phd, data->d); } static void xlatphd_step(struct xlatphd_data_s *data, float dt) { data->d = scale(data->dx, dt); } static void rotphd_wrap(phd_t *phd, rot_t *r) { rotphd(phd, r); } static void rotphd_step(rot_t *r, float dt) { r->deg *= dt; } /* deferred */ int xlatwall_def(sctr_t *sctr, int wallid, v3_t dx, v3_t *xdone) { /* adjust the offset vector */ int block=0; v3_t x={0,0,0}; wall_t *w = sctr->walls + wallid; float proj = dot(dx, sctr->phd->polys[wallid].plane.n); dx = scale(dx, proj); if(fabs(proj)<0.01){ *xdone = x; return 1; } else if(proj>0){ if(w->mptllist){ *xdone = x; return 1; } } else{ xlatphdpln(sctr->phd, wallid, dx); updbnd(map.sp, sctr->spid, sctr->phd->bnd); updmptls(sctr); *xdone = dx; return 0; } float len=length(dx); float bnd4d[2][3]; int n; xlatbnd4d(bnd4d, sctr->phd->bnd, &dx); n = bndqry4(map.sp, sctr->spid, bnd4d, meh_touchers); if(!n){ xlatphdpln(sctr->phd, wallid, dx); updbnd(map.sp, sctr->spid, sctr->phd->bnd); updmptls(sctr); *xdone = dx; return 0; /* n=0 mean now there's no contacting sctrs, and there won't be any after the tanslation, either. */ } phd_t *touchers[64]; for(int i=0; i<n; i++){ touchers[i] = ((sctr_t *)SP_GETOWNER(map.sp, meh_touchers[i]))->phd; } struct xlatphdpln_data_s data = {wallid, dx, dx}; phd_t *phd = dupphd(sctr->phd); float t = findtoi(phd, xlatphdpln_wrap, xlatphdpln_step, &data, touchers, n, length(dx), 0.01f); v3_t validx = scale(dx,t); xlatphdpln(sctr->phd, wallid, validx); updbnd(map.sp, sctr->spid, sctr->phd->bnd); updmptls(sctr); *xdone = validx; freephd(phd); return 0; } /* deferred */ int xlatsctr_def(sctr_t *sctr, v3_t dx, v3_t *xdone) { /* adjust the offset vector */ int block=0; v3_t x={0,0,0}; for(int i=0;i<sctr->nwalls;i++){ wall_t *w = sctr->walls + i; if(!w->mptllist){ continue; } plane_t *pln = &sctr->phd->polys[i].plane; if(dot(dx, pln->n)>0){ if(block++){ *xdone = x; return 1; } v3_t v = normalize(cross(pln->n, cross(dx, pln->n))); dx = scale(v, dot(dx,v)); } } float len=length(dx); if(len<0.01){ *xdone=x; return 1; } float bnd4d[2][3]; int n; xlatbnd4d(bnd4d, sctr->phd->bnd, &dx); n = bndqry4(map.sp, sctr->spid, bnd4d, meh_touchers); if(!n){ xlatphd(sctr->phd, dx); updbnd(map.sp, sctr->spid, sctr->phd->bnd); updmptls(sctr); *xdone = dx; return 0; /* n=0 mean now there's no contacting sctrs, and there won't be any after the tanslation, either. */ } phd_t *touchers[64]; for(int i=0; i<n; i++){ touchers[i] = ((sctr_t *)SP_GETOWNER(map.sp, meh_touchers[i]))->phd; } struct xlatphd_data_s data = {dx, dx}; phd_t *phd = dupphd(sctr->phd); float t = findtoi(phd, xlatphd_wrap, xlatphd_step, &data, touchers, n, length(dx), 0.01f); v3_t validx = scale(dx,t); xlatphd(sctr->phd, validx); updbnd(map.sp, sctr->spid, sctr->phd->bnd); updmptls(sctr); *xdone = validx; freephd(phd); return 0; } void xlatsctr_upd(sctr_t *s, v3_t x) { for(int i=0;i<s->nwalls;i++){ wall_t *w = s->walls+i; for(brush_t *b=w->brushlist; b; b=b->next){ phd_t *p = b->phd; for(int j=0; j<p->nverts; j++){ p->verts[j] = add(p->verts[j],x); } } } for(brush_t *b=s->brushlist; b; b=b->next){ phd_t *p = b->phd; for(int j=0; j<p->nverts; j++){ p->verts[j] = add(p->verts[j],x); } } xlatsp(s->sp,x); } int xlatsctr(sctr_t *sctr, v3_t dx) { v3_t xdone; int stuck = xlatsctr_def(sctr,dx,&xdone); if(!stuck) xlatsctr_upd(sctr,xdone); return stuck; } int xlatsctr_locked() { } int rotwall() { } int rotwall_cd() { } int rotwall_rearrange() { } int rotsctr_locked() { } static v3_t bndcntr(float bnd[2][3]) { v3_t c; c.x = (bnd[0][0] + bnd[1][0])*.5f; c.y = (bnd[0][1] + bnd[1][1])*.5f; c.z = (bnd[0][2] + bnd[1][2])*.5f; return c; } static float bndradius(float bnd[2][3]) { v3_t diag; diag.x = (bnd[1][0]-bnd[0][0])*.5f; diag.y = (bnd[1][1]-bnd[0][1])*.5f; diag.z = (bnd[1][2]-bnd[0][2])*.5f; return length(diag); } /* bounding box of a rotating point */ void bnd_of_rotpnt(float bnd[2][3], rot_t *rot, v3_t v) { } void bnd_of_rotphd(float bnd[2][3], rot_t *rot, phd_t *phd) { } #if 0 void sumbnds(float dest[2][3], float a[2][3], float b[2][3]) { enum{A,B}; enum{XMIN,XMAX,YMIN,YMAX,ZMIN,ZMAX}; float *bnd[2]={a,b}; /* [0][0], [0][1], [0][2], [1][0], [1][1], [1][2] */ dest[0][0] = bnd[bnd[A][XMIN] > bnd[B][XMIN]][XMIN]; dest[1][0] = bnd[bnd[A][XMAX] < bnd[B][XMAX]][XMAX]; dest[0][1] = bnd[bnd[A][YMIN] > bnd[B][YMIN]][YMIN]; dest[1][1] = bnd[bnd[A][YMAX] < bnd[B][YMAX]][YMAX]; dest[0][2] = bnd[bnd[A][ZMIN] > bnd[B][ZMIN]][ZMIN]; dest[1][2] = bnd[bnd[A][ZMAX] < bnd[B][ZMAX]][ZMAX]; } #endif void sumbnds(float a[6], float b[6]) { if(a[0]>b[0]) a[0]=b[0]; if(a[1]>b[1]) a[1]=b[1]; if(a[2]>b[2]) a[2]=b[2]; if(a[3]<b[3]) a[3]=b[3]; if(a[4]<b[4]) a[4]=b[4]; if(a[5]<b[5]) a[5]=b[5]; } int rotsctr_def(sctr_t *sctr, rot_t *rot, float *t1) { /* radius of rotation */ v3_t cntr = bndcntr(sctr->phd->bnd); float size = bndradius(sctr->phd->bnd); v3_t rr = sub(cntr, rot->org); rr = sub(rr, scale(rot->axis, dot(rr, rot->axis))); /* adjust the offset vector */ int block=0; float arc = DEG2RAD(rot->deg) * (length(rr) + size); if(arc<0.01f){ *t1 = 1.0f; return 1; } #if 0 float bnd4d[2][3]; int n; n = bndqry4(map.sp, sctr->spid, bnd4d, meh_touchers); if(!n){ xlatphd(sctr->phd, dx); updbnd(map.sp, sctr->spid, sctr->phd->bnd); updmptls(sctr); *t1 = 1.0f; return 0; /* n=0 mean now there's no contacting sctrs, and there won't be any after the tanslation, either. */ } phd_t *touchers[64]; for(int i=0; i<n; i++){ touchers[i] = SP_GETOWNER(map.sp, meh_touchers[i]); } rot_t rot =*rot; phd_t *phd = dupphd(sctr->phd); float t = findtoi(phd, rotphd_wrap, rotphd_step, &rot, touchers, n, arc, 0.01f); xlatphd(sctr->phd, sub(validx,x)); updbnd(map.sp, sctr->spid, sctr->phd->bnd); updmptls(sctr); *xdone = validx; freephd(phd); return 0; #endif } void rotsctr_upd(sctr_t *s, rot_t *rot) { float rotmat[3][3]; rot2mat(rot, rotmat); for(int i=0; i<s->nwalls; i++){ for(brush_t *b=s->walls[i].brushlist; b; b=b->next){ rotphd_bat(b->phd, rotmat, rot->org); updphdbnd(b->phd); updbnd_def(s->sp, b->spid, b->phd->bnd); } } for(brush_t *b=s->brushlist; b; b=b->next){ rotphd_bat(b->phd, rotmat, rot->org); updphdbnd(b->phd); updbnd_def(s->sp, b->spid, b->phd->bnd); } updallbnds(s->sp); } int rotsctr() { } int xlatpnt(pnt_t *p, float *frac) { } /* translate a point without collision detection */ int xlatpnt_nocd(pnt_t *p) { } void unlinkbrush(sctr_t *sctr, brush_t *b) { if(b->prev){ b->prev->next = b->next; } else{ if(b->wallid>=0){ sctr->walls[b->wallid].brushlist = b->next; } else{ sctr->brushlist = b->next; } } if(b->next){ b->next->prev = b->prev; } } void delbrush(sctr_t *sctr, brush_t *b) { } int brush2obj(sctr_t *sctr, brush_t *b, int cd) { int stuck=0; int n=rngqry(sctr->sp, b->phd->bnd, meh_touchers); for(int i=0; i<n; i++){ stuff_t *stuff = SP_GETOWNER(sctr->sp, meh_touchers[i]); if(stuff->type == NULL_BRUSH_TYPE){ int a=phdqry(b->phd, stuff->common.phd); if(a>=0){ if(cd){ return 1; } stuck=1; break; } } /* else: toucher->type == OBJ_TYPE. since obj won't intersect with anything including brush, we omit the test */ } obj_t *obj = malloc(sizeof(obj_t)); obj->type = OBJ_TYPE; obj->spid = b->spid; if(stuck){ obj->flag |= OBJ_PHANTOM; } SP_SETOWNER(sctr->sp, obj->spid, obj); setdbnd(sctr->sp, obj->spid); obj->phd = b->phd; unlinkbrush(sctr, b); free(b); obj->prev = NULL; obj->next = map.objlist; if(obj->next) obj->next->prev = obj; map.objlist = obj; /* TODO: update portals */ updmass(obj); return stuck; } typedef struct{ v3_t intx; float toi; } ccdinfo_t; /* transform objects with continuous collision detection */ int xlatobj(v3_t *xlat, obj_t *obj, sctr_t *sctr, ccdinfo_t *ccdinfo) { } static inline int bbintx(float b[6], float b2[6]) { return (b[0]<b2[3] && b[3]>b2[0] && b[1]<b2[4] && b[4]>b2[1] && b[2]<b2[5] && b[5]>b2[2]); } static inline int pntinbnd(float p[3], float bnd[6]) { return (p[0]>=bnd[0] && p[0]<=bnd[3] && p[1]>=bnd[1] && p[1]<=bnd[4] && p[2]>=bnd[2] && p[2]<=bnd[5]); } static inline void mergebnds(float dst[6], float a[6], float b[6]) { dst[0] = a[0]<b[0] ? a[0] : b[0]; dst[1] = a[1]<b[1] ? a[1] : b[1]; dst[2] = a[2]<b[2] ? a[2] : b[2]; dst[3] = a[3]>b[3] ? a[3] : b[3]; dst[4] = a[4]>b[4] ? a[4] : b[4]; dst[5] = a[5]>b[5] ? a[5] : b[5]; } #define neg3(c,a) {(c)[0]=-(a)[0]; (c)[1]=-(a)[1]; (c)[2]=-(a)[2];} #define add3(c,a,b) {(c)[0]=(a)[0]+(b)[0]; (c)[1]=(a)[1]+(b)[1]; (c)[2]=(a)[2]+(b)[2];} #define sub3(c,a,b) {(c)[0]=(a)[0]-(b)[0]; (c)[1]=(a)[1]-(b)[1]; (c)[2]=(a)[2]-(b)[2];} #define dot3(a,b) ((a)[0]*(b)[0] + (a)[1]*(b)[1] + (a)[2]*(b)[2]) #define cross3(c,a,b) {(c)[0]=((a)[1])*((b)[2]) - ((a)[2])*((b)[1]); \ (c)[1]=((a)[2])*((b)[0]) - ((a)[0])*((b)[2]); \ (c)[2]=((a)[0])*((b)[1]) - ((a)[1])*((b)[0]);} #define scale3(c,a,k) {(c)[0]=(a)[0]*(k); \ (c)[1]=(a)[1]*(k); \ (c)[2]=(a)[2]*(k);} #define mov3(c,a) {(c)[0]=(a)[0]; (c)[1]=(a)[1]; (c)[2]=(a)[2];} #define mad3(c,a,k,b) {(c)[0]=(a)[0]*(k)+(b)[0]; \ (c)[1]=(a)[1]*(k)+(b)[1]; \ (c)[2]=(a)[2]*(k)+(b)[2];} static int xlatvpln(const float x[3], const float v[3], const plane_t *pln, float *tmin, float itx[3]) { float v2[3]; float prjx = dot3(x, (float*)&pln->n); float prjv; float t; if(prjx>-0.00001) return 0; /* ignore backface */ add3(v2,v,x); prjv = dot3(v, (float*)&pln->n); if(prjv<pln->d || prjv+prjx>pln->d) return 0; /* the trace is totally on one side of the pln */ t = (pln->d - prjv) / prjx; if(t>=0 && t<*tmin){ *tmin = t; scale3(itx, x, t); add3(itx, itx, v); return 1; } return 0; } static int xlatee(float x[3], float d1[3], float d2[3], float e1[3], float e2[3], float *tmin, float itx[3]) { float d[3], e[3]; float de[3]; float x_x_e[3]; float de_x_x[3]; float denom; float s,u,v; sub3(d, d2, d1); sub3(e, e2, e1); cross3(x_x_e, x, e); denom = dot3(d, x_x_e); if(fabs(denom) < 0.00001){ return 0; } sub3(de, e1, d1); cross3(de_x_x, de, x); s = dot3(d, de_x_x)/denom; if(s<0 || s>1) return 0; u = dot3(e, de_x_x)/denom; if(u<0 || u>1) return 0; cross3(de_x_x, de, e); /* de_x_x is used to store de_x_e */ v = dot3(d, de_x_x)/denom; if(v>=0 && v<*tmin){ *tmin = v; mad3(itx, e, s, e1); return 1; } return 0; } void testxlatee() { v3_t d1={0,0,0},d2={2,0,0}; v3_t e1={1.5,1,-1},e2={1,2,1}; v3_t x={0,5,0}; v3_t itx; float tmin = 1; int stuck=xlatee(&x,&d1,&d2,&e1,&e2,&tmin,&itx); if(stuck){ printf("itx=(%f %f %f)\n", itx.x, itx.y, itx.z); } glLineWidth(3); glBegin(GL_LINES); glColor3f(0,0,0); glVertex3fv(&d1); glVertex3fv(&d2); glColor3f(1,1,1); glVertex3fv(&e1); glVertex3fv(&e2); glEnd(); glLineWidth(1); glPointSize(3); glColor3f(1,.5,.2); glBegin(GL_POINTS); glVertex3fv((float*)&itx); glEnd(); glPointSize(1); } #define EDGECACHE 1 static struct { v3_t *x0; v3_t xlat; phd_t *phd; v3_t intx; float t; float pbnd[2][3]; float ebnd[2][3]; /* epsilon bnd -- used for contact detection */ ccdinfo_t *ccd; int stuck; } meh_xp; #if EDGECACHE static inline int pntinpoly(v3_t *pnt, phd_t *phd, int pid) { poly_t *poly = phd->polys + pid; for(int i=0; i<poly->nv; i++){ edge_t *e = phd->edges + poly->e[i]; float d=dot(*pnt, e->pln.n); if((pid==e->p[0]) ^ (d>e->pln.d)) return 0; } return 1; } #else static inline int pntinpoly(v3_t *pnt, plane_t *edgeplns, int ne) { for(int i=0; i<ne; i++){ float d=dot(*pnt, edgeplns[i].n); printf("pnt=(%f %f %f)\nd=%f, edgeplns[i].d=%f\n", pnt->x,pnt->y,pnt->z,d, edgeplns[i].d); if(d >= edgeplns[i].d){ return 0; } } return 1; } #endif static void beginxlatphd(v3_t *x, phd_t *phd, ccdinfo_t *ccd) { meh_xp.x0 = x; meh_xp.xlat = *x; meh_xp.phd = phd; meh_xp.t = 1; xlatbnd4d(meh_xp.pbnd, phd->bnd, x); meh_xp.stuck = 0; meh_xp.ccd = ccd; } static int xlatagstphd(phd_t *phd) { /* phd1->v vs. phd2->p phd1->p vs. phd2->v phd1->e vs. phd2->e */ float bnd[2][3]; char v[32]; int nv=0; float negx[3]; float *x = &meh_xp.xlat; int coll=0; neg3(negx, ARRAY(meh_xp.xlat)); xlatbnd4d(bnd, phd->bnd, negx); if(!bbintx(bnd, meh_xp.pbnd)) return 0; /* 1. */ for(int i=0; i<meh_xp.phd->nverts; i++){ if(pntinbnd(meh_xp.phd->verts+i, bnd)) v[nv++] = i; } for(int i=0; i<phd->npolys; i++){ float polybnd[2][3]; poly_t *poly = phd->polys + i; #if EDGECACHE #else plane_t edgeplns[16]; for(int j=0; j<poly->nv; j++){ /* TODO: cache this! */ v3_t *v = phd->verts + poly->v[j]; v3_t *v2 = phd->verts + poly->v[(j+1)%poly->nv]; edgeplns[j].n = cross(poly->plane.n, sub(*v2, *v)); edgeplns[j].d = dot(*v, edgeplns[j].n); } #endif poly2bnd(phd, i, polybnd); xlatbnd4d(polybnd, polybnd, negx); for(int j=0; j<nv; j++){ v3_t *pnt = meh_xp.phd->verts + v[j]; float tmin=meh_xp.t; v3_t intx; int stuck; if(!pntinbnd(pnt, polybnd)) continue; stuck = xlatvpln(x, pnt, &poly->plane, &tmin, &intx); if(stuck){ #if EDGECACHE if(pntinpoly(&intx, phd, i)){ #else if(pntinpoly(&intx, edgeplns, poly->nv)){ #endif meh_xp.t = tmin; meh_xp.intx = intx; coll=1; } } } } /* 2. */ nv = 0; for(int i=0; i<phd->nverts; i++){ if(pntinbnd(phd->verts+i, meh_xp.pbnd)) v[nv++] = i; } for(int i=0; i<meh_xp.phd->npolys; i++){ float polybnd[2][3]; poly_t *poly = meh_xp.phd->polys + i; #if EDGECACHE #else plane_t edgeplns[16]; for(int j=0; j<poly->nv; j++){ /* TODO: cache this! */ v3_t *v = meh_xp.phd->verts + poly->v[j]; v3_t *v2 = meh_xp.phd->verts + poly->v[(j+1)%poly->nv]; edgeplns[j].n = cross(poly->plane.n, sub(*v2, *v)); edgeplns[j].d = dot(*v, edgeplns[j].n); } #endif poly2bnd(meh_xp.phd, i, polybnd); xlatbnd4d(polybnd, polybnd, x); for(int j=0; j<nv; j++){ v3_t *pnt = phd->verts + v[j]; float tmin = meh_xp.t; v3_t intx; int stuck; if(!pntinbnd(pnt, polybnd)) continue; stuck = xlatvpln(negx, pnt, &poly->plane, &tmin, &intx); if(stuck){ intx = add(intx, meh_xp.xlat); #if EDGECACHE if(pntinpoly(&intx, meh_xp.phd, i)){ #else if(pntinpoly(&intx, edgeplns, poly->nv)){ #endif meh_xp.t = tmin; meh_xp.intx = intx; coll=1; } } } } /* 3. */ for(int i=0; i<meh_xp.phd->nedges; i++){ float *d1,*d2,*e1,*e2; int *v; v = meh_xp.phd->edges[i].v; d1 = meh_xp.phd->verts + v[0]; d2 = meh_xp.phd->verts + v[1]; for(int j=0; j<phd->nedges; j++){ v = phd->edges[j].v; e1 = phd->verts + v[0]; e2 = phd->verts + v[1]; float tmin = meh_xp.t; v3_t intx; int stuck = xlatee(x, d1, d2, e1, e2, &tmin, &intx); if(stuck){ /* if(tmin < meh_xp.t){ */ meh_xp.t = tmin; meh_xp.intx = intx; coll=1; /* } */ } } } meh_xp.stuck += coll; return coll; } #define CONTACT_EPSILON 0.01 #define MAX_NCONTACTS 32 static v3_t meh_contacts[MAX_NCONTACTS]; static int meh_ncontacts; static void begincontact(phd_t *phd, v3_t **contacts) { ccdinfo_t ccd; v3_t x = {0,0,0}; beginxlatphd(&x, phd, &ccd); meh_ncontacts = 0; *contacts = meh_contacts; #if 0 for(int i=0; i<3; i++){ meh_xp.pbnd[0][i] -= CONTACT_EPSILON; meh_xp.pbnd[1][i] += CONTACT_EPSILON; } #endif } static int endcontact() { return meh_ncontacts; } static inline int segbndintx(float v[3], float v2[3], float bnd[2][3]) { /* v->v2 */ float d[3]; sub3(d,v2,v); /* x,y,z */ for(int i=0; i<3; i++){ if(v[i]<v2[i]){ if(v[i]>bnd[1][i] || v2[i]<bnd[0][i]) return 0; } else{ if(v[i]<bnd[0][i] || v2[i]<bnd[1][i]) return 0; } } /* */ } static inline int bbintx2(float dest[6], float a[6], float b[6]) { for(int i=0; i<3; i++){ int j=i+3; dest[i] = (a[i]>b[i] ? a[i] : b[i]) - CONTACT_EPSILON; dest[j] = (a[j]<b[j] ? a[j] : b[j]) + CONTACT_EPSILON; if(dest[i]>dest[j]) return 0; } return 1; } static inline int eeintx(phd_t *phd, int eid, phd_t *phd2, int eid2, float intx[3]) { edge_t *e = phd->edges + eid; edge_t *e2 = phd2->edges + eid2; v3_t ev = sub(phd->verts[e->v[1]], phd->verts[e->v[0]]); v3_t ev2 = sub(phd2->verts[e2->v[1]], phd2->verts[e2->v[0]]); v3_t axis = cross(ev, ev2); float a=dot(axis,axis); if(a<0.0001) return 0; axis = scale(axis, 1.0f/sqrt(a)); float d = dot(axis, sub(phd->verts[e->v[0]], phd2->verts[e2->v[0]])); if(fabs(d)>CONTACT_EPSILON) return 0; plane_t pln[2]; pln[0].n = cross(ev, axis); pln[0].d = dot(phd->verts[e->v[0]], pln[0].n); } /* TODO: use GJK/SAT to find contact points */ static int contact(phd_t *phd) { int cont=0; float intxbnd[2][3]; if(!bbintx2(intxbnd, meh_xp.pbnd, phd->bnd)) return 0; for(int i=0; i<meh_xp.phd->nverts; i++){ v3_t *v = meh_xp.phd->verts + i; if(!pntinbnd(v, intxbnd)) continue; for(int j=0; j<phd->npolys; j++){ poly_t *poly = phd->polys + j; float d = dot(*v, poly->plane.n) - poly->plane.d; if(d<-CONTACT_EPSILON || d>CONTACT_EPSILON) continue; if(pntinpoly(v, phd, j)){ meh_contacts[meh_ncontacts++] = *v; cont=1; } } } for(int i=0; i<phd->nverts; i++){ v3_t *v = phd->verts + i; if(!pntinbnd(v, intxbnd)) continue; for(int j=0; j<meh_xp.phd->npolys; j++){ poly_t *poly = meh_xp.phd->polys + j; float d = dot(*v, poly->plane.n) - poly->plane.d; if(d<-CONTACT_EPSILON || d>CONTACT_EPSILON) continue; if(pntinpoly(v, meh_xp.phd, j)){ meh_contacts[meh_ncontacts++] = *v; cont=1; } } } #if 0 /* meh_xp.phd vs. intxbnd */ for(int i=0; i<meh_xp.phd->nedges; i++){ } /* phd vs. intxbnd */ for(int i=0; i<phd->nedges; i++){ } for(int i=0; i<nme; i++){ for(int j=0; j<ne; j++){ } } #endif for(int i=0; i<meh_xp.phd->nedges; i++){ edge_t *me = meh_xp.phd->edges + i; v3_t *mv[2] = {meh_xp.phd->verts+me->v[0], meh_xp.phd->verts+me->v[1]}; for(int j=0; j<phd->nedges; j++){ edge_t *e = phd->edges + j; v3_t *v[2] = {phd->verts+e->v[0], phd->verts+e->v[1]}; float d = dot(me->pln.n, *v[0]); if((d<me->pln.d)^(dot(me->pln.n, *v[1])>me->pln.d)) continue; v3_t ev = sub(*v[1], *v[0]); float denom = dot(me->pln.n, ev); if(denom < 0.0001) continue; float t = (me->pln.d - dot(me->pln.n, *v[0])) / denom; if(t<0.0f || t>1.0f) continue; v3_t mev = sub(*mv[1], *mv[0]); v3_t intx = add(*v[0], scale(ev, t)); float d0 = dot(sub(intx, *mv[0]), mev); float d1; if(d0<0 || (d1=dot(sub(intx, *mv[1]), mev))>0) continue; float k = -d0/d1; v3_t dist = sub(intx, add(*mv[0], scale(mev, k/(k+1)))); if(dot(dist,dist) < CONTACT_EPSILON*.1){ meh_contacts[meh_ncontacts++] = intx; cont=1; } } } meh_xp.stuck += cont; return cont; } #if 0 static int contact(phd_t *phd) { /* phd1->v vs. phd2->p phd1->p vs. phd2->v phd1->e vs. phd2->e */ float bnd[2][3]; char v[32]; int nv=0; float negx[3]; float *x = &meh_xp.xlat; int cont=0; neg3(negx, ARRAY(meh_xp.xlat)); xlatbnd4d(bnd, phd->bnd, negx); if(!bbintx(bnd, meh_xp.pbnd)) return 0; /* 1. */ for(int i=0; i<meh_xp.phd->nverts; i++){ if(pntinbnd(meh_xp.phd->verts+i, bnd)) v[nv++] = i; } for(int i=0; i<phd->npolys; i++){ float polybnd[2][3]; poly_t *poly = phd->polys + i; #if EDGECACHE #else plane_t edgeplns[16]; for(int j=0; j<poly->nv; j++){ /* TODO: cache this! */ v3_t *v = phd->verts + poly->v[j]; v3_t *v2 = phd->verts + poly->v[(j+1)%poly->nv]; edgeplns[j].n = cross(poly->plane.n, sub(*v2, *v)); edgeplns[j].d = dot(*v, edgeplns[j].n); } #endif poly2bnd(phd, i, polybnd); xlatbnd4d(polybnd, polybnd, negx); for(int j=0; j<nv; j++){ v3_t *pnt = meh_xp.phd->verts + v[j]; float tmin=1; v3_t intx; int stuck; if(!pntinbnd(pnt, polybnd)) continue; stuck = xlatvpln(x, pnt, &poly->plane, &tmin, &intx); if(stuck){ #if EDGECACHE if(pntinpoly(&intx, phd, i)){ #else if(pntinpoly(&intx, edgeplns, poly->nv)){ #endif if(meh_ncontacts < MAX_NCONTACTS){ meh_contacts[meh_ncontacts++] = intx; cont=1; } } } } } /* 2. */ nv = 0; for(int i=0; i<phd->nverts; i++){ if(pntinbnd(phd->verts+i, meh_xp.pbnd)) v[nv++] = i; } for(int i=0; i<meh_xp.phd->npolys; i++){ float polybnd[2][3]; poly_t *poly = meh_xp.phd->polys + i; #if EDGECACHE #else plane_t edgeplns[16]; for(int j=0; j<poly->nv; j++){ /* TODO: cache this! */ v3_t *v = meh_xp.phd->verts + poly->v[j]; v3_t *v2 = meh_xp.phd->verts + poly->v[(j+1)%poly->nv]; edgeplns[j].n = cross(poly->plane.n, sub(*v2, *v)); edgeplns[j].d = dot(*v, edgeplns[j].n); } #endif poly2bnd(meh_xp.phd, i, polybnd); xlatbnd4d(polybnd, polybnd, x); for(int j=0; j<nv; j++){ v3_t *pnt = phd->verts + v[j]; float tmin = 1; v3_t intx; int stuck; if(!pntinbnd(pnt, polybnd)) continue; stuck = xlatvpln(negx, pnt, &poly->plane, &tmin, &intx); if(stuck){ intx = add(intx, meh_xp.xlat); #if EDGECACHE if(pntinpoly(&intx, meh_xp.phd, i)){ #else if(pntinpoly(&intx, edgeplns, poly->nv)){ #endif if(meh_ncontacts < MAX_NCONTACTS){ meh_contacts[meh_ncontacts++] = intx; cont=1; } } } } } /* 3. */ for(int i=0; i<meh_xp.phd->nedges; i++){ float *d1,*d2,*e1,*e2; int *v; v = meh_xp.phd->edges[i].v; d1 = meh_xp.phd->verts + v[0]; d2 = meh_xp.phd->verts + v[1]; for(int j=0; j<phd->nedges; j++){ v = phd->edges[j].v; e1 = phd->verts + v[0]; e2 = phd->verts + v[1]; float tmin = meh_xp.t; v3_t intx; int stuck = xlatee(x, d1, d2, e1, e2, &tmin, &intx); if(stuck){ if(meh_ncontacts < MAX_NCONTACTS){ meh_contacts[meh_ncontacts++] = intx; cont=1; } } } } meh_xp.stuck += cont; return cont; } #endif static int endxlatphd() { if(meh_xp.stuck){ /* meh_xp.t *= 0.98; */ /* TODO: change this to relative threshold */ v3_t xlat = scale(meh_xp.xlat, meh_xp.t); float d = length(xlat); meh_xp.t *= (d - CONTACT_EPSILON) / d; if(meh_xp.t < 0) meh_xp.t = 0; *meh_xp.x0 = scale(meh_xp.xlat, meh_xp.t); meh_xp.ccd->intx = meh_xp.intx; meh_xp.ccd->toi = meh_xp.t; return 1; } else{ meh_xp.ccd->toi = meh_xp.t; return 0; } } void dbg_drawphdnormals(phd_t *phd) { #if 0 glBegin(GL_LINES); for(int i=0; i<phd->npolys; i++){ v3_t c = polycntr(phd, i); v3_t c2 = add(c, normalize(phd->polys[i].plane.n)); glVertex3fv(&c); glVertex3fv(&c2); } glEnd(); #endif glColor3f(0,1,0); glBegin(GL_LINES); for(int i=0; i<phd->nedges; i++){ edge_t *e = phd->edges + i; v3_t c = scale(add(phd->verts[e->v[0]], phd->verts[e->v[1]]),.5f); v3_t c2 = add(c, e->pln.n); glVertex3fv(&c); glVertex3fv(&c2); } glEnd(); } void testxlatphd() { extern phd_t *globphds[]; static v3_t xlat = {.03, 0,0}; ccdinfo_t ccd; beginxlatphd(&xlat, globphds[1], &ccd); /* static int s=0; */ static v3_t intx; xlatagstphd(globphds[0]); int stuck = endxlatphd(); /* if(rot.rad) rotphd(globphds[1], &rot); */ #if 1 /* if(!s) */{ if(stuck){ /* s=1; */ /* if(rot.rad<0) rot.rad=0; */ intx = ccd.intx;/* add(meh_rp.rot.org, mattv3(meh_rp.zmat, ccd.intx)); */ /* printf("shit deg=%f, ft=%f, intx=(%f %f %f), rot.org=(%f %f %f)\n", RAD2DEG(meh_rp.rot.rad), meh_rp.ft, intx.x, intx.y, intx.z, rot.org.x, rot.org.y, rot.org.z); */ } } #endif if(ccd.toi){ xlatphd(globphds[1], xlat); } /* if(stuck) xlat.x = .03; */ /* printf("intx=(%f %f %f)\n", intx.x, intx.y, intx.z); */ #if 0 if(stuck){ if(rot.rad>0){ rotphd(globphds[1], &rot); intx = ccd.intx; } } #endif #if 1 glLineWidth(1); glColor3f(1,0,0); drawphd(globphds[0]); glColor3f(0,0,1); drawphd(globphds[1]); glLineWidth(1); glPointSize(2); glColor3f(0,1,1); glBegin(GL_POINTS); glVertex3fv(&intx); glEnd(); glPointSize(1); #endif #if 0 glColor3f(0,1,0); dbg_drawphdnormals(globphds[1]); #endif #if 0 glPointSize(2); glColor3f(1,.5,.5); glBegin(GL_POINTS); glVertex3fv(&ii); glEnd(); #endif #if 0 float color[3] = {.2,.2,1}; drawbox(meh_xp.pbnd, color); #endif #if 0 rot_t rot2; v3_t pnt = {1,0,0}; rot2.deg = 50; rot2.axis = vec(0,0,1); rot2.rad = DEG2RAD(rot2.deg); rot2.org = vec(0,0,0); float mat[3][3]; rot2mat(&rot2, mat); v3_t pnt2 = matv3(mat, pnt); rot2.deg = 210; rot2.rad = DEG2RAD(rot2.deg); rot2mat(&rot2, mat); v3_t pnt3 = matv3(mat, pnt); #endif #if 0 rot_t rot2; v3_t pnt = {1,0,0}; rot2.deg = 100; rot2.axis = vec(0,0,1); rot2.rad = DEG2RAD(rot2.deg); rot2.org = vec(0,0,0); float mat[3][3]; rot2mat(&rot2, mat); v3_t pnt2 = matv3(mat, pnt); #endif #if 0 glLineWidth(5); glColor3f(.6, .3, .9); glBegin(GL_LINE_STRIP); glVertex3fv(&pnt); glVertex3fv(&pnt2); glVertex3fv(&pnt3); glEnd(); glLineWidth(1); #endif } void testcontact() { extern phd_t *globphds[]; static v3_t xlat = {.3, 0,0}; v3_t *contacts; begincontact(globphds[1], &contacts); /* static int s=0; */ static v3_t intx; contact(globphds[0]); int n = endcontact(); printf("KKKKKKKKKKKK n=%i\n", n); glPointSize(5); glColor3f(1,0,0); glBegin(GL_POINTS); for(int i=0; i<n; i++) glVertex3fv(contacts+i); glEnd(); glPointSize(1); } typedef struct{ v3_t o,u,r; } rect3d_t; static void rotpntbnd_rect3d(rot_t *rot) { } static void rotpntbnd(rot_t *rot, v3_t p0, v3_t p1, float bnd[2][3]) { v3_t r,u,r1,proj; float radius; float c1,s1; float frad; /* f(rad) = -/+ cos(rad/2)^2 (f(rad) is increasing)*/ r = sub(p0,rot->org); proj = scale(rot->axis, dot(r,rot->axis)); r = sub(r, proj); radius = length(r); /* u = cross(r,rot->axis); */ u = cross(rot->axis, r); r1 = sub(p1,rot->org); r1 = sub(r1, proj); #if 0 c1 = dot(r1,r); s1 = dot(r1,u); frad = .5f * (1.0f + c1/radius); if(rot->deg<180) frad = -frad; #endif for(int i=0; i<3; i++){ float a = ((float*)&r)[i]; float b = ((float*)&u)[i]; int inc = b>0; int dec = !inc; #if 0 if(a){ float t = b/a; float frads[3]; float fradmax[2]; fradmax[1] = sqrt(a*a + b*b); fradmax[0] = -fradmax[1]; frads[1] = 1.0f / (1.0f + t*t); if(a*b>0){ frads[0] = .5f * (1.0f + sqrt(frads[1])); frads[1] = -frads[1]; frads[2] = frads[0] - 1; } else{ frads[0] = .5f * (1.0f - sqrt(frads[1])); frads[2] = frads[0] + 1; } frads[0] = -frads[0]; frads[2] = -frads[2]; if(frad < frads[0]) bnd[inc][i] = ((float*)&r1)[i]; else bnd[inc][i] = fradmax[inc]; if(frad < frads[1]) bnd[dec][i] = a; else if(frad < frads[2]) bnd[dec][i] = ((float*)&r1)[i]; else bnd[dec][i] = fradmax[dec]; } else{ if(rot->rad<PI/2) bnd[inc][i] = ((float*)&r1)[i]; else bnd[inc][i] = radius; if(rot->rad<PI) bnd[dec][i] = 0; else if(rot->rad<PI*3/2) bnd[dec][i] = ((float*)&r1)[i]; else bnd[dec][i] = radius; } #endif #if 1 float rad; float radmax[2]; if(a){ rad = atanf(b/a); if(rad<0) rad+=PI; radmax[1] = sqrt(a*a+b*b); radmax[0] = -radmax[1]; } else { rad = PI/2; radmax[0] = -radius; radmax[1] = radius; } if(rot->rad<rad){ bnd[inc][i] = ((float*)&r1)[i];} else bnd[inc][i] = radmax[inc]; if(rot->rad<2*rad) bnd[dec][i]=a; else if(rot->rad<rad+PI) bnd[dec][i] = ((float*)&r1)[i]; else bnd[dec][i] = radmax[dec]; /* if(a){ float radmax[2]; radmax[1] = sqrt(a*a+b*b); radmax[0] = -radmax[1]; if(rot->rad<rad){ bnd[inc][i] = ((float*)&r1)[i];} else bnd[inc][i] = radmax[inc]; if(rot->rad<2*rad) bnd[dec][i]=a; else if(rot->rad<rad+PI) bnd[dec][i] = ((float*)&r1)[i]; else bnd[dec][i] = radmax[dec]; } else{ if(rot->rad<PI/2) bnd[inc][i] = ((float*)&r1)[i]; else bnd[inc][i] = radius; if(rot->rad<PI) bnd[dec][i] = 0; else if(rot->rad<PI*3/2) bnd[dec][i] = ((float*)&r1)[i]; else bnd[dec][i] = radius; } */ #endif bnd[0][i] += ((float*)&rot->org)[i] + ((float*)&proj)[i]; bnd[1][i] += ((float*)&rot->org)[i] + ((float*)&proj)[i]; } } #define dot2(a,b) ((a)[0]*(b)[0]+(a)[1]*(b)[1]) #define cross2(a,b) ((a)[0]*(b)[1]-(a)[1]*(b)[0]) #define proj2(a,b) ((a)[0]*(b)[0]+(a)[1]*(b)[1]) #define sub2(c,a,b) {(c)[0]=(a)[0]-(b)[0];(c)[1]=(a)[1]-(b)[1];} /* #define sub3(c,a,b) {(c)[0]=(a)[0]-(b)[0];(c)[1]=(a)[1]-(b)[1];(c)[2]=(a)[2]-(b)[2];} */ #define scale2(c,a,s) {(c)[0]=(s)*((a)[0]); (c)[1]=(s)*((a)[1]);} #define mad2(c,a,k,b) {(c)[0]=(k)*(a)[0]+(b)[0]; (c)[1]=(k)*(a)[1]+(b)[1];} /* c=ka+b (a,b,c are v2, k is scalar) */ static int rotvpln(float v[3], plane_t *p, float *ft, float itx[3]) { float a,b,c,r2; float *n = &p->n; float d; float i0[2],i1[2]; r2 = dot2(v,v); a = dot2(n,n); if(!a) return 0; b = n[2]*v[2] - p->d; c = b*b - n[0]*n[0]*r2; b = n[1] * b; d = b*b - a*c; if(d<0){ if(d<-0.00001) return 0; d = 0; } if(d<0.00001){ if(n[0]){ /* i0[0] = (p->d - n[1]*i0[1] - n[2]*v.z) / n[0]; */ return 0; } else{ float d2; i0[1] = -b/a; d2 = r2 - i0[1]*i0[1]; if(d2<0) return 0; i1[0] = sqrt(d2); i0[0] = -i1[0]; i1[1] = i0[1]; } } else{ float sqrtd = sqrt(d); i0[1] = (-b + sqrtd) / a; i1[1] = (-b - sqrtd) / a; /* if n[0]==0, then a=n[1]*n[1], c=b*b/(n[1]*n[1]) => d = b*b - a*c = b*b - n[1]*n[1]*b*b/(n[1]*n[1]) == 0 so n[0]!=0 */ i0[0] = (p->d - n[1]*i0[1] - n[2]*v[2]) / n[0]; i1[0] = (p->d - n[1]*i1[1] - n[2]*v[2]) / n[0]; } /* find the first intersection */ if(1/* cross2(n,i0)>0 */){ int gt180 = cross2(v, i0)<0; float len = .5f*(dot2(i0,i0)+dot2(v,v)); /* float len = sqrt(dot2(i0,i0)*dot2(v,v)); */ float cosine = dot2(i0,v)/len; float ft2 = gt180 ? -1.0f-cosine: 1.0f+cosine; if(ft2 > *ft){ *ft = ft2; itx[0] = i0[0]; itx[1] = i0[1]; itx[2] = v[2]; return 1; } } /* else */if(1/* cross2(n,i1)>0 */){ /* collide with back face: ignored */ int gt180 = cross2(v, i1)<0; float len = .5f*(dot2(i1,i1)+dot2(v,v)); /* float len = sqrt(dot2(i1,i1)*dot2(v,v)); */ float cosine = dot2(i1,v)/len; float ft2 = gt180 ? -1.0f-cosine : 1.0f+cosine; if(ft2 > *ft){ *ft = ft2; itx[0] = i1[0]; itx[1] = i1[1]; itx[2] = v[2]; return 1; } } return 0; } static int rotee(float d1[3], float d2[3], float e1[3], float e2[3], float *ft, float itx[3]) { float d[3], e[3], v[2], i1[3], i2[3]; float a,b,c,t,t1,t2; float dz2, dd, ee; float b2ac; sub3(d,d2,d1); sub3(e,e2,e1); dz2 = d[2]*d[2]; { float k1,k2,b1,b2; /* f1(t) = k1 t + b1; f2(t) = k2 t + b2 */ k1 = d[0]*e[2]; b1 = d[0]*(e1[2]-d1[2]) + d[2]*d1[0]; k2 = d[1]*e[2]; b2 = d[1]*(e1[2]-d1[2]) + d[2]*d1[1]; a = dot2(e,e)*dz2 - k1*k1 - k2*k2; b = dot2(e,e1)*dz2 - k1*b1 - k2*b2; c = dot2(e1,e1)*dz2 - b1*b1 - b2*b2; } if(fabs(a)<0.00001) return 0; /* intersection is the edge */ b2ac = b*b-a*c; /* calculated by using xmaxima, if d[2]==0, then b*b-a*c=0; */ if(b2ac<0){ if(b2ac<-0.00001) return 0; else b2ac=0; } int intx=0; if(b2ac<0.00001){ /* d[2]==0 */ t = -b/a; if(t>=0 && t<=1){ /* between e1 and e2 */ float r2; float ft2; itx[0] = e[0]*t + e1[0]; itx[1] = e[1]*t + e1[1]; itx[2] = e[2]*t + e1[2]; r2 = dot2(itx,itx); a = dot2(d,d); b = dot2(d,d1); c = dot2(d1,d1)-r2; b2ac = b*b-a*c; if(!b2ac){ float td = -b/a; if(td>=0 && td<=1){ mad2(v,d,td,d1); if(cross2(v,itx)>=0){ /* <PI */ ft2 = 1.0f + dot2(itx,v)/r2; } else{ ft2 = -1.0f - dot2(itx,v)/r2; } if(ft2 > *ft){ *ft = ft2; intx = 1; } } } else{ float sqrtb2ac = sqrt(b2ac); float td[2] = {(-b+sqrtb2ac)/a, (-b-sqrtb2ac)/a}; for(int i=0; i<2; i++){ if(td[i]>=0 && td[i]<=1){ mad2(v,d,td[i],d1); if(cross2(v,itx)>=0){ ft2 = 1.0f + dot2(itx,v)/r2; } else{ ft2 = -1.0f - dot2(itx,v)/r2; } if(ft2 > *ft){ *ft = ft2; intx = 1; } } } } } } else{ float sqrtb2ac = sqrt(b2ac); t1 = (-b+sqrtb2ac)/a; /* assert(t1); */ if(t1>=0 && t1<=1){ float td; i1[2] = e[2]*t1 + e1[2]; td = (i1[2] - d1[2]) / d[2]; if(td>=0 && td<=1){ /* i1 is in between d1 and d2 */ printf("a=%f, b=%f, c=%f, t1=%f, td=%f\n",a,b,c,t1, td); float v[2]; float ft2; mad2(i1,e,t1,e1); /* i1 = t1*e + e1 */ mad2(v,d,td,d1); /* v = td*d + d1 */ float r2 = 0.5f*(dot2(i1,i1)+dot2(v,v)); if(cross2(v,i1)>=0){ /* <2*PI */ ft2 = 1.0f + dot2(i1,v)/r2; } else{ ft2 = -1.0f - dot2(i1,v)/r2; } printf("dot2(v,v)=%f, dot2(i1,i1)=%f ft2=%f, ft=%f JJJ\n", dot2(v,v),r2, ft2, *ft); if(ft2 > *ft){ /* found ealier hit point */ *ft = ft2; intx = 1; itx[0] = i1[0]; itx[1] = i1[1]; itx[2] = i1[2]; } } } t2 = (-b-sqrtb2ac)/a; if(t2>=0 && t2<=1){ float td; i2[2] = e[2]*t2 + e1[2]; td = (i2[2] - d1[2]) / d[2]; if(td>=0 && td<=1){ /* i1 is in between d1 and d2 */ float v[2]; float ft2; mad2(i2,e,t2,e1); mad2(v,d,td,d1); float r2 = .5f*(dot2(i2,i2)+dot2(v,v)); /* dot2(i2,v)/dot2(i2,i2) may > 1 */ if(cross2(v,i2)>=0){ /* <2*PI */ ft2 = 1.0f + dot2(i2,v)/r2; } else{ ft2 = -1.0f - dot2(i2,v)/r2; } if(ft2 > *ft){ /* found ealier hit point */ *ft = ft2; intx = 1; itx[0] = i2[0]; itx[1] = i2[1]; itx[2] = i2[2]; printf("KKK\n"); } } } } if(intx){ if(*ft>2.0f){ /* *ft=2.0f; */ printf("ft=%f, d[2]=%f\n", *ft, d[2]); } assert(*ft<=2.0); } return intx; } void testee() { #if 0 v3_t v0={-2.3, .5, 0.1},v1={-0.5, .5, 0.1}; v3_t obs0={-1.5, .7, -0.5},obs1={3, .9, 0.3}; rot_t rot; rot.axis=vec(0,0,1); rot.org=vec(0,0,0); rot.deg=250; rot.rad=DEG2RAD(rot.deg); float ft= rot.rad<PI ? 1.0f + cosf(rot.rad) : -1.0f - cosf(rot.rad); v3_t itx; int intx; /* float ft0 = ft; for(int i=0; i<10000000; i++){ ft = ft0; intx = rotee(&v0,&v1,&obs0,&obs1,&ft,&itx); } extern int done; done=1; */ intx = rotee(&v0,&v1,&obs0,&obs1,&ft,&itx); float c,rad; if(ft>=0) rad=acosf(ft-1.0f); else rad=2*PI-acosf(-1.0f-ft); rot.rad = rad; float rotmat[3][3]; rot2mat(&rot, rotmat); v3_t w0,w1; w0 = matv3(rotmat, v0); w1 = matv3(rotmat, v1); glLineWidth(5); glBegin(GL_LINES); glColor3f(0,1,0); glVertex3fv(&v0); glVertex3fv(&v1); glColor3f(1,0,0); glVertex3fv(&obs0); glVertex3fv(&obs1); glColor3f(0,0,1); glVertex3fv(&w0); glVertex3fv(&w1); glEnd(); glLineWidth(1); glColor3f(1,1,1); glPointSize(5); glBegin(GL_POINTS); glVertex3fv(&itx); glEnd(); glPointSize(1); printf("intx=%i, ft=%f\n",intx,ft); #endif } static inline void rotpln2z(float zmat[3][3], v3_t *org, plane_t *pln) { v3_t v = matv3(zmat, sub(scale(pln->n, pln->d), *org)); pln->n = matv3(zmat, pln->n); pln->d = dot(pln->n,v); } extern int globrebuildpntbnd; void debug_drawrotpnt_n_bnd() { static rot_t rot; v3_t p0, p1; float rotmat[3][3]; float rotbnd[2][3]; float zmat[3][3]; v3_t v; v3_t intx; testee(); if(globrebuildpntbnd){ rot.axis.x = rand(); rot.axis.y = rand(); rot.axis.z = rand(); rot.axis = normalize(rot.axis); rot.org = vec(0,0,0); rot.deg = rand()%360; rot.rad = DEG2RAD(rot.deg); globrebuildpntbnd=0; } #if 0 if(globrebuildpntbnd){ rot.axis = normalize(vec(1,0,1)); rot.org = vec(0,0,0); rot.deg = rand()%360; rot.rad = DEG2RAD(rot.deg); globrebuildpntbnd=0; } #endif p0.x = p0.y = p0.z = 1; v3_t proj = scale(rot.axis, dot(p0,rot.axis)); v3_t rotorg = add(rot.org, proj); v3_t r,u; r = sub(p0, rotorg); u = cross(rot.axis,r); rot2mat(&rot, rotmat); p1 = add(rot.org, matv3(rotmat, sub(p0,rot.org))); /* p1 = add(rotorg, add(scale(r,cosf(rot.rad)),scale(u,sinf(rot.rad)))); */ rotpntbnd(&rot, p0, p1, rotbnd); v = add(rot.org, rot.axis); v3_t z0,z1; rot2zmat(&rot,zmat); z0=matv3(zmat, sub(p0,rot.org)); z1=matv3(zmat, sub(p1,rot.org)); v3_t oldz0=z0,oldz1=z1; plane_t pln={0,1,0,.5}; rotpln2z(zmat, &rot.org, &pln); float ft = rot.rad>PI ? -1.0f-cosf(rot.rad) : 1.0f+cosf(rot.rad); int hit; #if 0 float ft0=ft; for(int i=0; i<10000000;i++){ ft=ft0; hit=rotvpln(&z0, &pln, &ft, &z1); } extern int done; done=1; #endif /* printf("ft=%f\n",ft); */ hit=rotvpln(&z0, &pln, &ft, &z1); if(hit){ z1=add(rot.org,mattv3(zmat, z1)); /* printf("hit=(%f %f %f)\n",z1.x,z1.y,z1.z); */ } z0=matv3(zmat,rot.axis); /* draw axis */ glBegin(GL_LINES); glColor3f(1,0,0); glVertex3fv(&rot.org); glColor3f(0,0,1); glVertex3fv(&v); glEnd(); /* draw trace */ glColor3f(0,0,.2); glBegin(GL_LINE_STRIP); for(float rad=0; rad<rot.rad; rad+=0.02){ v3_t p; p = add(rotorg, add(scale(r,cosf(rad)),scale(u,sinf(rad)))); glVertex3fv(&p); } glEnd(); /* draw points */ glPointSize(5); glBegin(GL_POINTS); glColor3f(0,1,1); glVertex3fv(&p0); glColor3f(0,1,0); glVertex3fv(&p1); if(hit){ glColor3f(1,0,0); glVertex3fv(&z1); } glColor3f(0,0,0); glVertex3fv(&oldz0); glColor3f(1,0,1); glVertex3fv(&oldz1); glEnd(); glPointSize(1); /* draw bounds */ float bndcolor[3] = {0,0,1}; drawbox(rotbnd, bndcolor); glColor3f(1,1,1); glBegin(GL_LINES); glVertex3f(0,0,0); glVertex3fv(&z0); glEnd(); } int rotobj(rot_t *rot, obj_t *obj, sctr_t *sctr, ccdinfo_t *ccdinfo) { /* 1. find all obstacles (brush/obj) 2. transform the object and obstacles into a collision coordinate system (1) translate center of rotation to (0,0,0) (2) rotate rotation axis to (0,0,1) */ #if 0 v3_t objverts[64]; v3_t obsverts[64]; float zmat[3][3]; float rotbnd[2][3]; int n; /* 1. */ rotationalbnd(rot, rotbnd, obj->phd); n = rngqry(sctr->sp, rotbnd, meh_touchers); if(!n){ return 0; } /* 2. */ rot2zmat(rot->axis, zmat); for(int i=0; i<obj->phd->nverts; i++){ objverts[i] = matv3(zmat, sub(obj->phd->verts[i], rot->org)); } for(int i=0; i<n; i++){ stuff_t *stuff = SP_GETOWNER(sctr->sp, meh_touchers[i]); phd_t *phd = stuff->common.phd; for(int j=0; j<phd->nverts; j++){ obsverts[j] = matv3(zmat, sub(phd->verts[i], rot->org)); } } #endif } static struct{ rot_t *rot0; phd_t *phd; rot_t rot; float zmat[3][3]; float rotmat[3][3]; v3_t zverts[32]; float vbnds[6*32]; /* bnd of verts */ float pbnd[2][3]; /* bnd of phd */ float ft; v3_t intx; ccdinfo_t *ccd; int stuck; } meh_rp; #define RADFUNC(rad) (((rad)>PI ? -1.0f-cosf(rad) : 1.0f+cosf(rad))) static void beginrotphd(rot_t *rot, phd_t *phd, ccdinfo_t *ccd) { meh_rp.phd = phd; meh_rp.rot0 = rot; meh_rp.ccd = ccd; meh_rp.stuck=0; if(rot->rad<0){ meh_rp.rot.rad = -meh_rp.rot.rad; meh_rp.rot.deg = -meh_rp.rot.deg; meh_rp.rot.axis = scale(rot->axis, -1); meh_rp.rot.org = rot->org; } else{ meh_rp.rot = *rot; } rot2zmat(&meh_rp.rot, meh_rp.zmat); rot2mat(&meh_rp.rot, meh_rp.rotmat); for(int i=0; i<phd->nverts; i++){ v3_t r, p; r = sub(phd->verts[i], rot->org); p = add(rot->org, matv3(meh_rp.rotmat, r)); meh_rp.zverts[i] = matv3(meh_rp.zmat, r); rotpntbnd(&meh_rp.rot, phd->verts[i], p, meh_rp.vbnds+6*i); } meh_rp.pbnd[0][0] = meh_rp.pbnd[0][1] = meh_rp.pbnd[0][2] = 1e10f; meh_rp.pbnd[1][0] = meh_rp.pbnd[1][1] = meh_rp.pbnd[1][2] = -1e10f; for(int i=0; i<6*phd->nverts; i+=6){ float *bnd=meh_rp.vbnds+i; for(int j=0; j<3; j++){ if(bnd[j]<meh_rp.pbnd[0][j]){ meh_rp.pbnd[0][j] = bnd[j];} if(bnd[j+3]>meh_rp.pbnd[1][j]){ meh_rp.pbnd[1][j] = bnd[j+3];} } } if(meh_rp.rot.rad>2*PI){ meh_rp.ft = -2.0f; } else{ meh_rp.ft = RADFUNC(meh_rp.rot.rad); } } int rotagstphd(phd_t *phd) { /* Three types of tests -- phd1->vert vs. phd2->poly -- phd1->poly vs. phd2->vert -- phd1->edge vs. phd2->edge Mid-phase: */ /* brute force */ /* 1 */ char bbitx[32]; char bbitx2[32]; plane_t edgeplns[16]; v3_t zverts[32]; int coll=0; for(int i=0; i<meh_rp.phd->nverts; i++){ bbitx[i] = bbintx(meh_rp.vbnds+6*i, phd->bnd); } for(int i=0; i<phd->nverts; i++){ zverts[i] = matv3(meh_rp.zmat, sub(phd->verts[i], meh_rp.rot.org)); } #if 1 for(int i=0; i<phd->npolys; i++){ poly_t *p = phd->polys + i; float pbnd[2][3]; plane_t pln = p->plane; rotpln2z(meh_rp.zmat, &meh_rp.rot.org, &pln); poly2bnd(phd, i, pbnd); #if EDGECACHE #else for(int j=0; j<p->nv; j++){ v3_t *v,*v2; v = zverts + p->v[j]; v2 = zverts + p->v[(j+1)%p->nv]; edgeplns[j].n = cross(pln.n, sub(*v2, *v)); edgeplns[j].d = dot(edgeplns[j].n, *v); } #endif for(int j=0; j<meh_rp.phd->nverts; j++){ if(!bbitx[j]) continue; if(!bbintx(meh_rp.vbnds+6*j, pbnd)) continue; v3_t intx,intx2; float ft = meh_rp.ft; /* printf("damn dot(pln.n,v)=%f, pln.d=%f, pln.n=(%f %f %f), v0=(%f, %f, %f)\n", dot(pln.n, meh_rp.zverts[j]), pln.d, pln.n.x, pln.n.y, pln.n.z, meh_rp.phd->verts[j].x, meh_rp.phd->verts[j].y, meh_rp.phd->verts[j].z); */ int stuck = rotvpln(meh_rp.zverts+j, &pln, &ft, &intx); /* printf("j=%i stuck=%i KKKKKKKKKKKKKKKKKKKKKKKK\n",j,stuck); */ if(stuck){ #if EDGECACHE intx2 = add(meh_rp.rot.org, mattv3(meh_rp.zmat, intx)); if(pntinpoly(&intx2, phd, i)){ #else if(pntinpoly(&intx, edgeplns, p->nv)){ #endif meh_rp.ft = ft; meh_rp.intx = intx; /* in z space */ coll=1; } } } } #endif #if 1 /* 2 */ for(int i=0; i<phd->nverts; i++){ bbitx[i] = pntinbnd(phd->verts+i, meh_rp.pbnd); } for(int i=0; i<meh_rp.phd->npolys; i++){ poly_t *p = meh_rp.phd->polys + i; plane_t pln = p->plane; rotpln2z(meh_rp.zmat, &meh_rp.rot.org, &pln); #if EDGECACHE #else for(int j=0; j<p->nv; j++){ v3_t *v,*v2; v = meh_rp.zverts + p->v[j]; v2 = meh_rp.zverts + p->v[(j+1)%p->nv]; edgeplns[j].n = cross(pln.n, sub(*v2, *v)); edgeplns[j].d = dot(edgeplns[j].n, *v); } #endif pln.n.x = -pln.n.x; for(int j=0; j<phd->nverts; j++){ if(!bbitx[j]) continue; v3_t intx, intx2; float ft = meh_rp.ft; v3_t v = zverts[j]; v.x = -v.x; int stuck = rotvpln(&v, &pln, &ft, &intx); if(stuck){ intx.x = -intx.x; #if EDGECACHE intx2 = add(meh_rp.rot.org, mattv3(meh_rp.zmat, intx)); if(pntinpoly(&intx2, meh_xp.phd, i)){ #else if(pntinpoly(&intx, edgeplns, p->nv)){ #endif meh_rp.ft = ft; meh_rp.intx = intx; coll=1; } } } } #endif /* 3 */ for(int i=0; i<meh_rp.phd->nedges; i++){ float *d1, *d2, *e1, *e2; int *v; v = meh_rp.phd->edges[i].v; d1 = meh_rp.zverts + v[0]; d2 = meh_rp.zverts + v[1]; for(int j=0; j<phd->nedges; j++){ v3_t intx; float ft = meh_rp.ft; v = phd->edges[j].v; e1 = zverts + v[0]; e2 = zverts + v[1]; int stuck = rotee(d1,d2,e1,e2,&ft,&intx); if(stuck){ printf("yeah KKKKKKKKK\n"); /* if(ft>meh_rp.ft){ */ meh_rp.ft = ft; meh_rp.intx = intx; /* } */ coll=1; } } } meh_rp.stuck += coll; return coll; } int endrotphd() { #if 0 if(meh_rp.ft>=2){ /* meh_rp.ccd->intx = vec(0,0,0); */ meh_rp.rot0->rad = 0; return 1; } if(meh_rp.ft<=-2){ meh_rp.rot0->rad = meh_rp.rot.rad; return 0; } #endif #if 0 if(meh_rp.ft>2.0f) meh_rp.ft=2.0f; else if(meh_rp.ft<-2.0f) meh_rp.ft=-2.0f; #endif if(meh_rp.stuck){ meh_rp.rot0->rad = meh_rp.ft>0 ? acosf(meh_rp.ft - 1.0f) : 2*PI - acosf(-meh_rp.ft - 1.0f); v3_t r = mattv3(meh_rp.zmat, meh_rp.intx); meh_rp.ccd->intx = add(meh_rp.rot.org, r); float l = meh_rp.rot0->rad * length(r); meh_rp.rot0->rad *= (l - CONTACT_EPSILON)/ l; /* meh_rp.ccd->intx = meh_rp.intx; */ /* meh_rp.rot0->rad *= 0.998; */ /* meh_rp.rot0->rad -= 0.0003; */ if(meh_rp.rot0->rad<0) meh_rp.rot0->rad = 0; } else{ return 0; } return meh_rp.stuck; } void testrotphd() { static float deg=1; extern phd_t *globphds[]; rot_t rot; ccdinfo_t ccd; rot.org = bndcntr(globphds[1]->bnd); rot.axis = normalize(vec(.5,1.3, -.3)); rot.deg = deg; rot.rad = DEG2RAD(rot.deg); printf("rad=%f\n",rot.rad); beginrotphd(&rot, globphds[1], &ccd); /* static int s=0; */ static v3_t intx; rotagstphd(globphds[0]); int stuck = endrotphd(); /* if(rot.rad) rotphd(globphds[1], &rot); */ #if 1 /* if(!s) */{ if(stuck){ deg=0; /* s=1; */ /* rot.rad -= 0.0003; */ /* if(rot.rad<0) rot.rad=0; */ intx = ccd.intx;/* add(meh_rp.rot.org, mattv3(meh_rp.zmat, ccd.intx)); */ printf("shit deg=%f, ft=%f, intx=(%f %f %f), rot.org=(%f %f %f)\n", RAD2DEG(meh_rp.rot.rad), meh_rp.ft, intx.x, intx.y, intx.z, rot.org.x, rot.org.y, rot.org.z); } } if(rot.rad){ rotphd(globphds[1], &rot); } printf("stuck=%i, rot.rad=%f\n", stuck, rot.rad); #endif /* printf("intx=(%f %f %f)\n", intx.x, intx.y, intx.z); */ #if 0 if(stuck){ if(rot.rad>0){ rotphd(globphds[1], &rot); intx = ccd.intx; } } #endif #if 1 glLineWidth(1); glColor3f(1,0,0); drawphd(globphds[0]); glColor3f(0,0,1); drawphd(globphds[1]); glLineWidth(1); glPointSize(5); glColor3f(0,1,1); glBegin(GL_POINTS); glVertex3fv(&intx); glEnd(); glPointSize(1); #endif #if 0 glPointSize(2); glColor3f(1,.5,.5); glBegin(GL_POINTS); glVertex3fv(&ii); glEnd(); #endif #if 0 float color[3] = {.2,.2,1}; drawbox(meh_rp.pbnd, color); #endif #if 0 rot_t rot2; v3_t pnt = {1,0,0}; rot2.deg = 50; rot2.axis = vec(0,0,1); rot2.rad = DEG2RAD(rot2.deg); rot2.org = vec(0,0,0); float mat[3][3]; rot2mat(&rot2, mat); v3_t pnt2 = matv3(mat, pnt); rot2.deg = 210; rot2.rad = DEG2RAD(rot2.deg); rot2mat(&rot2, mat); v3_t pnt3 = matv3(mat, pnt); #endif #if 0 rot_t rot2; v3_t pnt = {1,0,0}; rot2.deg = 100; rot2.axis = vec(0,0,1); rot2.rad = DEG2RAD(rot2.deg); rot2.org = vec(0,0,0); float mat[3][3]; rot2mat(&rot2, mat); v3_t pnt2 = matv3(mat, pnt); #endif #if 0 glLineWidth(5); glColor3f(.6, .3, .9); glBegin(GL_LINE_STRIP); glVertex3fv(&pnt); glVertex3fv(&pnt2); glVertex3fv(&pnt3); glEnd(); glLineWidth(1); #endif } /* find contact points between two phds just another translational ccd? or some static checking? which one is faster? this test shouldn't be O(n^2) for a phd, three contact points are enough. or, use persistent contact manifold? */ int addlight() { } int rmlight() { } int xlatlight() { } /* which sector the point is in? */ sctr_t *inwhichsctr(v3_t pnt) { int n=pntqry(map.sp, pnt, meh_touchers); for(int i=0;i<n;i++){ sctr_t *s = SP_GETOWNER(map.sp, meh_touchers[i]); if(pntinphd(pnt, s->phd)) return s; } return NULL; } static void drawsctr(sctr_t *s) { for(int i=0;i<s->nwalls;i++){ wall_t *w = s->walls + i; for(brush_t *b=w->brushlist; b; b=b->next){ drawphd(b->phd); } } for(brush_t *b=s->brushlist; b; b=b->next){ drawphd(b->phd); } glLineWidth(3); for(int i=0;i<s->nwalls;i++){ wall_t *w = s->walls + i; for(metaptl_t *mp=w->mptllist; mp; mp=mp->next){ glColor3f(0,1,0); glBegin(GL_POLYGON); for(int j=0;j<mp->nverts;j++){ glVertex3fv(mp->verts+j); } glEnd(); } } glLineWidth(1); } static void drawmap() { for(sctr_t *s=map.sctrlist; s; s=s->next){ drawphd(s->phd); } glLineWidth(3); for(sctr_t *s=map.sctrlist; s; s=s->next){ for(int i=0;i<s->nwalls;i++){ wall_t *w = s->walls + i; for(metaptl_t *mp=w->mptllist; mp; mp=mp->next){ glColor3f(0,1,0); glBegin(GL_POLYGON); for(int j=0;j<mp->nverts;j++){ glVertex3fv(mp->verts+j); } glEnd(); } } } glLineWidth(1); } static void integrate() { } /* simulate the object */ int sim(obj_t *obj) { } #if 0 /* take a snapshot of the map, regardless of whether or not other things like physics are finished. */ int snapshot(pnt_t *p, v3_t *dir) { } #endif void render(cam_t *cam) { sctr_t *s = inwhichsctr(cam->pos); if(s){ glColor3f(0,0,0); drawsctr(s); } else{ glColor3f(1,1,1); drawmap(); } } int loadsctr() { } int stosctr() { } /* create a new empty map (the previous map is ) */ void initmap() { if(map.sp){ freesp(map.sp); /* remove sectors */ } map.sp = allocsp(32); map.sctrlist = NULL; map.nsctrs = 0; } void shutdownmap() { if(map.sp){ freesp(map.sp); rmallsctrs(); } } /* the sectors are stored in one file, separated from the content in each sector. sectors, portals and light volumes are all loaded to RAM; brushes, objects and textures are streamed in later when needed. */ int loadmap() { } sctr_t *debug_getsctr(int id) { if(id>=map.nsctrs) return NULL; sctr_t *s=map.sctrlist; while(id){ s=s->next; id--; } return s; }
20.952951
125
0.577426
5667b10db6ef5cbfeb1c10cd1f51361225dcd286
1,032
c
C
libft/ft_lstdelcont.c
Mcluckinson/lemin_viz
f52b2d8b4b07d58f8ed1224401381f87bb4b3905
[ "WTFPL" ]
null
null
null
libft/ft_lstdelcont.c
Mcluckinson/lemin_viz
f52b2d8b4b07d58f8ed1224401381f87bb4b3905
[ "WTFPL" ]
null
null
null
libft/ft_lstdelcont.c
Mcluckinson/lemin_viz
f52b2d8b4b07d58f8ed1224401381f87bb4b3905
[ "WTFPL" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_lstdelcont.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: cyuriko <cyuriko@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/05/06 13:13:37 by cyuriko #+# #+# */ /* Updated: 2019/05/06 17:20:59 by cyuriko ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" void ft_lstdelcont(void *content, size_t content_size) { if (!content) return ; free(content); content_size = 0; }
46.909091
80
0.194767
4cc62fc32d7069fc6174cf9dc7bd8568dc0635b6
1,631
h
C
ScoreBlitz/Classes/PagePickerScrollView.h
Proper-Job/irollmusic
23111dfb9adfe06e89180554f6f34a31f6d40650
[ "MIT" ]
null
null
null
ScoreBlitz/Classes/PagePickerScrollView.h
Proper-Job/irollmusic
23111dfb9adfe06e89180554f6f34a31f6d40650
[ "MIT" ]
null
null
null
ScoreBlitz/Classes/PagePickerScrollView.h
Proper-Job/irollmusic
23111dfb9adfe06e89180554f6f34a31f6d40650
[ "MIT" ]
null
null
null
// // PagePickerScrollView.h // ScoreBlitz // // Created by Moritz Pfeiffer on 16.03.11. // Copyright 2011 __MyCompanyName__. All rights reserved. // #import <UIKit/UIKit.h> @class Score, PagePickerItemView, PagePickerScrollView, Page; @protocol PickerScrollViewDelegate <NSObject> - (void)pickerScrollViewDidHide:(PagePickerScrollView *)thePickerScrollView; - (void)pickerScrollViewSelectionDidChange:(Page *)newSelection; @end @interface PagePickerScrollView : UIScrollView <UIScrollViewDelegate> { @protected NSMutableSet *_recycledItems, *_visibleItems; NSArray *_orderedPagesAsc; } @property (nonatomic, weak) id <PickerScrollViewDelegate> pickerDelegate; @property (nonatomic, strong) Score *activeScore; @property (nonatomic, assign) PagePickerShowAnimation showAnimation; @property (nonatomic, weak) UIView *theSuperview; @property (nonatomic, weak) IBOutlet PagePickerItemView *itemView; @property (nonatomic, assign) CGFloat padding; @property (nonatomic, strong) Page *activePage; - (id)init; - (void)showInView:(UIView *)theView belowToolbar:(UIToolbar *)theToolbar withAnimation:(PagePickerShowAnimation)theAnimation; - (void)hideAnimated:(BOOL)animated; - (void)viewControllerPageSelectionDidChange; - (NSArray *)orderedPagesAsc; - (void)pagePickerButtonPressedWithPage:(Page *)thePage; #define kPickerHeightHorizontal 195 #define kPickerWidthVertical 140 #define kPickerXPickerPaddingVertical 5 #define kPickerShowHideAnimationDuration .35 #define kPickerItemHeight 185 #define kPickerItemWidth 125 #define kPickerBackgroundAlpha .5 #define kPickerItemOverlayImageAlpha .5 @end
29.125
76
0.798896
1ece076f12b5a81140a135d77dfab1e12cc144a2
3,884
h
C
openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/systemd/1_242+AUTOINC+db2e367bfc-r0/git/src/basic/static-destruct.h
sotaoverride/backup
ca53a10b72295387ef4948a9289cb78ab70bc449
[ "Apache-2.0" ]
null
null
null
openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/systemd/1_242+AUTOINC+db2e367bfc-r0/git/src/basic/static-destruct.h
sotaoverride/backup
ca53a10b72295387ef4948a9289cb78ab70bc449
[ "Apache-2.0" ]
null
null
null
openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/systemd/1_242+AUTOINC+db2e367bfc-r0/git/src/basic/static-destruct.h
sotaoverride/backup
ca53a10b72295387ef4948a9289cb78ab70bc449
[ "Apache-2.0" ]
null
null
null
#pragma once #include "alloc-util.h" #include "macro.h" /* A framework for registering static variables that shall be freed on shutdown * of a process. It's a bit like gcc's destructor attribute, but allows us to * precisely schedule when we want to free the variables. This is supposed to * feel a bit like the gcc cleanup attribute, but for static variables. Note * that this does not work for static variables declared in .so's, as the list * is private to the same linking unit. But maybe that's a good thing. */ typedef struct StaticDestructor { void* data; free_func_t destroy; } StaticDestructor; #define STATIC_DESTRUCTOR_REGISTER(variable, func) \ _STATIC_DESTRUCTOR_REGISTER(UNIQ, variable, func) #define _STATIC_DESTRUCTOR_REGISTER(uq, variable, func) \ /* Type-safe destructor */ \ static void UNIQ_T(static_destructor_wrapper, uq)(void* p) \ { \ typeof(variable)* q = p; \ func(q); \ } \ /* The actual destructor structure we place in a special section to find \ * it */ \ _section_("SYSTEMD_STATIC_DESTRUCT") /* We pick pointer alignment, since \ that is apparently what gcc does \ for static variables */ \ _alignptr_ /* Make sure this is not dropped from the image because not \ explicitly referenced */ \ _used_ /* Make sure that AddressSanitizer doesn't pad \ this variable: we want everything in this \ section packed next to each other so that we \ can enumerate it. */ \ _variable_no_sanitize_address_ static const StaticDestructor \ UNIQ_T(static_destructor_entry, uq) = { \ .data = &(variable), \ .destroy = UNIQ_T( \ static_destructor_wrapper, uq), \ } /* Beginning and end of our section listing the destructors. We define these as * weak as we want this to work even if there's not a single destructor is * defined in which case the section will be missing. */ extern const struct StaticDestructor _weak_ __start_SYSTEMD_STATIC_DESTRUCT[]; extern const struct StaticDestructor _weak_ __stop_SYSTEMD_STATIC_DESTRUCT[]; /* The function to destroy everything. (Note that this must be static inline, as * it's key that it remains in the same * linking unit as the variables we want to destroy. */ static inline void static_destruct(void) { const StaticDestructor* d; if (!__start_SYSTEMD_STATIC_DESTRUCT) return; d = ALIGN_TO_PTR(__start_SYSTEMD_STATIC_DESTRUCT, sizeof(void*)); while (d < __stop_SYSTEMD_STATIC_DESTRUCT) { d->destroy(d->data); d = ALIGN_TO_PTR(d + 1, sizeof(void*)); } }
55.485714
96
0.475026
1eeaafeb66581777c8c3bc201df5758d33153216
947
h
C
SSIDCard-master/SSIDCard/Classes/Public/Category/UIView+SS.h
wnrz/SSIDCard-
3b8b33028d9084d0d9096159ac0360190094eb8d
[ "MIT" ]
248
2018-05-02T02:26:22.000Z
2021-11-08T03:22:34.000Z
SSIDCard-master/SSIDCard/Classes/Public/Category/UIView+SS.h
wnrz/SSIDCard-
3b8b33028d9084d0d9096159ac0360190094eb8d
[ "MIT" ]
5
2018-05-30T02:07:35.000Z
2020-07-14T09:57:00.000Z
SSIDCard-master/SSIDCard/Classes/Public/Category/UIView+SS.h
wnrz/SSIDCard-
3b8b33028d9084d0d9096159ac0360190094eb8d
[ "MIT" ]
30
2018-05-02T02:26:37.000Z
2021-01-27T07:50:46.000Z
// // UIView+SS.h // SSIDCard // // Created by 张家铭 on 2018/5/3. // #import <UIKit/UIKit.h> @interface UIView (SS) @property (nonatomic) CGFloat ss_left; ///< Shortcut for frame.origin.x. @property (nonatomic) CGFloat ss_top; ///< Shortcut for frame.origin.y @property (nonatomic) CGFloat ss_right; ///< Shortcut for frame.origin.x + frame.size.width @property (nonatomic) CGFloat ss_bottom; ///< Shortcut for frame.origin.y + frame.size.height @property (nonatomic) CGFloat ss_width; ///< Shortcut for frame.size.width. @property (nonatomic) CGFloat ss_height; ///< Shortcut for frame.size.height. @property (nonatomic) CGFloat ss_centerX; ///< Shortcut for center.x @property (nonatomic) CGFloat ss_centerY; ///< Shortcut for center.y @property (nonatomic) CGPoint ss_origin; ///< Shortcut for frame.origin. @property (nonatomic) CGSize ss_size; ///< Shortcut for frame.size. @end
39.458333
98
0.682154
7183e13ee3a3e266d4ada8161cf28c4c4d526ca0
5,330
c
C
sys/src/lib/9p2000/convM2S.c
ekaitz-zarraga/jehanne
431c7ae36521d0d931a21e1100d8522893d22a35
[ "RSA-MD" ]
287
2017-01-06T07:22:55.000Z
2022-03-28T10:45:32.000Z
sys/src/lib/9p2000/convM2S.c
ekaitz-zarraga/jehanne
431c7ae36521d0d931a21e1100d8522893d22a35
[ "RSA-MD" ]
17
2017-01-06T16:49:43.000Z
2022-01-07T11:23:27.000Z
sys/src/lib/9p2000/convM2S.c
ekaitz-zarraga/jehanne
431c7ae36521d0d931a21e1100d8522893d22a35
[ "RSA-MD" ]
21
2017-01-23T14:46:57.000Z
2021-11-17T23:27:41.000Z
/* * This file is part of the UCB release of Plan 9. It is subject to the license * terms in the LICENSE file found in the top-level directory of this * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No * part of the UCB release of Plan 9, including this file, may be copied, * modified, propagated, or distributed except according to the terms contained * in the LICENSE file. */ #include <u.h> #include <lib9.h> #include <9P2000.h> static uint8_t* gstring(uint8_t *p, uint8_t *ep, char **s) { int n; if(p+BIT16SZ > ep) return nil; n = GBIT16(p); if(n < 0) return nil; p += BIT16SZ - 1; if(p+n+1 > ep) return nil; /* move it down, on top of count, to make room for '\0' */ memmove(p, p + 1, n); p[n] = '\0'; *s = (char*)p; p += n+1; return p; } static uint8_t* gqid(uint8_t *p, uint8_t *ep, Qid *q) { if(p+QIDSZ > ep) return nil; q->type = GBIT8(p); p += BIT8SZ; q->vers = GBIT32(p); p += BIT32SZ; q->path = GBIT64(p); p += BIT64SZ; return p; } /* * no syntactic checks. * three causes for error: * 1. message size field is incorrect * 2. input buffer too short for its own data (counts too long, etc.) * 3. too many names or qids * gqid() and gstring() return nil if they would reach beyond buffer. * main switch statement checks range and also can fall through * to test at end of routine. */ uint32_t convM2S(uint8_t *ap, uint32_t nap, Fcall *f) { uint8_t *p, *ep; uint32_t i, size; p = ap; ep = p + nap; if(p+BIT32SZ+BIT8SZ+BIT16SZ > ep) return 0; size = GBIT32(p); p += BIT32SZ; if(size < BIT32SZ+BIT8SZ+BIT16SZ) return 0; f->type = GBIT8(p); p += BIT8SZ; f->tag = GBIT16(p); p += BIT16SZ; switch(f->type) { default: return 0; case Tversion: if(p+BIT32SZ > ep) return 0; f->msize = GBIT32(p); p += BIT32SZ; p = gstring(p, ep, &f->version); break; case Tflush: if(p+BIT16SZ > ep) return 0; f->oldtag = GBIT16(p); p += BIT16SZ; break; case Tauth: if(p+BIT32SZ > ep) return 0; f->afid = GBIT32(p); p += BIT32SZ; p = gstring(p, ep, &f->uname); if(p == nil) break; p = gstring(p, ep, &f->aname); break; case Tattach: if(p+BIT32SZ > ep) return 0; f->fid = GBIT32(p); p += BIT32SZ; if(p+BIT32SZ > ep) return 0; f->afid = GBIT32(p); p += BIT32SZ; p = gstring(p, ep, &f->uname); if(p == nil) break; p = gstring(p, ep, &f->aname); break; case Twalk: if(p+BIT32SZ+BIT32SZ+BIT16SZ > ep) return 0; f->fid = GBIT32(p); p += BIT32SZ; f->newfid = GBIT32(p); p += BIT32SZ; f->nwname = GBIT16(p); p += BIT16SZ; if(f->nwname > MAXWELEM) return 0; for(i=0; i<f->nwname; i++){ p = gstring(p, ep, &f->wname[i]); if(p == nil) break; } break; case Topen: if(p+BIT32SZ+BIT8SZ > ep) return 0; f->fid = GBIT32(p); p += BIT32SZ; f->mode = GBIT8(p); p += BIT8SZ; break; case Tcreate: if(p+BIT32SZ > ep) return 0; f->fid = GBIT32(p); p += BIT32SZ; p = gstring(p, ep, &f->name); if(p == nil) break; if(p+BIT32SZ+BIT8SZ > ep) return 0; f->perm = GBIT32(p); p += BIT32SZ; f->mode = GBIT8(p); p += BIT8SZ; break; case Tread: if(p+BIT32SZ+BIT64SZ+BIT32SZ > ep) return 0; f->fid = GBIT32(p); p += BIT32SZ; f->offset = GBIT64(p); p += BIT64SZ; f->count = GBIT32(p); p += BIT32SZ; break; case Twrite: if(p+BIT32SZ+BIT64SZ+BIT32SZ > ep) return 0; f->fid = GBIT32(p); p += BIT32SZ; f->offset = GBIT64(p); p += BIT64SZ; f->count = GBIT32(p); p += BIT32SZ; if(p+f->count > ep) return 0; f->data = (char*)p; p += f->count; break; case Tclunk: case Tremove: if(p+BIT32SZ > ep) return 0; f->fid = GBIT32(p); p += BIT32SZ; break; case Tstat: if(p+BIT32SZ > ep) return 0; f->fid = GBIT32(p); p += BIT32SZ; break; case Twstat: if(p+BIT32SZ+BIT16SZ > ep) return 0; f->fid = GBIT32(p); p += BIT32SZ; f->nstat = GBIT16(p); p += BIT16SZ; if(p+f->nstat > ep) return 0; f->stat = p; p += f->nstat; break; /* */ case Rversion: if(p+BIT32SZ > ep) return 0; f->msize = GBIT32(p); p += BIT32SZ; p = gstring(p, ep, &f->version); break; case Rerror: p = gstring(p, ep, &f->ename); break; case Rflush: break; case Rauth: p = gqid(p, ep, &f->aqid); break; case Rattach: p = gqid(p, ep, &f->qid); break; case Rwalk: if(p+BIT16SZ > ep) return 0; f->nwqid = GBIT16(p); p += BIT16SZ; if(f->nwqid > MAXWELEM) return 0; for(i=0; i<f->nwqid; i++){ p = gqid(p, ep, &f->wqid[i]); if(p == nil) break; } break; case Ropen: case Rcreate: p = gqid(p, ep, &f->qid); if(p == nil) break; if(p+BIT32SZ > ep) return 0; f->iounit = GBIT32(p); p += BIT32SZ; break; case Rread: if(p+BIT32SZ > ep) return 0; f->count = GBIT32(p); p += BIT32SZ; if(p+f->count > ep) return 0; f->data = (char*)p; p += f->count; break; case Rwrite: if(p+BIT32SZ > ep) return 0; f->count = GBIT32(p); p += BIT32SZ; break; case Rclunk: case Rremove: break; case Rstat: if(p+BIT16SZ > ep) return 0; f->nstat = GBIT16(p); p += BIT16SZ; if(p+f->nstat > ep) return 0; f->stat = p; p += f->nstat; break; case Rwstat: break; } if(p==nil || p>ep) return 0; if(ap+size == p) return size; return 0; }
16.920635
79
0.573546
71a82752954b486cf23f23c84b1a625af191ad7a
825
h
C
gnu/usr.bin/binutils/binutils/defparse.h
ArrogantWombatics/openbsd-src
75721e1d44322953075b7c4b89337b163a395291
[ "BSD-3-Clause" ]
1
2019-02-16T13:29:23.000Z
2019-02-16T13:29:23.000Z
gnu/usr.bin/binutils/binutils/defparse.h
ArrogantWombatics/openbsd-src
75721e1d44322953075b7c4b89337b163a395291
[ "BSD-3-Clause" ]
1
2018-08-21T03:56:33.000Z
2018-08-21T03:56:33.000Z
gnu/usr.bin/binutils/binutils/defparse.h
ArrogantWombatics/openbsd-src
75721e1d44322953075b7c4b89337b163a395291
[ "BSD-3-Clause" ]
null
null
null
#ifndef BISON_Y_TAB_H # define BISON_Y_TAB_H #ifndef YYSTYPE typedef union { char *id; int number; } yystype; # define YYSTYPE yystype # define YYSTYPE_IS_TRIVIAL 1 #endif # define NAME 257 # define LIBRARY 258 # define DESCRIPTION 259 # define STACKSIZE 260 # define HEAPSIZE 261 # define CODE 262 # define DATA 263 # define SECTIONS 264 # define EXPORTS 265 # define IMPORTS 266 # define VERSIONK 267 # define BASE 268 # define CONSTANT 269 # define READ 270 # define WRITE 271 # define EXECUTE 272 # define SHARED 273 # define NONSHARED 274 # define NONAME 275 # define PRIVATE 276 # define SINGLE 277 # define MULTIPLE 278 # define INITINSTANCE 279 # define INITGLOBAL 280 # define TERMINSTANCE 281 # define TERMGLOBAL 282 # define ID 283 # define NUMBER 284 extern YYSTYPE yylval; #endif /* not BISON_Y_TAB_H */
18.333333
30
0.758788
42a47ad25ba34cc4dcbf7fa930c19e8cd32dae0d
283
h
C
LMNote/LMNote/Store/LMNDraft.h
SheltonWan/Note
27b6e3221acdad88c15ad2f7ce95eaba88601c7b
[ "MIT" ]
211
2018-07-17T09:54:10.000Z
2022-03-10T07:58:51.000Z
LMNote/LMNote/Store/LMNDraft.h
mohsinalimat/LMNote
893c992511c06d8e4f3acaf1c0db75d20e2d0f3a
[ "MIT" ]
13
2018-07-21T03:36:59.000Z
2021-07-19T02:36:49.000Z
LMNote/LMNote/Store/LMNDraft.h
mohsinalimat/LMNote
893c992511c06d8e4f3acaf1c0db75d20e2d0f3a
[ "MIT" ]
44
2018-07-19T08:16:14.000Z
2022-03-07T09:11:20.000Z
// // LMNDraft.h // LMNote // // Created by littleMeaning on 2018/7/3. // Copyright © 2018年 littleMeaning. All rights reserved. // #import <LMNote/LMNote.h> @class LMNTextStorage; @interface LMNDraft : LMNItem @property (nonatomic, strong) LMNTextStorage *textStorage; @end
15.722222
58
0.713781
b6d629f2388d4f18a1419d6fd26dc4981f67b1d8
638
c
C
ds/nameres/rnr/setup/test/ghn.c
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
ds/nameres/rnr/setup/test/ghn.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
ds/nameres/rnr/setup/test/ghn.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#include <nt.h> #include <ntrtl.h> #include <nturtl.h> #include <windows.h> #include <winsock2.h> #include <wsipx.h> #include <svcguid.h> #include <nspapi.h> #include <stdio.h> #include <stdlib.h> #include <rpc.h> #include <rpcdce.h> _cdecl main(int argc, char **argv) { WSADATA wsaData; char hostName[256]; WSAStartup( MAKEWORD(1, 1), &wsaData ); if ( !gethostname( hostName, 256 ) ) { printf( "\nHost name is %s.\n", hostName ); } else { printf( "\nNo host name.\nError: %d", WSAGetLastError() ); } WSACleanup(); return( 0 ); }
16.789474
67
0.554859
b6fe29114e5a2eedfb88dd4017ae4e1bb9a3467e
196
h
C
src/utility/apple_script.h
ivan-volnov/vocabulary_builder
1515ee286194105ebe9d5b4f84eb6eb880ab7b1b
[ "MIT" ]
null
null
null
src/utility/apple_script.h
ivan-volnov/vocabulary_builder
1515ee286194105ebe9d5b4f84eb6eb880ab7b1b
[ "MIT" ]
null
null
null
src/utility/apple_script.h
ivan-volnov/vocabulary_builder
1515ee286194105ebe9d5b4f84eb6eb880ab7b1b
[ "MIT" ]
null
null
null
#ifndef APPLE_SCRIPT_H #define APPLE_SCRIPT_H #include <string> namespace AppleScript { bool run_apple_script(const std::string& script); } // namespace AppleScript #endif // APPLE_SCRIPT_H
14
49
0.77551
8e182e3bb93856a6e6c263742abeae575f45a6bb
10,898
c
C
packages/PIPS/newgen/src/genC/stack.c
DVSR1966/par4all
86b33ca9da736e832b568c5637a2381f360f1996
[ "MIT" ]
51
2015-01-31T01:51:39.000Z
2022-02-18T02:01:50.000Z
packages/PIPS/newgen/src/genC/stack.c
DVSR1966/par4all
86b33ca9da736e832b568c5637a2381f360f1996
[ "MIT" ]
7
2017-05-29T09:29:00.000Z
2019-03-11T16:01:39.000Z
packages/PIPS/newgen/src/genC/stack.c
DVSR1966/par4all
86b33ca9da736e832b568c5637a2381f360f1996
[ "MIT" ]
12
2015-03-26T08:05:38.000Z
2022-02-18T02:01:51.000Z
/* $Id$ Copyright 1989-2014 MINES ParisTech This file is part of NewGen. NewGen 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 any later version. NewGen 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 NewGen. If not, see <http://www.gnu.org/licenses/>. */ /* * STACK MANAGEMENT * * Fabien COELHO, 05/12/1994 * * Could be integrated in Newgen as a building type (as lists, mappings). * there is no actual need of such a type on the functional point of view. * I put it there since it may be much more efficient than lists. * Stack print out and read in functions would be needed. * (direction problem). * * More thoughts needed. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include <stdio.h> #include "genC.h" #include "newgen_include.h" /* STACK STRUCTURES */ /* the stack buckets, i.e. arrays containing the elements */ typedef struct __stack_bucket { size_t n_item; /* next available item in the bucket */ size_t max_items; /* the max number of items of this bucket */ void ** items; /* the items (only pointers at the moment) */ struct __stack_bucket *succ;/* the next bucket */ /* we could keep the previous bucket? */ } _stack_bucket, *_stack_ptr; /* the stack head */ typedef struct __stack_head { size_t size; /* current number of elements in stack */ size_t max_extent; /* maximum extension of the stack */ _stack_ptr stack;/* buckets in use by the stack */ _stack_ptr avail;/* allocated buckets not in use anymore */ size_t bucket_size; /* reference bucket size for allocation */ size_t n_buckets; /* number of allocated buckets */ int type; /* as BASIC, LIST, EXTERNAL, CHUNK, domain? */ int policy; /* may be used to indicate an allocation policy */ } _stack_head; /* and also *stack (in headers) */ /* usefull defines */ #define STACK_PTR_NULL ((_stack_ptr) NULL) #define STACK_PTR_NULL_P(x) ((x)==STACK_PTR_NULL) #define STACK_DEFAULT_SIZE 50 /* STACK ITERATOR */ typedef struct __stack_iterator { _stack_ptr bucket; /* current bucket */ bool downward; /* true if downward iterations */ size_t index; /* current index in bucket */ _stack_ptr list; /* all buckets */ } _stack_iterator; /* and also *stack_iterator (in headers) */ static void update_iterator_upward(stack_iterator i) { _stack_ptr x=i->list; while(!STACK_PTR_NULL_P(x) && x->succ!=i->bucket) x=x->succ; i->bucket=x, i->index=0; if (x && i->bucket->n_item==0) i->bucket = STACK_PTR_NULL; } #define STACK_ITERATOR_END_P(i) STACK_PTR_NULL_P(i->bucket) #define DEFINE_ITERATOR(i,blk,idx,dwn,lst) \ { \ i->bucket=(blk); \ i->index=(idx); \ i->list=lst; \ i->downward=dwn; \ } #define UPDATE_ITERATOR_DOWNWARD(i) \ if (i->index == (size_t) -1) \ { \ i->bucket = i->bucket->succ; \ i->index = (i->bucket) ? (i->bucket->n_item)-1 : (size_t) -1; \ } #define UPDATE_ITERATOR_UPWARD(i) \ if (i->index==i->bucket->n_item) \ update_iterator_upward(i); #define NEXT_ITERATION(i) \ if (i->downward) \ { \ i->index--; UPDATE_ITERATOR_DOWNWARD(i); \ } \ else \ { \ i->index++; UPDATE_ITERATOR_UPWARD(i); \ } static void stack_iterator_internal_init (const stack s, int down, stack_iterator i) { STACK_CHECK(s); if ((s->size)==0) DEFINE_ITERATOR(i, STACK_PTR_NULL, -1, down, STACK_PTR_NULL) else { if (down) { DEFINE_ITERATOR(i, s->stack, (s->stack->n_item)-1, down, s->stack); UPDATE_ITERATOR_DOWNWARD(i); } else { DEFINE_ITERATOR(i, STACK_PTR_NULL, 0, down, s->stack); update_iterator_upward(i); /* NOT the define! */ } } } stack_iterator stack_iterator_init(const stack s, bool down) { stack_iterator i = (stack_iterator) malloc(sizeof(_stack_iterator)); stack_iterator_internal_init(s, down, i); return i; } bool stack_iterator_next_and_go(stack_iterator i, void ** pitem) { if (STACK_ITERATOR_END_P(i)) { *pitem = (void*) NULL; return false; } else { *pitem = (i->bucket->items)[i->index]; NEXT_ITERATION(i); return true; } } bool stack_iterator_end_p(stack_iterator i) { return STACK_ITERATOR_END_P(i); } void stack_iterator_end(stack_iterator * pi) { (*pi)->bucket = NEWGEN_FREED; (*pi)->downward = 0; (*pi)->index = 0; (*pi)->list = NEWGEN_FREED; free(*pi); *pi=(stack_iterator) NULL; } /* * STACK ALLOCATION * */ /* allocates a bucket of size size */ static _stack_ptr allocate_bucket(int size) { _stack_ptr x = (_stack_ptr) malloc(sizeof(_stack_bucket)); message_assert("pointer was allocated", x); x->n_item = 0; x->max_items = size; x->items = (void **) malloc(sizeof(void *)*size); message_assert("pointer was allocated", x->items); x->succ = STACK_PTR_NULL; return x; } /* search for a new bucket, first in the available list, * if none are available, a new bucket is allocated */ static _stack_ptr find_or_allocate(stack s) { if (!STACK_PTR_NULL_P(s->avail)) { _stack_ptr x = s->avail; s->avail = (s->avail)->succ; x->succ = STACK_PTR_NULL; /* clean the bucket to be returned */ return x; } else { s->n_buckets++; /* may depend from the policy? */ return allocate_bucket(s->bucket_size); } } /* ALLOCATEs a new stack of @p type @param type record newgen domain of stack contents. should be used to check the type of appended elements. @param bucket_size is the number of elements in the elemental stack container. If you now you will have big stacks, try big numbers here to save memory. @param policy not used, 0 is fine. */ stack stack_make(int type, int bucket_size, int policy) { stack s = (stack) malloc(sizeof(_stack_head)); message_assert("pointer was allocated", s); if (bucket_size<10) bucket_size=STACK_DEFAULT_SIZE; /* not too small */ s->size = 0; s->type = type; s->policy = policy; /* not used */ s->bucket_size = bucket_size; s->max_extent = 0; s->n_buckets = 0; s->stack = allocate_bucket(bucket_size); s->avail = STACK_PTR_NULL; return s; } /* duplicate a stack with its contents. */ stack stack_copy(const stack s) { stack n = stack_make(s->type, s->bucket_size, s->policy); STACK_MAP_X(i, void*, stack_push(i, n), s, 0); return n; } /* FREEs the stack */ static void free_bucket(_stack_ptr x) { gen_free_area(x->items, x->max_items*sizeof(void*)); gen_free_area((void**) x, sizeof(_stack_bucket)); } static void free_buckets(_stack_ptr x) { _stack_ptr tmp; while(!STACK_PTR_NULL_P(x)) { tmp=x, x=x->succ, tmp->succ=STACK_PTR_NULL; free_bucket(tmp); } } void stack_free(stack * ps) { free_buckets((*ps)->stack), (*ps)->stack=STACK_PTR_NULL; free_buckets((*ps)->avail), (*ps)->avail=STACK_PTR_NULL; gen_free_area((void**) *ps, sizeof(stack_head)); *ps = STACK_NULL; } /* STACK MISCELLANEOUS */ #define STACK_OBSERVER(name, what) \ int stack_##name(const stack s) { STACK_CHECK(s); return(what); } /* Here we define stack_size(), stack_bsize(), stack_policy() and stack_max_extent(): */ STACK_OBSERVER(size, s->size) STACK_OBSERVER(bsize, s->bucket_size) STACK_OBSERVER(policy, s->policy) STACK_OBSERVER(max_extent, s->max_extent) STACK_OBSERVER(consistent_p, 1) /* well, it is not implemented */ bool stack_empty_p(const stack s) { STACK_CHECK(s); return s->size==0; } #undef STACK_OBSERVER /* APPLY f to all items of stack s; */ void stack_map(const stack s, gen_iter_func_t f) { _stack_ptr x; int i; STACK_CHECK(s); for(x=s->stack; x!=NULL; x=x->succ) for(i=(x->n_item)-1; i>=0; i--) (*f)(x->items[i]); } static int number_of_buckets(_stack_ptr x) { int n=0; for(; !STACK_PTR_NULL_P(x); x=x->succ, n++); return n; } void stack_info(FILE * f, const stack s) { fprintf(f, "stack_info about stack %p\n", s); if (STACK_NULL_P(s)) { fprintf(f, " - is null\n"); return; } /* else */ if (stack_undefined_p(s)) { fprintf(f, " - is undefined\n"); return; } /* else */ fprintf(f, " - type %d, size %zd, max extent %zd\n", s->type, s->size, s->max_extent); fprintf(f, " - buckets: %d in use, %d available\n", number_of_buckets(s->stack), number_of_buckets(s->avail)); } /* STACK USE */ /* PUSHes the item on stack s * * a new bucket is allocated if necessary. * the size it the same than the initial bucket size. * Other policies may be considered. */ void stack_push(void * item, stack s) { _stack_ptr x = s->stack; assert(!STACK_PTR_NULL_P(x)); if (x->n_item == x->max_items) { _stack_ptr saved = x; x = find_or_allocate(s); x->succ = saved; s->stack = x; } /* PUSH! */ s->size++; if (s->size > s->max_extent) s->max_extent = s->size; x->items[x->n_item++] = item; } /* POPs one item from stack s * * the empty buckets are not freed here. * stack_free does the job. */ void *stack_pop(stack s) { _stack_ptr x = s->stack; if (x->n_item==0) { _stack_ptr saved = x->succ; x->succ = s->avail, s->avail = x; s->stack = saved, x = saved; } assert(!STACK_PTR_NULL_P(x) && x->n_item>0); /* POP! */ s->size--; return x->items[--x->n_item]; } /* returns the item on top of stack s */ void *stack_head(const stack s) { _stack_ptr x = s->stack; if (x->n_item==0) x = x->succ; assert(!STACK_PTR_NULL_P(x) && x->n_item>0); /* HEAD */ return x->items[(x->n_item)-1]; } /* returns the nth item starting from the head and counting from 1, when possible, or NULL, elsewhere. stack_nth(stack,1)==stack_head(stack) if stack_size(stack)>=1. */ void *stack_nth(const stack s, int nskip) { void * value = NULL; message_assert("positive nskip", nskip>=0); // message_assert("deep enough stack", stack_size(s)>=nskip); _stack_iterator si; stack_iterator_internal_init(s, true, &si); while (nskip && stack_iterator_next_and_go(&si, &value)) nskip--; return value; } /* REPLACEs the item on top of stack s, and returns the old item */ void *stack_replace(void * item, stack s) { _stack_ptr x = s->stack; void *old; if (x->n_item==0) x = x->succ; assert(!STACK_PTR_NULL_P(x) && x->n_item>0); /* REPLACE */ old = x->items[(x->n_item)-1]; x->items[(x->n_item)-1] = item; return old; } /* that is all */
23.236674
78
0.646908
0683bf449e054709e00566db4c231235b1b5591a
2,132
h
C
+hidi/Sensor.h
dddvision/functionalnavigation
1e2e9688072418ab441669ff8a09ae33e60cd9e1
[ "Unlicense", "MIT" ]
3
2016-09-06T03:09:45.000Z
2021-01-20T06:03:50.000Z
+hidi/Sensor.h
dddvision/functionalnavigation
1e2e9688072418ab441669ff8a09ae33e60cd9e1
[ "Unlicense", "MIT" ]
null
null
null
+hidi/Sensor.h
dddvision/functionalnavigation
1e2e9688072418ab441669ff8a09ae33e60cd9e1
[ "Unlicense", "MIT" ]
4
2015-03-14T21:55:19.000Z
2021-05-02T19:34:52.000Z
// Copyright 2011 Scientific Systems Company Inc., New BSD License #ifndef HIDISENSOR_H #define HIDISENSOR_H #include "hidi.h" namespace hidi { /** * This class defines methods shared by synchronously time-stamped sensors. * * @note * All sensors use SI units and radians unless otherwise stated. */ class Sensor { private: /** * Prevents deep copying. */ Sensor(const Sensor&); /** * Prevents assignment. */ Sensor& operator=(const Sensor&); protected: /** * Protected constructor. */ Sensor(void) {} public: /** * Incorporate new data and allow old data to expire. * * @note * This function updates the object state without waiting for new data to be acquired. */ virtual void refresh(void) = 0; /** * Check whether data is available. * * @return true if any data is available and false otherwise */ virtual bool hasData(void) = 0; /** * Return index to the first data node. * * @return index to first node * * @note * Throws an exception if no data is available. */ virtual uint32_t first(void) = 0; /** * Return index to the last data node. * * @return index to last node * * @note * Throws an exception if no data is available. */ virtual uint32_t last(void) = 0; /** * Get GPS equivalent time stamp at a node. * * @param[in] node index of a node (MATLAB: M-by-N) * @return time stamp at the node (MATLAB: M-by-N) * * @note * GPS time is measured from the prime meridian in seconds since 1980 JAN 06 T00:00:00. * GPS time may be a few seconds ahead of UTC. * Time stamps must not decrease with increasing indices. * Throws an exception if any index is out of range. */ virtual double getTime(const uint32_t& node) = 0; /** * Virtual base class destructor. */ virtual ~Sensor(void) {} }; } #endif
22.680851
92
0.567542
06a58d9e9859dbfb7cd1dbc481233d98aebcf554
426
h
C
ThereminiOS/Synthesizer/Classes/VWW/VWWSynthesizerNotes.h
SmallPlanetiOS/theremin-
de4483f5c07f1b6e32dd0d74d683589627296824
[ "AML" ]
1
2019-03-21T06:30:23.000Z
2019-03-21T06:30:23.000Z
ThereminiOS/Synthesizer/Classes/VWW/VWWSynthesizerNotes.h
SmallPlanetiOS/theremin-
de4483f5c07f1b6e32dd0d74d683589627296824
[ "AML" ]
null
null
null
ThereminiOS/Synthesizer/Classes/VWW/VWWSynthesizerNotes.h
SmallPlanetiOS/theremin-
de4483f5c07f1b6e32dd0d74d683589627296824
[ "AML" ]
null
null
null
// // VWWSynthesizerNotes.h // Synthesizer // // Created by Zakk Hoyt on 8/12/12. // Copyright (c) 2012 Zakk Hoyt. All rights reserved. // #import <Foundation/Foundation.h> #import "VWWSynthesizerTypes.h" @interface VWWSynthesizerNotes : NSObject +(VWWSynthesizerNotes *)sharedInstance; +(float)getClosestNoteForFrequency:(float)frequency; +(float)getClosestNoteForFrequency:(float)frequency inKey:(VWWKeyType)key; @end
25.058824
74
0.767606
06aa36bae4014d818bdee61c1692a34e81483f25
966
h
C
inc/kos_error.h
kos-lang/kos
0f8dac3f1006dbf79e5cf7d918264a1804d78f72
[ "MIT" ]
12
2017-01-01T20:29:32.000Z
2022-03-29T21:03:11.000Z
inc/kos_error.h
kos-lang/kos
0f8dac3f1006dbf79e5cf7d918264a1804d78f72
[ "MIT" ]
18
2016-09-16T18:16:05.000Z
2019-11-06T22:26:07.000Z
inc/kos_error.h
kos-lang/kos
0f8dac3f1006dbf79e5cf7d918264a1804d78f72
[ "MIT" ]
null
null
null
/* SPDX-License-Identifier: MIT * Copyright (c) 2014-2021 Chris Dragan */ #ifndef KOS_ERROR_H_INCLUDED #define KOS_ERROR_H_INCLUDED enum KOS_ERROR_E { KOS_SUCCESS, KOS_SUCCESS_RETURN, /* auxiliary, not an error */ KOS_ERROR_INTERNAL, KOS_ERROR_EXCEPTION, KOS_ERROR_OUT_OF_MEMORY, KOS_ERROR_NOT_FOUND, KOS_ERROR_NO_DIRECTORY, KOS_ERROR_ERRNO, /* read errno to get error code */ KOS_ERROR_SETTER, /* property has a setter */ KOS_ERROR_SCANNING_FAILED, KOS_ERROR_PARSE_FAILED, KOS_ERROR_COMPILE_FAILED, KOS_ERROR_INVALID_UTF8_CHARACTER, KOS_ERROR_INTERRUPTED, KOS_ERROR_INVALID_EXPONENT, KOS_ERROR_EXPONENT_OUT_OF_RANGE, KOS_ERROR_NUMBER_TOO_BIG, KOS_ERROR_INTEGER_EXPECTED, KOS_ERROR_INVALID_NUMBER, KOS_ERROR_LAST_ERROR, /* GetLastError (Windows only) */ KOS_ERROR_NO_VIRTUAL_TERMINAL }; #endif
29.272727
78
0.696687
059347bf0909676e36bdb9c53bb4024c4ce3c1e1
6,309
c
C
orte/mca/schizo/singularity/schizo_singularity.c
ICLDisco/SCON_Prototype
69841e27f0079b21d1f930655678a6183af3282f
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
orte/mca/schizo/singularity/schizo_singularity.c
ICLDisco/SCON_Prototype
69841e27f0079b21d1f930655678a6183af3282f
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
orte/mca/schizo/singularity/schizo_singularity.c
ICLDisco/SCON_Prototype
69841e27f0079b21d1f930655678a6183af3282f
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
/* * Copyright (c) 2016 Intel, Inc. All rights reserved. * $COPYRIGHT$ * * Additional copyrights may follow * * $HEADER$ * */ #include "orte_config.h" #include "orte/types.h" #include "opal/types.h" #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include <ctype.h> #include "opal/util/argv.h" #include "opal/util/basename.h" #include "opal/util/opal_environ.h" #include "opal/util/os_dirpath.h" #include "opal/util/path.h" #include "orte/runtime/orte_globals.h" #include "orte/util/name_fns.h" #include "orte/mca/schizo/base/base.h" #include "schizo_singularity.h" static int setup_app(char **personality, orte_app_context_t *context); static int setup_fork(orte_job_t *jdata, orte_app_context_t *context); orte_schizo_base_module_t orte_schizo_singularity_module = { .setup_app = setup_app, .setup_fork = setup_fork }; static int setup_app(char **personality, orte_app_context_t *app) { int i; char *newenv, *pth, *t2; bool takeus = false; /* see if we are included */ for (i=0; NULL != personality[i]; i++) { if (0 == strcmp(personality[i], "singularity")) { takeus = true; break; } } if (!takeus) { /* even if they didn't specify, check to see if * this involves a singularity container */ if (0 != strcmp(app->argv[0],"singularity") && 0 != strcmp(app->argv[0],"sapprun") && NULL == strstr(app->argv[0], ".sapp")) { /* guess not! */ return ORTE_ERR_TAKE_NEXT_OPTION; } } opal_output_verbose(1, orte_schizo_base_framework.framework_output, "%s schizo:singularity: checking app %s", ORTE_NAME_PRINT(ORTE_PROC_MY_NAME), app->argv[0]); if (0 < strlen(OPAL_SINGULARITY_PATH)) { asprintf(&pth, "%s/singularity", OPAL_SINGULARITY_PATH); } else { /* since we allow for detecting singularity's presence, it * is possible that we found it in the PATH, but not in a * standard location. Check for that here */ pth = opal_path_findv("singularity", X_OK, app->env, NULL); if (NULL == pth) { /* cannot execute */ return ORTE_ERR_TAKE_NEXT_OPTION; } } /* find the path and prepend it with the path to Singularity */ for (i = 0; NULL != app->env && NULL != app->env[i]; ++i) { /* add to PATH */ if (0 == strncmp("PATH=", app->env[i], 5)) { t2 = opal_dirname(pth); asprintf(&newenv, "%s:%s", t2, app->env[i] + 5); opal_setenv("PATH", newenv, true, &app->env); free(newenv); free(t2); break; } } free(pth); if (0 == strcmp(app->argv[0], "singularity")) { /* we don't want the backend to setup a cache dir */ orte_set_attribute(&app->attributes, ORTE_APP_NO_CACHEDIR, ORTE_ATTR_GLOBAL, NULL, OPAL_BOOL); } /* export an envar to permit shared memory operations */ opal_setenv("SINGULARITY_NO_NAMESPACE_PID", "1", true, &app->env); return ORTE_SUCCESS; } static int setup_fork(orte_job_t *jdata, orte_app_context_t *app) { int i; bool takeus = false; char *p, *t2; char dir[MAXPATHLEN]; /* see if we are included */ for (i=0; NULL != jdata->personality[i]; i++) { if (0 == strcmp(jdata->personality[i], "singularity")) { takeus = true; break; } } if (!takeus) { /* even if they didn't specify, check to see if * this involves a singularity container */ if (0 != strcmp(app->argv[0],"singularity") && 0 != strcmp(app->argv[0],"sapprun") && NULL == strstr(app->argv[0], ".sapp")) { /* guess not! */ return ORTE_ERR_TAKE_NEXT_OPTION; } } /* set the singularity cache dir, unless asked not to do so */ if (!orte_get_attribute(&app->attributes, ORTE_APP_NO_CACHEDIR, NULL, OPAL_BOOL)) { opal_setenv("SINGULARITY_CACHEDIR", orte_process_info.job_session_dir, true, &app->env); opal_setenv("SINGULARITY_CACHEDIR", orte_process_info.job_session_dir, true, &environ); } /* save our current directory */ getcwd(dir, sizeof(dir)); /* change to the working directory for this context */ chdir(app->cwd); /* if the app contains .sapp, then we need to strip that * extension so singularity doesn't bark at us */ if (NULL != strstr(app->argv[0], ".sapp")) { /* ensure the app is installed */ opal_output_verbose(1, orte_schizo_base_framework.framework_output, "%s schizo:singularity: installing app %s", ORTE_NAME_PRINT(ORTE_PROC_MY_NAME), app->argv[0]); t2 = opal_basename(app->argv[0]); p = strstr(t2, ".sapp"); *p = '\0'; // strip the extension if (0 < opal_output_get_verbosity(orte_schizo_base_framework.framework_output)) { (void)asprintf(&p, "singularity -vv install --runkey %s %s", t2, app->argv[0]); } else { (void)asprintf(&p, "singularity --quiet install --runkey %s %s", t2, app->argv[0]); } system(p); free(p); free(app->argv[0]); app->argv[0] = t2; } /* ensure that we use "singularity run" to execute this app */ if (0 != strcmp(app->app, "singularity")) { opal_output_verbose(1, orte_schizo_base_framework.framework_output, "%s schizo:singularity: adding singularity cmd", ORTE_NAME_PRINT(ORTE_PROC_MY_NAME)); /* change the app to the "singularity" command */ free(app->app); app->app = strdup("singularity"); opal_argv_prepend_nosize(&app->argv, "run"); if (0 < opal_output_get_verbosity(orte_schizo_base_framework.framework_output)) { opal_argv_prepend_nosize(&app->argv, "-vv"); } else { opal_argv_prepend_nosize(&app->argv, "--quiet"); } opal_argv_prepend_nosize(&app->argv, "singularity"); } /* return to the original directory */ chdir(dir); return ORTE_SUCCESS; }
33.205263
102
0.582343
5ecb6a416524e5bb784f42ea7936f38b916819d5
1,490
h
C
Warcraft II/Warcraft II/EnemyCannonTower.h
DevCrumbs/Warcraft-II
fd4fab4c629783d6acc18c34bdaac15fcfb54dd1
[ "MIT" ]
9
2019-07-02T06:24:03.000Z
2022-03-18T20:07:02.000Z
Warcraft II/Warcraft II/EnemyCannonTower.h
DevCrumbs/Warcraft-II
fd4fab4c629783d6acc18c34bdaac15fcfb54dd1
[ "MIT" ]
109
2018-02-21T23:40:29.000Z
2020-04-25T18:26:41.000Z
Warcraft II/Warcraft II/EnemyCannonTower.h
DevCrumbs/Warcraft-II
fd4fab4c629783d6acc18c34bdaac15fcfb54dd1
[ "MIT" ]
6
2018-06-27T07:30:10.000Z
2020-03-09T19:18:41.000Z
#ifndef __EnemyCannonTower_H__ #define __EnemyCannonTower_H__ #include "StaticEntity.h" #include <list> struct EnemyCannonTowerInfo { SDL_Rect completeTexArea = { 0,0,0,0 }; iPoint size{ 0,0 }; uint life = 0u; float speed = 0.0f; uint sightRadius = 0; uint damage = 0; uint attackWaitTime = 0; uint arrowSpeed = 0; }; class EnemyCannonTower :public StaticEntity { public: EnemyCannonTower(fPoint pos, iPoint size, int currLife, uint maxLife, const EnemyCannonTowerInfo& enemyCannonTowerInfo, j1Module* listener); ~EnemyCannonTower(); void Move(float dt); void OnCollision(ColliderGroup* c1, ColliderGroup* c2, CollisionState collisionState); // State machine void TowerStateMachine(float dt); //Cannon bullet void CreateCannonBullet(); private: EnemyCannonTowerInfo enemyCannonTowerInfo; EntitiesEvent EntityEvent = EntitiesEvent_CREATED; TowerState towerState = TowerState_Idle; //Attack Entity* attackingTarget = nullptr; float attackTimer = 0.0f; std::list<Entity*> enemyAttackList; //Cannon bullet Particle* cannonParticle = nullptr; // Reconstruction Particle* peon = nullptr; float secondsReconstruction = 0.0f; float startReconstructionTimer = 0.0f; float inProgressReconstructionTimer = 0.0f; bool isRestartReconstructionTimer = false; bool isStartReconstructionTimer = false; bool isInProgressReconstructionTimer = false; BuildingState buildingStateBeforeReconstruction = BuildingState_NoState; }; #endif //__EnemyCannonTower_H__
22.923077
141
0.780537
bafab54c3d6c47d130f6c0d0ad705f10af60dd26
71
h
C
include/iupcells.h
LuaDist/iup
d19be94945cd9d9816252b4002607cf42c60c08b
[ "MIT" ]
68
2015-01-21T11:06:38.000Z
2022-03-18T11:01:40.000Z
include/iuptree.h
Archs/luajit-aio
79402e0b0d2da16a13e01644fd9cf7010ae72903
[ "MIT" ]
null
null
null
include/iuptree.h
Archs/luajit-aio
79402e0b0d2da16a13e01644fd9cf7010ae72903
[ "MIT" ]
17
2015-01-08T16:38:03.000Z
2022-01-20T15:00:57.000Z
/* dummy header for backward compatibility */ #include <iupcontrols.h>
23.666667
45
0.760563
c78b3b8847888c5b5c12a52e1893b5352b8e6ded
6,939
c
C
components/amp/engine/quickjs_engine/addons/utils/ui/page_entry.c
wstong999/AliOS-Things
6554769cb5b797e28a30a4aa89b3f4cb2ef2f5d9
[ "Apache-2.0" ]
4,538
2017-10-20T05:19:03.000Z
2022-03-30T02:29:30.000Z
components/amp/engine/quickjs_engine/addons/utils/ui/page_entry.c
wstong999/AliOS-Things
6554769cb5b797e28a30a4aa89b3f4cb2ef2f5d9
[ "Apache-2.0" ]
1,088
2017-10-21T07:57:22.000Z
2022-03-31T08:15:49.000Z
components/amp/engine/quickjs_engine/addons/utils/ui/page_entry.c
wstong999/AliOS-Things
6554769cb5b797e28a30a4aa89b3f4cb2ef2f5d9
[ "Apache-2.0" ]
1,860
2017-10-20T05:22:35.000Z
2022-03-27T10:54:14.000Z
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #ifdef AMP_ADVANCED_ADDON_UI #include "aos_fs.h" #include "aos_system.h" #include "amp_config.h" #include "amp_defines.h" #include "amp_task.h" #include "board_mgr.h" #include "quickjs.h" #include "cJSON.h" #include "page_entry.h" #include "render.h" #include "quickjs_addon_common.h" #define MOD_STR "APPENTRY" //static dlist_t g_pages_list; static JSClassID js_page_entry_class_id; extern char g_app_path[128]; extern amp_app_desc_t g_app; char app_file_path[128]; int search_js_page_entry(amp_app_desc_t *app) { int i; int size; cJSON *root = NULL; cJSON *item = NULL; cJSON *temp = NULL; void *json_data = NULL; void * js_app_fd = NULL; int file_len = 0; int json_fd = -1; page_desc_t *page; if (app == NULL) { return -1; } snprintf(app_file_path, 128, AMP_APP_MAIN_JSON); /* cannot find the index.js int current dir */ if ((json_fd = aos_open(app_file_path, O_RDONLY)) < 0) { amp_error(MOD_STR, "cannot find the file :%s", app_file_path); return -1; } /* read package config file to json_data buffer */ file_len = aos_lseek(json_fd, 0, SEEK_END); printf("%s %d\r\n", __func__, file_len); json_data = aos_calloc(1, sizeof(char) * (file_len + 1)); if (NULL == json_data) { aos_close(json_fd); json_fd = -1; return -1; } aos_lseek(json_fd, 0, SEEK_SET); aos_read(json_fd, json_data, file_len); aos_close(json_fd); /* parser the package json data */ root = cJSON_Parse(json_data); if (NULL == root) { aos_free(json_data); amp_error(MOD_STR, "cJSON_Parse failed"); return -1; } item = cJSON_GetObjectItem(root, "pages"); if (item == NULL) { return -1; } size = cJSON_GetArraySize(item); app->page = aos_malloc(sizeof(page_desc_t) * size); if (NULL == app->page) { return -1; } memset(app->page, 0, sizeof(page_desc_t) * size); app->num = size; app->cur_page = 0; for (i = 0; i < size; i++) { page = &app->page[i]; page->index = i; temp = cJSON_GetArrayItem(item, i); if(NULL == temp ) { continue; } //strncpy(page->path, temp->valuestring, 64); //printf("temp->valuestring == %s\n\r",temp->valuestring); snprintf(page->path, 64, "%s", temp->valuestring); snprintf(page->css_file, 128, "%s%s", temp->valuestring, ".css"); snprintf(page->xml_file, 128, "%s%s", temp->valuestring, ".xml"); snprintf(page->js_file, 128, "%s%s", temp->valuestring, ".js"); } aos_free(json_data); cJSON_Delete(root); return 0; } void page_config_parse() { memset(&g_app, 0, sizeof(g_app)); search_js_page_entry(&g_app); } page_options_t* page_get_cur_options(void) { int index; if (g_app.cur_page >= g_app.num) { return NULL; } index = g_app.cur_page; return &(g_app.page[index].options); } static int page_add_options(page_options_t *options) { int index; if (options == NULL) { return -1; } if (g_app.cur_page >= g_app.num) { return -1; } index = g_app.cur_page; g_app.page[index].options.object = options->object; g_app.page[index].options.data = options->data; g_app.page[index].options.on_show = options->on_show; g_app.page[index].options.on_update = options->on_update; g_app.page[index].options.on_exit = options->on_exit; return 0; } /* App(Object options) entry */ static JSValue native_page_entry(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { int i; int ret; page_options_t page_options; JSValue irq_cb = argv[0]; /* check paramters */ if (!JS_IsObject(irq_cb)) { return JS_ThrowTypeError(ctx, "not a object"); } memset(&page_options, 0, sizeof(page_options_t)); /* get options object */ //duk_dup(ctx, -1); page_options.object = JS_DupValue(ctx, irq_cb); /* find data */ if (JS_GetPropertyStr(ctx, argv[0], "data")) { amp_debug(MOD_STR, "find Page#data()"); page_options.data = JS_DupValue(ctx, irq_cb); } /* find onShow() */ //if (duk_get_prop_string(ctx, 0, "onShow")) if (JS_GetPropertyStr(ctx, argv[0], "onShow")) { amp_debug(MOD_STR, "find Page#onShow()"); page_options.on_show = JS_DupValue(ctx, irq_cb); } /* find onUpdate() */ if (JS_GetPropertyStr(ctx, argv[0], "onUpdate")) { amp_debug(MOD_STR, "find Page#onUpdate()"); page_options.on_update = JS_DupValue(ctx, irq_cb); } /* find onExit() */ if (JS_GetPropertyStr(ctx, argv[0], "onExit")) { amp_debug(MOD_STR, "find Page#onExit()"); page_options.on_exit = JS_DupValue(ctx, irq_cb); } /* one-by-one insert into page list */ ret = page_add_options(&page_options); // amp_task_schedule_call(page_entry, NULL); return 1; } void page_entry(void *para) { page_options_t *options; JSContext *ctx = js_get_context(); options = page_get_cur_options(); if (options == NULL) { return; } /* onShow hook */ uint32_t value = 0; JSValue val = JS_Call(ctx, options->on_show, JS_UNDEFINED, 1, &value); JS_FreeValue(ctx, val); } void page_exit(void *para) { page_options_t *options; JSContext *ctx = js_get_context(); options = page_get_cur_options(); if (options == NULL) { amp_debug("page", "%s : %d---------------------------------", __func__, __LINE__); return; } /* onShow hook */ uint32_t value = 0; JSValue val = JS_Call(ctx, options->on_exit, JS_UNDEFINED, 1, &value); JS_FreeValue(ctx, val); JS_FreeValue(ctx, options->object); } void page_update(void *para) { page_options_t *options; JSContext *ctx = js_get_context(); options = page_get_cur_options(); if (options == NULL) { return; } /* onShow hook */ uint32_t value = 0; JSValue val = JS_Call(ctx, options->on_update, JS_UNDEFINED, 1, &value); JS_FreeValue(ctx, val); } static JSClassDef js_page_entry_class = { "APPENTRY", }; static int js_page_entry_init(JSContext *ctx) { JSValue proto; JS_NewClassID(&js_page_entry_class_id); JS_NewClass(JS_GetRuntime(ctx), js_page_entry_class_id, &js_page_entry_class); proto = JS_NewObject(ctx); JS_SetClassProto(ctx, js_page_entry_class_id, proto); return; } void page_entry_register(void) { amp_debug(MOD_STR, "module_page_entry_register"); JSContext *ctx = js_get_context(); aos_printf("module page_entry register\n"); js_page_entry_init(ctx); QUICKJS_GLOBAL_FUNC("Page", native_page_entry); } #endif
22.676471
90
0.613633
22ea3117d37df63494c6819b2621a3cc5dd5126e
453
h
C
cppLib/code/ECS/MovementSystem.h
DrYaling/ProcedureContentGenerationForUnity
3c4f1e70b01e4fe2b9f847324b60b15016b9a740
[ "MIT" ]
3
2019-05-14T07:19:59.000Z
2019-05-14T08:08:25.000Z
cppLib/code/ECS/MovementSystem.h
DrYaling/ProcedureContentGenerationForUnity
3c4f1e70b01e4fe2b9f847324b60b15016b9a740
[ "MIT" ]
null
null
null
cppLib/code/ECS/MovementSystem.h
DrYaling/ProcedureContentGenerationForUnity
3c4f1e70b01e4fe2b9f847324b60b15016b9a740
[ "MIT" ]
1
2018-08-08T07:39:16.000Z
2018-08-08T07:39:16.000Z
#ifndef Movement_system_h #define Movement_system_h #include "ISystem.h" #include "MovementComponent.h" namespace ecs { //test code class MovementSystem :public System<MovementComponent>, public ISystem { typedef System base; public: MovementSystem(); MovementSystem(const MovementSystem& copy) { LogError("wow!its here!"); } ~MovementSystem(); SystemCatalog GetCatalog()override; void OnUpdate(int32_t time_diff) override; }; } #endif
22.65
75
0.761589
b3c49192d44b45ef7768a7e8a9097c40261263d1
13,354
c
C
ARIS/boot/synergy/ssp/src/framework/el/tx/tx_src/tx_trace_user_event_insert.c
arrow-acs/acn-embedded
b31d4cf2055f8809fa7b80ec80703402fc09001e
[ "Apache-2.0" ]
7
2017-03-27T01:08:22.000Z
2019-08-20T18:29:03.000Z
ARIS/boot/synergy/ssp/src/framework/el/tx/tx_src/tx_trace_user_event_insert.c
konexios/moonstone-acn-embedded
b31d4cf2055f8809fa7b80ec80703402fc09001e
[ "Apache-2.0" ]
5
2017-11-10T23:09:50.000Z
2018-04-04T13:58:31.000Z
ARIS/boot/synergy/ssp/src/framework/el/tx/tx_src/tx_trace_user_event_insert.c
konexios/moonstone-acn-embedded
b31d4cf2055f8809fa7b80ec80703402fc09001e
[ "Apache-2.0" ]
5
2017-03-29T02:15:10.000Z
2019-02-22T13:09:42.000Z
#ifdef AMS_ENCRYPT_PACKAGE -----BEGIN ENCRYPTED FILE v0.6----- 9S04Fc0roaJnwZGP6OG7EDBImvEWKQdoMQNOXjk4ZvxTSJPk3yRkrUfzmivV40+I O5vHVn/TuiHbeSlU7Ltzuziq3KyX1LWuZApe52bi2PBeKHgRQZdFXiWNORU0eM+n PH+CDPVdK0ogppE3K88d1jrItxceIdNOCejL5x2RIpafg/4NqaPKqlX/YKe+9Fww YuadrmMSB1EAl2gGzkPQoieqRZC823VULF94oAFX0LZwElXISq3q63+GiG0httxW fgQB+1r8gVKDoZGhlZolUVE4M85/MLpf3VqSOY5fqQWe6yZ05SSLBjZ/i4ziOi7Q 7/A5kalrtE2edu4mMY43+sWL+hSgXqDo3BcMSaiYSdt/bxK9jwAoXCI0d4r19Q14 nwwv9aozkDkNhdGW8BFwaZFBw2769HdBOGm02dk+xwi4Y/9fCSPgHSZ9eB6lJ9/T JAS2FA4a29nXRrSlcnPY9Qm2X6jOlsUvOTOJ4M8xTmoOmnFUGFERP5GUPHKXDTRH ud8QNZZ4ePoizTT98CG0JX/IBp1YB3KczyRSOkP/4ROP+WyxBHaLkz2RNoIKomdI vIX/Gw65s0v6eozNr4nhWDX6H/Q4peJSfs/mzkLeZCbWIsANh7myASImZc/SM9pu Rp0wCeq6FYPGbf9nP6KgcWQENdICjkVK3GNORTcg2VVQraKty1iPYyuvhoncZtJ/ aCyiFrTvscZGik/Szo8h3JaqBJtAcdmjucFjOOgxtrdS610Vj7HyQeF7Q4qEnLse 7K2VLdOO569sDtAYUkIcIl/Gs03T1NVNXYC9GQfDRhCr890KxiYU+7iPjN0Qcps0 oRtOG50YCHEGJRIMLCpJVDYzeOwk873kOcw4n0OlmgMrU1Wc+/Z7D1nHvKfs799U DSByEBWETP6XdhS+BAtBTyKGEhHtgTXJQHFdmeDOtFoAWCyou81p6TYUCWHD60/J c+Y16lmn1+5dc6vtTwRX6i5KCx19Ze7LlwbaGkUlPP8bHtAgNLjNSpWtT/HN6k+v n/Xz0f09aEuDXQmXTMWh6V8pOuCxjvmtVOeEASlhFSEGuoIxz3F4swR5NXi+29rx EE/Ei4sQzn7ws8ePSHh+tK95jmw+cPUpaG2AUtycqfor57RgLuM9sMefWPjY5/6U uxv5GSS3Wr8g+0flu7SgXvwP3aRZfbngtdt5u9+aM3bX66+Rnek1ialGneUSBi6+ Qeh/+05ygf2HdNwBp3WNJybDwmeGAw2XvYCg1mTi/BYN0pM/PV1xuFzZKWgB4TXz eLh4B3KDHQER5EBhMB+ahsIlHU13Gucg84ULyec6M9G/00RTuUPfzpCxnJfAXBi5 te2vlEeR3KxX/ZtG1RaFC1ICDC2r4IGGzMCq8iT8S6lAbvTwnJ08VJesdpM/UE2V TNl9L01Hu/l7tghtUfa65vWLPAVNyz8P7FmgICaM4hMmkUBSTezWrUkKWsOHdJPs Ez+8ZyAe5Z6/6GR5OzY+2Q3Q7409+dfwGYvaNDllduGEcDxKBy22KLhec/CWx5Pa ZZwL5lw5bhoc2EgZf0Hsvw0l8HbDTtKlJZSZgdqaDc3HBo2w69u63KiIfVmbD+at 6ShDITK5NzM0rPwiOmNhusGD5WDZZmGHDGY+7uata/vbhc8KY+2rcOv54fiuV1Ta rhI/wwZcUVghNuGQdbF8kXB59tQRi18tQNPEEg0LtbycZxDBUkOG6Naw85N01ZgJ Fu+iksjZA8LacS1mSAh/lCNJRQ46s6zTYmjShTlyA6UhSqiokb67cDPZcabaYzmw uuZg+yCI8p1DRwO3gsDfopBmKzIB7anQWGJfLx1x92kH/6abd4vZmg2UGLCwuL7e dK0BuJDj7gWDC8Qed8CetXhEJPsyqa0dYCwv7opIIhh3267oaI47gFc4r/2oeqCH 0VkwflmdB2QQX2LZxF7iYSpwM3WuNpNBVDvt7Bkfy7QdVRk4ivm96vXaYJ9q/9Ww 4MlwvzMSe4qiqSRBAGS/ynpLEdiM6/7+IT7mY7OB2BdXiy5vVH0H1iesLP1MAbJJ z0OZHoWSmCJNuAyZgB+GOYHVzBdSFw6P3W/GExoWJO/bx+AvD3mKxtqDMpt01fny lGXe65PvnlqVaced6u2ZkGbgllMS28LQT8kNH60qwNND48BCOlXLxPJ4nz915UWw 1jV32qmB5N9eP9hyM1AT+jUsWMROeDJGEuBQn1koKvlrJ9vbrf2MTlFSiuczYGiT CvlPzKqT5O4J9RGpPYS0zIotKE9b59qDlFMoznTAXqNfOQ9OQIXoaIeJznUe6taG 2qXuFN1iWfykSl8ncbRy141b8dgqtfNGbZo68HIKEwewRMUlHxzA8kDUs22lVTHu vbkG4Ft6JzJsqjc+xG1aGbJK43gGnywpgRk1jVTA649cxrQ2ynFJIkhHeq8xmqax X2euXB4t6jSvQSxwUFXx1DPNKt0cP521zk6UXnjKTIA77wDM8twqrJVDj7BGNq2f JAemJKNDUI/0GXIdmhXiw0xrsFCb6YFaUPUV1Bjl3PjpATqyGWJj12IwFiJoHUSM SvP/IQCMM0AhTLzsmge4MI/fwNizt9yd6sc8s08/tcnF8kgR2ReIoWryxVAeHZvR SCEsJ5QesYkE7xABEdprq3Bcmj49dTiph6aWWV8QlwHp8BpMSAboxgSjbT7+ncUI +6BIwwFHzM9bzzIB8fjKXTx3BVRfjjkTMqb+WsKEZmfpdmdJzLEGsIDDKuwPBD0J +sTp7AXGrQLYdkZFLlnNXynjf04MGVsn/4ndXDHoTUVUTzgVhPuccC5kRHxetWyI 59XYfV6Ck5KKSe0sEEx5gWpKehg37ySX9rfhaSRfbRcfQqot1ME275MvFmAPj+90 BIWLw+Ms73tUaeErHu8We7S6I2jOcPfnTMK3hYdpEn+doQAzvBAwNFHTFBpLo+Vg /9BkAiLWQ470im+9yuRoHoQ+dBHv6K52Icp19J4/I1lKbtsA/G4emooW5rEewKu4 G3JFdx3Na9uTrybH6P+pPgz9P3oQnP6HGqXLai3jOxQqA5mB23XmectbV0TSsA4Z n3i//+GuI2sHSmLM4nOAM2V+sQDfnZ9PvdXZ9pAsn5iS9RhrFywwQOFeXeFVwiId TTtwuD6OuL8V6s0YsHA6AIZB+PiorG1dHu+9sY+JHM/46Iz/OwmLZb88633ywtEQ BKeal0+8CAQwfjzCH60JUMc02eH604DFi2iepKKyOLUcqE8w8xDoSqgfrkQhMOqY haZddSXyBen5XybRawQ2XlGRal0j/LdiKsa5ALSr6QtyNV3cTUCtIrXut9useWmQ /BxMFrFiTPPSofgj4ByjtqLLZvWqAUk/syhmE8sR3N9eAfhpXrtykyBa4x9ikadm 5+l3HDaW7ILX7pGw3jO85qZxHq5ZAseijLFqiNRYzbUa1DjBUuY5YcceaibQomeJ ztpP2x1ZQN0BfHMF2qmkmDRM+LXXi8X7LH4D1WoHLc99BPmIYshuED8pE8RmsJwx EvBkMmcDrpO+BtNIhqDQrPqJ+A4RS9sWHqGHCZylOK1b0uLVM3WT1HaoRfvT5xsJ DbQMhov6QlZ5wMUtaON+sX/tS3zYprS40Uk7bEXVf+JWJlpmEOMJrJw1EbVggrYm ZxcmdiF1xiPkjJWK8GLnkjvBp0myRhj3PFN4VtISwQ75MgZUax5QL2LdqEGyBxLH 1nVXXtV294VjbJk32Q3ojYa+PPMXcYPYoMr7qCaDf7jMIlcmKufu219HzMNreBZe eUBod1rYH/0MYgd6TPVKCM75wu1aW0ASEYit0k1KeDJdyk2JyDzt4P3Pn2YdZm1f Ye8s5rdyUINMuNmPiCOhpiZ7LHbZw2MwBz8lFlaRL0NMywwe8hCbnhSYCO5ylxTU YD6cR5dZGrUwsFbfKxetg3lExgXn3IIVPsf0Dsrg4pogb69G0lDfU5Wi7V3vwY89 qO9DcK5WbVjpBcFfYbSakZwKwHpRqM+1C6tFXIKB/XaFgWnMXK6a9x5A4Req9UC4 I1jWprPM7PIYo+cbHGuKW35QmKgaegZEeQyUuPviFl1j6rb+LqRSYKOX1ageFBr1 doIyQue7N3Of/hMCAj2yGf/2zjJ4O97iRMBVEC7ECpy8N0dT9mbZfY3A5+F2IM0/ 4vgBCewkdLpTi78DDDxwd0yvGwxNiOl1Q5ZrU6dyZyuQq9JJi0o4xVauiWjXVWnp Y5vwwN4KO2XEiLTYr3DpsEksAwY3fFMpsar/mNZ0EGgvgrnj4GNUti9Nl9rm9wyN DBBQqi7UR2pYGyRW6XMPcBsnvz4TLe5v55mrf8Um0dL8lEpxIzh/y3NoUOa6ov6S 3svm7/2Ti2FZdmB4QEbZEdaDyR4m+jE9BQZNFI4Y+b+jYy07oBaw7CimUoUigbs8 /O8OvL4WOde0gScsb2pwlQ/SUqXa5F4uRl++eOc7Fu5gu8tQfw0S3vUKIoOESqxC e99gzjxfm0sFR4XMpSruKUbD1KkcfbZTCXen8wKd1aesVmblzRs57Oi18Ti0RF2S VQ5YNe3do6bNqHkUzZszgQl8agNz1KR9T3FA7d+lsb51O8GHojPhC27qeA23Ti2n GjM2bHlxFIJomK/5Xpn55dkA82mdjo0uYuzFmH1shfslzVvCBOkp4dgxJT3X+hNt 4FUnaurOkHsAiDbAOMFRZ/0vAlSN4wTUhopE2833lFGAmawoQaevpPlfrl6yFC79 Eg5z8KE+mMfS5bUHNzelqj+xwkgZItzErnVnkwTT2RVoOxLbMTYsLt/d1DAkYzuz CCbwbrEDzWX08YfX1yxCYM6XTMuHvUXmgtl4t1M4ht5kYfqnTTkadmAFSMDUE9IF BusCLcaHL1qDO8k2o1n8WhsN1dWbcI8ecw/WC8Ucxrmf9PQvDVrpFK5D+M1EKSEt kFp6aBV4QzYcynpLdJdpd+CVMXiSmPbT5y1t63kWJhCXKpn4+y1Li3DeSSfuaHH/ IOG6FdraWvUXqZA74tqIaXzqDwfcml4pRMCHNXMwtx6xmQa4/B5C7F3cFBXQQvxr 6YxMMTdFS9EhJphrwtMH215YL7B5rzAubfbvu+7+7ZNbQAZi/GalaA1cVk6x+zOX krNJdBIVmtbWKLvrg2U74o1Cy8qiQiWrAXCe/UkHs+dGj2e8h2UA3qbF2irjLClp YClmHAugftk44NXaXbytvDM00qmhuLgoh8og+nVEwtEw+ivG/sS4LFZ7qUbR9L2i VmSHrQeinZWulg4QA7lhdBu9gqp2OWsHwfSux4cbX/lm/88l2b5cATAiM1bnXZOQ ClbX3084v+aMgOD5aumkR1HcDDyLhBy6/is+9HntTRPEVfwTtD/PPgc95h/L+ENz i/Xucvx/mqyxAFv7Zi0UXrbKZYLX+e6nmS+S4gVArRCJikF5MeoFXcn5psXczWr+ fYwL6aikDG7F2WtyX8GdP+UyePEHh/P2yRDD69D+uyU2yHymXwKgIdnhOzSgkZ9j 3X0BBSZOGuRuXnhmTbpRK1IGqIRhl/icXi3jkAY8TGRJkl6Zr6ASuTFxnn3KUZa0 3v/uzAzTYbCBkeX+BYjvG72PHX8Db7D1/mHNqNYyZHdTjBYKyCPbjiwtJF5mlHzH S+A9RxUUiBJ5edh1d/+DtenCFF9iLyF5VLW+wUYQ2x0nwhh9rSDj8wJlC9OUJ5n6 epDBORF7943KMd5HDY1/VJynTrQm2zx2rYmxagcXzk5nc5Y4s5ZdP8AvJ03cG/j4 cdvvGROrvPGNdr218jGFUIXlrB6yVOmFpVU3VcedNyeWq9kZ7RL+lqCLyXPBK8UO y5w/Ls6FAvV/e12tTQArFn6c0gBDb/3KgLHNRmaDVMRqsvGb3tkI3A9jjkD8LzZw TqiM5VK7sA5Ns0LuuEW0R4ZfSduLMSVlzIdeprLR/uPl0fLH6zEzp3LhriYwlq4E BTQRUIvPFRvB183D+aoA33j4euVyYOO1JAiEps8cMqHwK98UFkjfwm5TOv/ta7U5 JZ9JXU/hkP2iNH/zT4lSHl8M6fJWJHu19p9522weYClMjG0UTLJj09h3TzMR8Tvg xGrK4tSRDe4hfHVyFaRKQtbyhYAIlAC6ncECggC1JnFN0pmhx6u93hmx7LOjC14y BtJuXdm294hOyuZE6HlWbz1kLbd+4v/igxdHWe2vlBMYeQReRrFvoNUyaXkKpudY gAiku76LfBTNYKBfJcEU8GEen9uWTtUDCGrLrF/MIvM8X5HTOxI7sYhPkRw3P+aZ k98IdbhLuyKgOYNwiFA5Hr6EQzR4Icmin7hGN/yKytFmnJbUnMaBNU8dKndnpqCj J73bFCwSCQRk9RiCvxH0nPGOj1HU16USSOQ5R4izp27ggmyDjdP5tEh1pddtXGkA fJXs9BD/fL5aMR5gN9WRzCtIxdElMjQI5xvRl8f7BnVNdDkAMruo+cFIyRlUZtWx py8JcO46SNklZzlnBhQhxdNV1D6HWDQt29JbyTNWQnb8nvQScjsbOoKEFNSiRhZa hu/EdnPNET9Jj3MvQIEV5LI0V1msNlARxKoUOWHaktRrwmt9fph2LMmfXw1zIsHv +AJ+PJLF1x0lBero11ikoP75OK6CfUkXs4/SwNtdxCORRKXGsQLcY6+xVLCF5HNA gt3YYFnlL7dYkAOxxNDCOr+Ag1NAFpnGlmqvNWCdxzckXnieydNbj1kd9hu+9na8 lkxGGBrOPzhlC+CzYqRuhlGzi2UuEzg/nG2Ye5AyEKJ9JGknhHOGKi3JaRMicNx+ mrgwOkXDP46nSYSIdE3YMbPq0xaCD3eIWSgRcZzupWI1GBQxeZ+fm8LVVR3rZXNL TafwU5lhWSiHttdGOri28w+CGoEry7AM0glep6WlSbCfHAaALhqUGoNVZlcX98HV JSze+oe0TVfpjIsBEYCP2dIEahJYG6gD03+x2qxXeHMW6pXttp/FNyRlc6hjz0ED fJhoO9bX19cKvNrBQIFo6Bb7Ri84OjHTVp5sYxCap/lK2mbD4V6ZTMoOGFTwTWKi icJr0m7FKwWMscm54y6vuCDwzE5n/ftOXqvnaZ35Ji/kfPBa+KdAbYQOPRtjntMo 3LcICXDHu7Kcigv1FTVzKcmxD2JAJxXtol8Kqymva2WpHL3dCPo1a/evToW/HVhe x4FZIWe/lu7idC2hzabymakdjM3ehxOLPif96xMKrRF8CpRgDdb5nzvyb47N908o zIY4BC7AJkPn7I0QWKG3c5C7ton22H+qdNuStLjoBH19XeCjOO8UOVEN5xY2a/EN mqkcn5lovtbQ8laomci+gXYlJTTTwV/oCW0/8NykztPyLIQ10FS448Qwx1ksg5cX 8+y++rl3gic9UJHmNme+zRIP96JXePA4O9AUH4wuzCNJInrRK2cdeHIGGWI0zjLZ H8H1oidpOCX/aH+aT2L8b7YM9aInHjvH0X1yxr53MFGxXse66AfgGuI6ZxuuDJnY Sdqz2kDXq8XRlvMFLFKFPwsXNlunNCVK+dTpQfjl8PkfjMBgy0xj1rBrf4h2+aR8 Qbi60Nt/Zh79ymLaxB7TH2eb3oyPVo3BPZoACkAQIOX0LI/DCmiF3Gi7KJhRf+BT CcSzP6MI5tf/agIquJcH44IrTgqKRJ1QI7mauAX5WuFKorkdfze1bGt39x0oZuvE XRcq+fG5haFgGR7cINY1q7FIjcww9NPaVqTtT7RhELrbccTemIbYRnnUIjg4ZCw8 /kNdXlLhlKKAuupkXbEjrRQ56K8fYYxkUfqHHrerOMStAUHg5Ym/4RRUM8tDJ4Fi BVe9cXsFJBFJ2KRwXoFb5Dbs/SZB7fwp1ZDjXzRBu1s7ktqj5HltQlZBGspwKJyU mCeub57rQphVklocLd7770jlHJQ8mqGS01fm87W1w1trpPR5joALesagbfLVCcPI oPRGZ8uZrKCDqzCJbn94yA0pSHYC3z9jVVQX1oVgvrzsKEYZLfxkYc2i4pnNRAmr uZklj97U4m7ZCFgLmqjFwL9PCQwwnJPFQ/0jpso+waVMMPg6UBYK2CUTNbdlH503 N8vTHfO9B4SRDAiM27lTBJ9Nd1w7cdlJQiwUBQPH2sp1vFy/S7rX6hjJQkqKDzn1 e1f0U0+dQuWcnU0C4CAhYHAIrF2PumHkaHdDD73S7WOxvEANz3hfzflH/2BRDQ6u wPojIJmZTYZ+dR5X4dSom5g2gtSARoaawrn+s2jEqEuhNRMSbYAenJu+6+6Pu2be uu1fGfafdhzsxKfni5a3shDiXLWMaAca/3VTOrTuZurKUMFonrJQLYFU4v8Bcsh0 WM+NMjEo6JKbmUHlC7jz+KiPbyAVonI/a2pza5ST0H2ySoFfOcppL3aNVuXrpCLv PfXbPTWZViQZoG9mrmqBuO42GUZ27YU1q3W55VhEHx3KqF7eQgSHseEs0J3a4WDw hIakHbYo7wZXXmNoL7OWW2UVVrrxRfwnQkvMoQyqpoCK3FT+Bb+i4naQD/yiW2s+ kp6Y0ijGOsq9qjh6IGXW8KLo0WeUTugdzdwx0gSIVTo5+wob+5zC0ox5C6c3RK2m 0oz8+NLXpLMkFyth4ZgcTXtgke93ETy0/9XXlPy61VOpGHcnFhuuxuS020rh8Lge cDagxnxOn2Fgi3NLfLk36f3U1mIr0HW01KKU4dDeBxnwcjEOpxOllr8LZKNNhdEy dfz9bjfQpXDv8IvuSgU2wGAZyYxPLFkimKlsQYNsobUVY+mLxf+0VdUhiiSS5x/h EYfxjZoUWTOD78EDZl7NqmoIJGmCENKO9ofh+PJzSYR7maEIafb5EAwxtEo0xGEQ cAnBEtwomzSGnppUrP+4fYvnARKBupi3Gt/Cf2DLWpFHSXouh0r6XkF3Cqh9ZuS0 D43QJCRAAwmAL1DhIh7XEkln4VEYbHOIBzlD1gjug1GmSKQ1bXwbpQLLrz5uHva1 uZW01sXunQc+VnruLCiDdlX0WrJKfr5e1v02Dl62kJYCUIc7DK3nZ/5F5y7il6zf Rpr/lw3rhL5TbsTuGRYWMlV8W/8UgV4H1bA9SBSdtImrTnlwaMhiupO0pDZqCw+v m8a3oLWr4KqVU/Ia8SgyC6wWZfIKLXellJ+fgRXYLk99R202CZX3l3l5S4M/wT4Q 5SgfktJspSG+SodyqJk5jqO8sa2GbCMuzNcrZOG7ESo///fG29VG5TgoJQrCJ7XH 2TQBcMhssQkm9kn55Ddpd1HTi+g//wmzMlTkUeh9tGscRzlj7wB4CRh9ENu7X9GX JwYcb48bB/viRzArUGX1Msw89XlF4Cr8VQ6RjmY4Vg2JSzUsdJyctAQWM35exbLQ HIcecUFQHQBoIETygfthfumMPjaiIz5oP1enz+6x58lfC/DDX7X55j4q0qXo2U8l dFhfbr4PHqKkolWcvmJ4iRBrhfDcmjJm74roo0N+Er8QUZlB3Z8CsrL7Dwd6Xj8F 7/w7HbrEatjjIZwnBst+3qMIl+7S2PG3tdzZ4OXbVaDtvGUjYgMmdjTLrAmIYa2x 6BVwtAxlfg/exygHeasBXC5ajKQqQJnbInPRWmAWgoVJE3vJw8VXWcbZu12+7Yt5 0GFFLwBIt/m2PhCfamWvG5QWY1AVtAGLVX0iqn9mOQ8x0YjjCXC6w99XBQlq1wL5 oMKtW8Sw2nM2BLi2qlNt2YVN8kMas4AL0+sioGrNkEVQiCZCisDbW6ycFZ28ADeg 7ZfRdHbYL2zUTYKDhElizJ9UCURHNV49PN7/dZMoDPiPUzMPRgAsUobV5kBHin/S fufGjdcEey0xLOJqm9s/GRJB973dXiQMbath+gc66R/+iCYStpCNAXpcCx/nU31h bsF9xYUq9YK/B46DGWZxgt93F2TmrEZVgo8ceAOJ1M7x1+wWTmQp+F9fvSWxLqj9 6Hq1IK1jhqpHM3k2h2Sx0YlIAqlONfoNKAB7GkexvA0RIv172RaY13E6X8tzXP59 7lipuJ9/SDDFWplTOPxaA93EK+X4GUcCLJwlqLlxKd6atbPHpouvOZ93g0RhYiIr tQ6hEYkUYihlhc0StHQe8oj1rV8t/Rhgb1eKbdX/idnsR48P0HN+5Ws3Jarj9nMg josUk+hAPA/SApgVkKRxNvILLRjAfYSbjJfbOiD4hVf25ewjVKVR/MPlg59Nifev h+R8d16QXBjGNgxb0W8mk6xSSecqOgpY/ztUmBH6/Wqg1mPM56l2w79fESrltw1f i4XbqkkNAMsmfG7JJatH7hA6nMV85f35G6d+aym3uTjtG/vJwLyoMLcYWL4KshsH BZoynvLk3en/baGoSpA69BKyxK+Qc2NMErsVL1u3iPOuSkHZu0DxlEdOT991PI0A HKlofZpVlcQ8j3RRVGrE3Jukd0nNgFzSH3oxbqadNXHxRKZbmJv4dJER5s5FSFTl 2bFTw0PwSWGr8MH9QyqC8Ya8Q8O93369mlDVdpL/WiV0jxj3QQTCspcTBjQv5vIM CtbWLN87UqquGwDwatGkyDZ36wiSA7MHdj4HIJHlFyOWrsYgVK6YP0nmsS4ik78F +0AeamsjSGiFr+3LftZ0j42otBCejM9HpDZP8aRzWTIHY27kNWtn/hQWKFDA1nze BhVHIkxeubLJeArPYedhhc2BN5T8VeHDBVRr+MhHqnMAQ7Vh3XRpBIPBItiGqJ/k gVMB4b9a0wedp2X8y/A1AfQQppAzPj5VXe9CFJFMqVp3L7CZuWFZS9sOuwhTYdAG lk+TaujzOh4XxeIfZcXCnhJZL+J7HKtdT8QgbmrTz+O7Wxx38AbjuDNa9Qe0ddfj mPItXhJp9+0FZlOOqDvmbJXz3DjPVsmgPfpJxXJWncC+hZeTiyq9HAr9uZ+TUwZr OZkyUEZVZE9qRf4t85xu24R/eea/IR8GB0Ke9ciijmNKBac/OxLV4zE8aRlqn7eY wl4vVHRzsX1xbbBZyyx12jbWTRZK8gX586mhdQIIXqmD9MQELS5M1XjyBusI+1Xk qAX2dLq0Qbm7Oth+cw3lroSP6ZqhYjMKnJNL/qF+UYRKdsWjZcrFpp2Zv4rNxh/x 2ekmzFgyyvsNVaeOGZ2uvt4CL6Gd5SIlDbxBNC5IFI4VxoHVBtZSfrTshxg5zKQK eM77M98YfmdtmYj3wuxIuOlETTGbSjqQ75cS/evXNLbHhhlrICbx2VVEO43btquT mfX8GEIm+bz1YyqtA8WXdWJ9Mke+C2TZPqiNhA2/LjmDoTrXE7aBFkzHCt/+jchP URxMf+KU/IR2F4Qr4GzQO8PlAMS7Sw3AfpfJdkzTLcO6H7TzPU2X1TXqQkPi+npV IULH5WXFUWfEwiogjTyvla+J419GdWp54U3g6Y6cLGKCFFcKnGiAmTjuc2xtiM9G yw+BqwCYiT7cx9zO6pR++zYUDKDYXgk2CVnWKQReTXeFq7rHfeoYpBzrl5uOEjc5 5pbRT9ryIj9wc7mfDUccxxJAAIs3VinWN7I6SkvTE1TTgoLm5+IiXn+DvhPf+pSp M1p4Xw6EvswU+35dXC1k7N2Lg6yPgZFNWukDRIRQOYlGeMJGdX3So/NulKrxR0Hy SOf/TnXGK5fZqKxHPwwxoYhnN261nnLs7gn/2sK4wudbxKHBKdcOEGxG2qLAXcAf 4HJmfKrKjDMO05Gfx6POw1XBpiXRqk65GZN8mCFlojUcBhDM+CYOY+vlkzn3zWnB pwhXypY9h9emq61Z93O3Jt0k9f/zTeQ/j8pnaB+6m8mfoQq6OTzM22v1IIgi/oqz wYThR5RSVIe/x6W6oD7MblOu3Z13JBJNzbJCz5zDz8a0fb4BmAq5AMD/g2I6+KpT CjgqmuHIsp8nBVbX99/kxZSn9nmHKdbtvr7hjGxq0KtdzxObp0vp1DB1fd26jdR0 CefeF6u+gB67kzsIsOcLtstZ3vUqreSsWKuCLLgU0UjJ9mz0dZwS1G482bdommXS /mcs4nVAcPUJyxhrzxIUpwMWsfOLfdpd5LHHqiWzKfbiN1tV1btlF6FJyg7MYgbc v8QAIqbkkWI8rzjZ4jB2ba+nO4ve9g3GpnUAaCD3omEfFJX0u85UWefE0xbGz4fw mh7S58zM6C2Lw+Vx8qL6hxBR51QC0obP2L1cijP20nqgqmqUFh3O2JKrqX+8dnM9 vm9WWijuDPyW75gi8DNOTBdjZTI+l6kbDr/FxvYR0777jCkhdBpSpU112AJRDkXM tGJuEo5hpVMEMyRj9qNUdwuTMVWEf/lBoKd0zxn4PEnIb9d2ka2Cg+uvHXVqVY6n jO7X/Xbl7Er+BoeVM1scdEROFJfm/8OoczQgGXGrZWiAjxr9SMA2OAexAZgKd7Ly qfgCKLvAmYcZCYuEuHUGgAejoCh4mY9UKAw7tjsLsgGm4P/KjIARQqtZfVo29XRE uls9h/6naCgDBzrvaYNDeVOBERT9IrLrBgcaELyMYjqwai4r/1ihQACp10T1vTs0 niLPfuRNOwJnvbqjzeV2dVhSZ7G+/P934HL3i6BV1LBGhpWNjPEWFL9UzJNi5U5F W5899ZuObtn036eqdkDBNgPbuH7KGQuJLE49QTWJVzUoV/INSr4OW6KEZzcwQwj9 4xZNn2HWmZt8K0jNk8Vw0PXZ4/tG/HSZV4K6yricRo/dYwDWblQz2Rq1EAD80Dtp BNshn/oSBGu0HNi1dvO1maLGn4F8dtgF8TL2ALqM2gE4xZxASjLCL38EVQq0QxDG zbWeMY9zdSOXJylkVrNvv1qolAcKpRkXKJAJmy5Vg5qckoKc0PssyKsxNbF7Albh +vnVUi/1NjqDn3MXowtYIXyYPFrBXhOoZDuCiIRgQsMb5yFfW42efEpxTo/t8W59 mkwDKtTkAvQD9+0UOrc35Ap7VTl8JKUsAw988ocz5C2Y4YlZcd6mXJn1nerVDE6q 1EzYYS0N1pkR6x8dynxNH0gSm08GSJ1n+RAMqgGFL2ADvkQtoWZdONcnMAQvquxQ -----END ENCRYPTED FILE----- #else #error "Secure builder required to compile this file" #endif
63.590476
64
0.951176
5f3a63fce8d7d0c0448cf6ed9c3b392cf2a34a15
54
h
C
bookcode/cproject/namespace/two.h
zhangymPerson/Think-in-java-note
b89ca3b90ad3d43d010e4764d06ee5ffff8e118d
[ "Apache-2.0" ]
null
null
null
bookcode/cproject/namespace/two.h
zhangymPerson/Think-in-java-note
b89ca3b90ad3d43d010e4764d06ee5ffff8e118d
[ "Apache-2.0" ]
3
2021-12-14T20:50:59.000Z
2021-12-18T18:26:01.000Z
bookcode/cproject/namespace/two.h
zhangymPerson/Think-in-java-note
b89ca3b90ad3d43d010e4764d06ee5ffff8e118d
[ "Apache-2.0" ]
null
null
null
#include <iostream> namespace two { void fun(); }
9
19
0.62963
93fd2959ee0042ff6fdb3aca9c210a3701232a2a
290
h
C
util.h
Naoya-Horiguchi/mce-inject
4cbe46321b4a81365ff3aafafe63967264dbfec5
[ "Intel" ]
25
2015-03-31T14:30:48.000Z
2022-01-17T03:29:42.000Z
util.h
Naoya-Horiguchi/mce-inject
4cbe46321b4a81365ff3aafafe63967264dbfec5
[ "Intel" ]
1
2017-03-13T03:15:18.000Z
2017-03-13T03:15:18.000Z
util.h
Naoya-Horiguchi/mce-inject
4cbe46321b4a81365ff3aafafe63967264dbfec5
[ "Intel" ]
16
2016-07-07T02:19:27.000Z
2022-02-21T09:54:32.000Z
#define ARRAY_SIZE(x) (sizeof(x)/sizeof(*(x))) void err(const char *msg); #define NEW(x) ((x) = xalloc(sizeof(*(x)))) void *xalloc(size_t sz); void *xcalloc(size_t a, size_t b); #ifdef __GNUC__ #define barrier() asm volatile("" ::: "memory") #else #define barrier() do {} while(0) #endif
22.307692
47
0.655172
9e0a77d453fbc13a4445bbae13fa2ec7f39861cd
14,050
h
C
src/bitcoinrpc.h
xiaolin1579/TDC
c5aadc1676cc9bdb7e558500c55944d3a78fb8be
[ "MIT" ]
1
2019-10-23T22:59:35.000Z
2019-10-23T22:59:35.000Z
src/bitcoinrpc.h
xiaolin1579/TDC
c5aadc1676cc9bdb7e558500c55944d3a78fb8be
[ "MIT" ]
14
2020-04-19T10:46:52.000Z
2020-05-12T15:01:50.000Z
src/bitcoinrpc.h
xiaolin1579/TDC
c5aadc1676cc9bdb7e558500c55944d3a78fb8be
[ "MIT" ]
5
2020-01-05T10:55:11.000Z
2020-05-28T05:12:24.000Z
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef _BITCOINRPC_H_ #define _BITCOINRPC_H_ 1 #include <string> #include <list> #include <map> class CBlockIndex; class CReserveKey; #include "json/json_spirit_reader_template.h" #include "json/json_spirit_writer_template.h" #include "json/json_spirit_utils.h" #include "util.h" // HTTP status codes enum HTTPStatusCode { HTTP_OK = 200, HTTP_BAD_REQUEST = 400, HTTP_UNAUTHORIZED = 401, HTTP_FORBIDDEN = 403, HTTP_NOT_FOUND = 404, HTTP_INTERNAL_SERVER_ERROR = 500, }; // Bitcoin RPC error codes enum RPCErrorCode { // Standard JSON-RPC 2.0 errors RPC_INVALID_REQUEST = -32600, RPC_METHOD_NOT_FOUND = -32601, RPC_INVALID_PARAMS = -32602, RPC_INTERNAL_ERROR = -32603, RPC_PARSE_ERROR = -32700, // General application defined errors Общее применение определенные ошибки RPC_MISC_ERROR = -1, // std::exception thrown in command handling std::exception добавление(брость) в команду обработки RPC_FORBIDDEN_BY_SAFE_MODE = -2, // Server is in safe mode, and command is not allowed in safe mode Сервер находится в безопасном режиме, и команда не допускается в безопасном режиме RPC_TYPE_ERROR = -3, // Unexpected type was passed as parameter Неожиданный тип был передан в качестве параметра RPC_INVALID_ADDRESS_OR_KEY = -5, // Invalid address or key Неверный адрес или ключ RPC_OUT_OF_MEMORY = -7, // Ran out of memory during operation Исчерпал память во время операции RPC_INVALID_PARAMETER = -8, // Invalid, missing or duplicate parameter Неверный, отсутствующий или дублирующий параметр RPC_DATABASE_ERROR = -20, // Database error Ошибка базы данных RPC_DESERIALIZATION_ERROR = -22, // Error parsing or validating structure in raw format Ошибка разбора или проверки структуры в сыром(необработанном) формате RPC_SERVER_NOT_STARTED = -18, // RPC server was not started (StartRPCThreads() not called) // P2P client errors RPC_CLIENT_NOT_CONNECTED = -9, // Bitcoin is not connected Bitcoin не подключен RPC_CLIENT_IN_INITIAL_DOWNLOAD = -10, // Still downloading initial blocks Тем не менее скачиваем начальные блоки // Wallet errors RPC_WALLET_ERROR = -4, // Unspecified problem with wallet (key not found etc.) Неопределенная проблема с бумажником (ключ не найден и т.д.) RPC_WALLET_INSUFFICIENT_FUNDS = -6, // Not enough funds in wallet or account Не достаточно средств в бумажнике или учетной записи RPC_WALLET_INVALID_ACCOUNT_NAME = -11, // Invalid account name Неверное имя учетной записи RPC_WALLET_KEYPOOL_RAN_OUT = -12, // Keypool ran out, call keypoolrefill first Keypool закончился, вызывайте keypoolrefill первым RPC_WALLET_UNLOCK_NEEDED = -13, // Enter the wallet passphrase with walletpassphrase first Введите Wallet пароль с walletpassphrase первым RPC_WALLET_PASSPHRASE_INCORRECT = -14, // The wallet passphrase entered was incorrect Фраза-пароль кошелька неверна RPC_WALLET_WRONG_ENC_STATE = -15, // Command given in wrong wallet encryption state (encrypting an encrypted wallet etc.) Команда, данная в неправильно зашифрованном состоянии бумажника(шифрование зашифрованного бумажника и т.д.) RPC_WALLET_ENCRYPTION_FAILED = -16, // Failed to encrypt the wallet Не удалось зашифровать бумажник RPC_WALLET_ALREADY_UNLOCKED = -17, // Wallet is already unlocked Wallet уже разблокирован }; json_spirit::Object JSONRPCError(int code, const std::string& message); void StartRPCThreads(); void StopRPCThreads(); int CommandLineRPC(int argc, char *argv[]); /** Convert parameter values for RPC call from strings to command-specific JSON objects. Преобразование параметров значений для RPC вызова из строк в специфическую-команду JSON объектов */ json_spirit::Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams); /* Type-check arguments; throws JSONRPCError if wrong type given. Does not check that the right number of arguments are passed, just that any passed are the correct type. Use like: RPCTypeCheck(params, boost::assign::list_of(str_type)(int_type)(obj_type)); Проверка типов аргументов; создает исключение JSONRPCError, если данный тип неправильный. Не проверять, что пришло правильное количество аргументов, просто, что любой переданный являются правильным типом. Используйте как: RPCTypeCheck(params, boost::assign::list_of(str_type)(int_type)(obj_type)); */ void RPCTypeCheck(const json_spirit::Array& params, const std::list<json_spirit::Value_type>& typesExpected, bool fAllowNull=false); /* Check for expected keys/value types in an Object. Use like: RPCTypeCheck(object, boost::assign::map_list_of("name", str_type)("value", int_type)); Проверка типов ожидаемых ключей/значений в объекте Используйте как: RPCTypeCheck(object, boost::assign::map_list_of("name", str_type)("value", int_type)); */ void RPCTypeCheck(const json_spirit::Object& o, const std::map<std::string, json_spirit::Value_type>& typesExpected, bool fAllowNull=false); /* Run func nSeconds from now. Uses boost deadline timers. Запустите func nSeconds теперь. Используя boost таймеры крайнего срока Overrides previous timer <name> (if any). Заменяет(переопределяет) предыдущий таймера <name> (если таковые имеются) */ void RPCRunLater(const std::string& name, boost::function<void(void)> func, int64 nSeconds); typedef json_spirit::Value(*rpcfn_type)(const json_spirit::Array& params, bool fHelp); class CRPCCommand { public: std::string name; rpcfn_type actor; bool okSafeMode; bool threadSafe; }; /** * Bitcoin RPC command dispatcher. Bitcoin RPC командный диспетчер */ class CRPCTable { private: std::map<std::string, const CRPCCommand*> mapCommands; public: CRPCTable(); const CRPCCommand* operator[](std::string name) const; std::string help(std::string name) const; /** * Execute a method. Выполнить метод * @param method Method to execute Метод для выполнения * @param params Array of arguments (JSON objects) Массив аргументов (JSON объекты) * @returns Result of the call. Результат выполнения вызова * @throws an exception (json_spirit::Value) when an error happens. Исключение (json_spirit::Value) когда происходят ошибки */ json_spirit::Value execute(const std::string &method, const json_spirit::Array &params) const; }; extern const CRPCTable tableRPC; extern void InitRPCMining(); extern void ShutdownRPCMining(); extern int64 nWalletUnlockTime; extern int64 AmountFromValue(const json_spirit::Value& value); extern json_spirit::Value ValueFromAmount(int64 amount); extern double GetDifficulty(const CBlockIndex* blockindex = NULL); extern std::string HexBits(unsigned int nBits); extern std::string HelpRequiringPassphrase(); extern void EnsureWalletIsUnlocked(); extern json_spirit::Value getconnectioncount(const json_spirit::Array& params, bool fHelp); // in rpcnet.cpp extern json_spirit::Value getpeerinfo(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value addnode(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getaddednodeinfo(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value dumpprivkey(const json_spirit::Array& params, bool fHelp); // in rpcdump.cpp extern json_spirit::Value importprivkey(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value dumpwallet(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value importwallet(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getgenerate(const json_spirit::Array& params, bool fHelp); // in rpcmining.cpp extern json_spirit::Value setgenerate(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value usetxinblock(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getblocktarget(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getnetworkhashps(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value gethashespersec(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getmininginfo(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getwork(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getblocktemplate(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value submitblock(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getnewaddress(const json_spirit::Array& params, bool fHelp); // in rpcwallet.cpp extern json_spirit::Value getaccountaddress(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value setaccount(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getaccount(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getaddressesbyaccount(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value sendtoaddress(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value signmessage(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value verifymessage(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getreceivedbyaddress(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getreceivedbyaccount(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getbalance(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value movecmd(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value sendfrom(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value sendmany(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value addmultisigaddress(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value createmultisig(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value listreceivedbyaddress(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value listreceivedbyaccount(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value listtransactions(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value listaddressgroupings(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value listaccounts(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value listsinceblock(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value gettransaction(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value backupwallet(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value keypoolrefill(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value walletpassphrase(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value walletpassphrasechange(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value walletlock(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value encryptwallet(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value validateaddress(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getinfo(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getrawtransaction(const json_spirit::Array& params, bool fHelp); // in rcprawtransaction.cpp extern json_spirit::Value listunspent(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value lockunspent(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value listlockunspent(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value createrawtransaction(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value decoderawtransaction(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value signrawtransaction(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value sendrawtransaction(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getblockcount(const json_spirit::Array& params, bool fHelp); // in rpcblockchain.cpp extern json_spirit::Value getbestblockhash(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getdifficulty(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value settxfee(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getrawmempool(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getblockhash(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getblock(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value gettxoutsetinfo(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value gettxout(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value verifychain(const json_spirit::Array& params, bool fHelp); #endif
62.444444
243
0.730747
9e59f7b1f19eb8672cc3c468e6e30d4f221b6e3b
2,533
h
C
src/other/ext/gdal/gcore/mdreader/reader_kompsat.h
dservin/brlcad
34b72d3efd24ac2c84abbccf9452323231751cd1
[ "BSD-4-Clause", "BSD-3-Clause" ]
83
2021-03-10T05:54:52.000Z
2022-03-31T16:33:46.000Z
src/other/ext/gdal/gcore/mdreader/reader_kompsat.h
dservin/brlcad
34b72d3efd24ac2c84abbccf9452323231751cd1
[ "BSD-4-Clause", "BSD-3-Clause" ]
13
2021-06-24T17:07:48.000Z
2022-03-31T15:31:33.000Z
src/other/ext/gdal/gcore/mdreader/reader_kompsat.h
dservin/brlcad
34b72d3efd24ac2c84abbccf9452323231751cd1
[ "BSD-4-Clause", "BSD-3-Clause" ]
54
2021-03-10T07:57:06.000Z
2022-03-28T23:20:37.000Z
/****************************************************************************** * $Id$ * * Project: GDAL Core * Purpose: Read metadata from Kompsat imagery. * Author: Alexander Lisovenko * Author: Dmitry Baryshnikov, polimax@mail.ru * ****************************************************************************** * Copyright (c) 2014-2015 NextGIS <info@nextgis.ru> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef READER_KOMPSAT_H_INCLUDED #define READER_KOMPSAT_H_INCLUDED #include "reader_pleiades.h" /** @brief Metadata reader for Kompsat TIFF filename: aaaaaaaaaa.tif Metadata filename: aaaaaaaaaa.eph aaaaaaaaaa.txt RPC filename: aaaaaaaaaa.rpc Common metadata (from metadata filename): SatelliteId: AUX_SATELLITE_NAME AcquisitionDateTime: IMG_ACQISITION_START_TIME, IMG_ACQISITION_END_TIME */ class GDALMDReaderKompsat: public GDALMDReaderBase { public: GDALMDReaderKompsat(const char *pszPath, char **papszSiblingFiles); virtual ~GDALMDReaderKompsat(); virtual bool HasRequiredFiles() const override; virtual char** GetMetadataFiles() const override; protected: virtual void LoadMetadata() override; char** ReadTxtToList(); virtual time_t GetAcquisitionTimeFromString(const char* pszDateTime) override; protected: CPLString m_osIMDSourceFilename; CPLString m_osRPBSourceFilename; }; #endif // READER_KOMPSAT_H_INCLUDED
38.378788
82
0.69167
9af6bf3aacb6419226eb3f6f81094829aacaa034
9,839
c
C
gdb/testsuite/gdb.base/printcmds.c
greyblue9/binutils-gdb
05377632b124fe7600eea7f4ee0e9a35d1b0cbdc
[ "BSD-3-Clause" ]
1
2020-10-14T03:24:35.000Z
2020-10-14T03:24:35.000Z
gdb/testsuite/gdb.base/printcmds.c
greyblue9/binutils-gdb
05377632b124fe7600eea7f4ee0e9a35d1b0cbdc
[ "BSD-3-Clause" ]
null
null
null
gdb/testsuite/gdb.base/printcmds.c
greyblue9/binutils-gdb
05377632b124fe7600eea7f4ee0e9a35d1b0cbdc
[ "BSD-3-Clause" ]
null
null
null
/* This table is used as a source for every ascii character. It is explicitly unsigned to avoid differences due to native characters being either signed or unsigned. */ #include <stdlib.h> unsigned char ctable1[256] = { 0000, 0001, 0002, 0003, 0004, 0005, 0006, 0007, 0010, 0011, 0012, 0013, 0014, 0015, 0016, 0017, 0020, 0021, 0022, 0023, 0024, 0025, 0026, 0027, 0030, 0031, 0032, 0033, 0034, 0035, 0036, 0037, 0040, 0041, 0042, 0043, 0044, 0045, 0046, 0047, 0050, 0051, 0052, 0053, 0054, 0055, 0056, 0057, 0060, 0061, 0062, 0063, 0064, 0065, 0066, 0067, 0070, 0071, 0072, 0073, 0074, 0075, 0076, 0077, 0100, 0101, 0102, 0103, 0104, 0105, 0106, 0107, 0110, 0111, 0112, 0113, 0114, 0115, 0116, 0117, 0120, 0121, 0122, 0123, 0124, 0125, 0126, 0127, 0130, 0131, 0132, 0133, 0134, 0135, 0136, 0137, 0140, 0141, 0142, 0143, 0144, 0145, 0146, 0147, 0150, 0151, 0152, 0153, 0154, 0155, 0156, 0157, 0160, 0161, 0162, 0163, 0164, 0165, 0166, 0167, 0170, 0171, 0172, 0173, 0174, 0175, 0176, 0177, 0200, 0201, 0202, 0203, 0204, 0205, 0206, 0207, 0210, 0211, 0212, 0213, 0214, 0215, 0216, 0217, 0220, 0221, 0222, 0223, 0224, 0225, 0226, 0227, 0230, 0231, 0232, 0233, 0234, 0235, 0236, 0237, 0240, 0241, 0242, 0243, 0244, 0245, 0246, 0247, 0250, 0251, 0252, 0253, 0254, 0255, 0256, 0257, 0260, 0261, 0262, 0263, 0264, 0265, 0266, 0267, 0270, 0271, 0272, 0273, 0274, 0275, 0276, 0277, 0300, 0301, 0302, 0303, 0304, 0305, 0306, 0307, 0310, 0311, 0312, 0313, 0314, 0315, 0316, 0317, 0320, 0321, 0322, 0323, 0324, 0325, 0326, 0327, 0330, 0331, 0332, 0333, 0334, 0335, 0336, 0337, 0340, 0341, 0342, 0343, 0344, 0345, 0346, 0347, 0350, 0351, 0352, 0353, 0354, 0355, 0356, 0357, 0360, 0361, 0362, 0363, 0364, 0365, 0366, 0367, 0370, 0371, 0372, 0373, 0374, 0375, 0376, 0377 }; unsigned char ctable2[] = { 'a','X','X','X','X','X','X','X','X','X','X','X','X','X','X','X', 'a','a','X','X','X','X','X','X','X','X','X','X','X','X','X','X', 'a','a','a','X','X','X','X','X','X','X','X','X','X','X','X','X', 'a','a','a','a','X','X','X','X','X','X','X','X','X','X','X','X', 'a','a','a','a','a','X','X','X','X','X','X','X','X','X','X','X', 'a','a','a','a','a','a','X','X','X','X','X','X','X','X','X','X', 'a','a','a','a','a','a','a','X','X','X','X','X','X','X','X','X', 'a','a','a','a','a','a','a','a','X','X','X','X','X','X','X','X', 'a','a','a','a','a','a','a','a','a','X','X','X','X','X','X','X', 'a','a','a','a','a','a','a','a','a','a','X','X','X','X','X','X', 'a','a','a','a','a','a','a','a','a','a','a','X','X','X','X','X', 'a','a','a','a','a','a','a','a','a','a','a','a','X','X','X','X', 'a','a','a','a','a','a','a','a','a','a','a','a','a','X','X','X', 'a','a','a','a','a','a','a','a','a','a','a','a','a','a','X','X', 'a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','X', 'a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','a', 0 }; /* Single and multidimensional arrays to test access and printing of array members. */ typedef int ArrayInt [10]; ArrayInt a1 = {2,4,6,8,10,12,14,16,18,20}; typedef char ArrayChar [5]; ArrayChar a2 = {'a','b','c','d','\0'}; int int1dim[12] = {0,1,2,3,4,5,6,7,8,9,10,11}; int int2dim[3][4] = {{0,1,2,3},{4,5,6,7},{8,9,10,11}}; int int3dim[2][3][2] = {{{0,1},{2,3},{4,5}},{{6,7},{8,9},{10,11}}}; int int4dim[1][2][3][2] = {{{{0,1},{2,3},{4,5}},{{6,7},{8,9},{10,11}}}}; char *teststring = (char*)"teststring contents"; typedef char *charptr; charptr teststring2 = "more contents"; /* Test printing of a struct containing character arrays. */ struct some_arrays { unsigned char array1[4]; unsigned char array2[1]; unsigned char array3[1]; unsigned char array4[2]; unsigned char array5[4]; } arrays = { {'a', 'b', 'c', '\0'}, {'d'}, {'e'}, {'f', 'g' }, {'h', 'i', 'j', '\0'} }; struct some_arrays *parrays = &arrays; enum some_volatile_enum { enumvolval1, enumvolval2 }; /* A volatile enum variable whose name is the same as the enumeration name. See PR11827. */ volatile enum some_volatile_enum some_volatile_enum = enumvolval1; /* An enum considered as a "flag enum". */ enum flag_enum { FE_NONE = 0x00, FE_ONE = 0x01, FE_TWO = 0x02, FE_TWO_LEGACY = 0x02, }; enum flag_enum three = (enum flag_enum) (FE_ONE | FE_TWO); /* Another enum considered as a "flag enum", but with no enumerator with value 0. */ enum flag_enum_without_zero { FEWZ_ONE = 0x01, FEWZ_TWO = 0x02, }; enum flag_enum_without_zero flag_enum_without_zero = (enum flag_enum_without_zero) 0; /* Not a flag enum, an enumerator value has multiple bits sets. */ enum not_flag_enum { NFE_ONE = 0x01, NFE_TWO = 0x02, NFE_F0 = 0xf0, }; enum not_flag_enum three_not_flag = (enum not_flag_enum) (NFE_ONE | NFE_TWO); /* A structure with an embedded array at an offset > 0. The array has all elements with the same repeating value, which must not be the same as the value of the preceding fields in the structure for the test to be effective. This tests whether GDB uses the correct element content offsets (relative to the complete `some_struct' value) when counting value repetitions. */ struct some_struct { int a; int b; unsigned char array[20]; } some_struct = { 0x12345678, 0x87654321, { 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa } }; /* The following variables are used for testing byte repeat sequences. The variable names are encoded: invalid_XYZ where: X = start Y = invalid Z = end Each of X and Z can be "E" (empty), "S" (single), "L" (long single), or "R" (repeat). Y can be either any of the above except "E" (otherwise there is nothing to test). */ char invalid_ESE[] = "\240"; char invalid_SSE[] = "a\240"; char invalid_LSE[] = "abaabbaaabbb\240"; char invalid_RSE[] = "aaaaaaaaaaaaaaaaaaaa\240"; char invalid_ESS[] = "\240c"; char invalid_SSS[] = "a\240c"; char invalid_LSS[] = "abaabbaaabbb\240c"; char invalid_RSS[] = "aaaaaaaaaaaaaaaaaaaa\240c"; char invalid_ESL[] = "\240cdccddcccddd"; char invalid_SSL[] = "a\240cdccddcccddd"; char invalid_LSL[] = "abaabbaaabbb\240cdccddcccddd"; char invalid_RSL[] = "aaaaaaaaaaaaaaaaaaaa\240cdccddcccddd"; char invalid_ESR[] = "\240cccccccccccccccccccc"; char invalid_SSR[] = "a\240cccccccccccccccccccc"; char invalid_LSR[] = "abaabbaaabbb\240cccccccccccccccccccc"; char invalid_RSR[] = "aaaaaaaaaaaaaaaaaaaa\240cccccccccccccccccccc"; char invalid_ELE[] = "\240\240\240\240"; char invalid_SLE[] = "a\240\240\240\240"; char invalid_LLE[] = "abaabbaaabbb\240\240\240\240"; char invalid_RLE[] = "aaaaaaaaaaaaaaaaaaaa\240\240\240\240"; char invalid_ELS[] = "\240\240\240\240c"; char invalid_SLS[] = "a\240\240\240\240c"; char invalid_LLS[] = "abaabbaaabbb\240\240\240\240c"; char invalid_RLS[] = "aaaaaaaaaaaaaaaaaaaa\240\240\240\240c"; char invalid_ELL[] = "\240\240\240\240cdccddcccddd"; char invalid_SLL[] = "a\240\240\240\240cdccddcccddd"; char invalid_LLL[] = "abaabbaaabbb\240\240\240\240cdccddcccddd"; char invalid_RLL[] = "aaaaaaaaaaaaaaaaaaaa\240\240\240\240cdccddcccddd"; char invalid_ELR[] = "\240\240\240\240cccccccccccccccccccc"; char invalid_SLR[] = "a\240\240\240\240cccccccccccccccccccc"; char invalid_LLR[] = "abaabbaaabbb\240\240\240\240cccccccccccccccccccc"; char invalid_RLR[] = "aaaaaaaaaaaaaaaaaaaa\240\240\240\240cccccccccccccccccccc"; char invalid_ERE[] = "" "\240\240\240\240\240\240\240\240\240\240" "\240\240\240\240\240\240\240\240\240\240"; char invalid_LRE[] = "abaabbaaabbb" "\240\240\240\240\240\240\240\240\240\240" "\240\240\240\240\240\240\240\240\240\240"; char invalid_RRE[] = "aaaaaaaaaaaaaaaaaaaa" "\240\240\240\240\240\240\240\240\240\240" "\240\240\240\240\240\240\240\240\240\240"; char invalid_ERS[] = "" "\240\240\240\240\240\240\240\240\240\240" "\240\240\240\240\240\240\240\240\240\240c"; char invalid_ERL[] = "" "\240\240\240\240\240\240\240\240\240\240" "\240\240\240\240\240\240\240\240\240\240cdccddcccddd"; char invalid_ERR[] = "" "\240\240\240\240\240\240\240\240\240\240" "\240\240\240\240\240\240\240\240\240\240cccccccccccccccccccc"; char invalid_SRE[] = "a" "\240\240\240\240\240\240\240\240\240\240" "\240\240\240\240\240\240\240\240\240\240"; char invalid_SRS[] = "a" "\240\240\240\240\240\240\240\240\240\240" "\240\240\240\240\240\240\240\240\240\240c"; char invalid_SRL[] = "a" "\240\240\240\240\240\240\240\240\240\240" "\240\240\240\240\240\240\240\240\240\240cdccddcccddd"; char invalid_SRR[] = "a" "\240\240\240\240\240\240\240\240\240\240" "\240\240\240\240\240\240\240\240\240\240cccccccccccccccccccc"; char invalid_LRS[] = "abaabbaaabbb" "\240\240\240\240\240\240\240\240\240\240" "\240\240\240\240\240\240\240\240\240\240c"; char invalid_LRL[] = "abaabbaaabbb" "\240\240\240\240\240\240\240\240\240\240" "\240\240\240\240\240\240\240\240\240\240cdccddcccddd"; char invalid_LRR[] = "abaabbaaabbb" "\240\240\240\240\240\240\240\240\240\240" "\240\240\240\240\240\240\240\240\240\240cccccccccccccccccccc"; char invalid_RRS[] = "aaaaaaaaaaaaaaaaaaaa" "\240\240\240\240\240\240\240\240\240\240" "\240\240\240\240\240\240\240\240\240\240c"; char invalid_RRL[] = "aaaaaaaaaaaaaaaaaaaa" "\240\240\240\240\240\240\240\240\240\240" "\240\240\240\240\240\240\240\240\240\240cdccddcccddd"; char invalid_RRR[] = "aaaaaaaaaaaaaaaaaaaa" "\240\240\240\240\240\240\240\240\240\240" "\240\240\240\240\240\240\240\240\240\240cccccccccccccccccccc"; /* -- */ int main () { void *p = malloc (1); /* Prevent AIX linker from removing variables. */ return ctable1[0] + ctable2[0] + int1dim[0] + int2dim[0][0] + int3dim[0][0][0] + int4dim[0][0][0][0] + teststring[0] + *parrays -> array1 + a1[0] + a2[0]; free (p); }
37.988417
85
0.630654
7f6aefc0b88108c21cc650c425a748283112635a
9,851
c
C
CWE-119/source_files/199319/uninit_pointer.c
CGCL-codes/VulDeePecker
98610f3e116df97a1e819ffc81fbc7f6f138a8f2
[ "Apache-2.0" ]
185
2017-12-14T08:18:15.000Z
2022-03-30T02:58:36.000Z
CWE-119/source_files/199319/uninit_pointer.c
CGCL-codes/VulDeePecker
98610f3e116df97a1e819ffc81fbc7f6f138a8f2
[ "Apache-2.0" ]
11
2018-01-30T23:31:20.000Z
2022-01-17T05:03:56.000Z
CWE-119/source_files/199319/uninit_pointer.c
CGCL-codes/VulDeePecker
98610f3e116df97a1e819ffc81fbc7f6f138a8f2
[ "Apache-2.0" ]
87
2018-01-10T08:12:32.000Z
2022-02-19T10:29:31.000Z
/********Software Analysis - FY2013*************/ /* * File Name: uninit_pointer.c * Defect Classification * --------------------- * Defect Type: Pointer related defects * Defect Sub-type: Uninitialized pointer * Description: Defect Code to identify uninitialized pointer access in the code flow */ /* * uninit_pointer.c * * Created on: Sep 20, 2013 * Author: hemalatha */ #include "HeaderFile.h" char ** uninit_pointer_016_gbl_doubleptr; /* * Types of defects: Uninitialized pointer * Complexity: When using a single pointer int Variable - Loading */ void uninit_pointer_001 () { int a = 5; int *p ; int ret; ret = *p; /*Tool should detect this line as error*/ /*ERROR:Uninitialized pointer*/ } /* * Types of defects: Uninitialized pointer * Complexity: 1 single pointer int Variable Write */ void uninit_pointer_002 () { int a; int *p ; *p = 1; /*Tool should detect this line as error*/ /*ERROR:Uninitialized pointer*/ } /* * Types of defects: Uninitialized pointer * Complexity: When using a double pointer int Variable Write */ void uninit_pointer_003 () { int **pp; int *p; int a = 0; int ret; pp = &p; ret = **pp; /*Tool should detect this line as error*/ /*ERROR:Uninitialized pointer*/ } /* * Types of defects: Uninitialized pointer * Complexity: 1 single pointer int Function arguments Loading */ void uninit_pointer_004_func_001 (int *p) { int ret; ret = 0; } void uninit_pointer_004 () { int a = 0; int *p ; uninit_pointer_004_func_001(p);/*Tool should detect this line as error*/ /*ERROR:Uninitialized pointer*/ } /* * Types of defects: Uninitialized pointer * Complexity: pointer arrays int Function arguments Loading */ void uninit_pointer_005_func_001 (int *pbuf[]) { int buf1[6] = {1, 2, 3, 4, 5, 6}; int buf2[6] = {1, 2, 3, 4, 5, 6}; int buf3[6] = {1, 2, 3, 4, 5, 6}; int buf4[6] = {1, 2, 3, 4, 5, 6}; int buf5[6] = {1, 2, 3, 4, 5, 6}; pbuf[0] = buf1; pbuf[2] = buf3; pbuf[3] = buf4; pbuf[4] = buf5; int ret; ret = pbuf[1][1]; } void uninit_pointer_005 () { int *pbuf[5]; uninit_pointer_005_func_001(pbuf);/*Tool should detect this line as error*/ /*ERROR:Uninitialized pointer*/ } /* * Types of defects: Uninitialized pointer * Complexity: double pointer int Function arguments Write */ void uninit_pointer_006_func_001 (int **pp) { **pp = 1;/*Tool should detect this line as error*/ /*ERROR:Uninitialized pointer*/ } void uninit_pointer_006 () { int a; int *p; uninit_pointer_006_func_001(&p); } /* * Types of defects: Uninitialized pointer * Complexity: When using a double char pointer arrays */ void uninit_pointer_007 () { char *buf1=strdup("String1"); char *buf2; char *buf3=strdup("String3"); char *buf4=strdup("String4"); char *buf5=strdup("String5"); if (!buf1 || !buf3 || !buf4 || !buf5) return; char **pbuf[5] = {&buf2, &buf3, &buf4, &buf5}; int i,j=4; for(i=0;i<5;i++) { *((*pbuf[i])+j)='a';/*Tool should detect this line as error*/ /*ERROR:Uninitialized pointer*/ } free(buf1); free(buf3); free(buf4); free(buf5); } /* * Types of defects: Uninitialized pointer * Complexity: structure int Function arguments Loading */ typedef struct { int a; int b; int uninit; } uninit_pointer_008_s_001; void uninit_pointer_008_func_001 (uninit_pointer_008_s_001 *p) { int ret; p->uninit=ret; } void uninit_pointer_008 () { uninit_pointer_008_s_001 s; s.a = 1; s.b = 1; uninit_pointer_008_func_001(&s);/*Tool should detect this line as error*/ /*ERROR:Uninitialized pointer*/ } /* * Types of defects: Uninitialized pointer * Complexity: When using a pointer to char and initialized based on return value of function */ int uninit_pointer_009_func_001(int flag) { int ret; if (flag ==0) ret = 0; else ret=flag+1; return ret; } void uninit_pointer_009() { char *buf,buf1[25]; int flag=10; if(uninit_pointer_009_func_001(flag)==0) { buf = "This is a string"; } if(uninit_pointer_009_func_001(flag)>0) { strcpy(buf1,buf);/*Tool should detect this line as error*/ /*ERROR:Uninitialized pointer*/ } } /* * Types of defects: Uninitialized pointer * Complexity: void pointer to data passed from one function to another */ void uninit_pointer_010_func_001 (void * vptr) { /* cast void pointer to a pointer of the appropriate type */ char * * cptr = (char * *)vptr; char * buf ; buf = (*cptr);/*Tool should detect this line as error*/ /*ERROR:Uninitialized pointer*/ } void uninit_pointer_010 () { void *buf1; uninit_pointer_010_func_001(&buf1); } /* * Types of defects: Uninitialized pointer * Complexity: When using a unsigned int pointer and partially initialized in a infinite loop */ void uninit_pointer_011 () { unsigned int * ptr,a=0; ptr = (unsigned int *)malloc(10*sizeof(unsigned int *)); int i; if (ptr!=NULL) { while(1) { for(i=0; i<10/2; i++) { ptr[i] = i; } break; } while(1) { for(i=0; i<10; i++) { a += ptr[i];/*Tool should detect this line as error*/ /*ERROR:Uninitialized pointer*/ } break; } } } /* * Types of defects: Uninitialized pointer * Complexity: When using a pointer to float , pointing to 1D array */ void uninit_pointer_012 () { float * fptr; float arr[10]; fptr = arr; int i; for(i=0; i<10/2; i++) { fptr[i] = (float)i; } for(i=0; i<10; i++) { arr[i] = ++fptr[i];/*Tool should detect this line as error*/ /*ERROR:Uninitialized pointer*/ } } /* * Types of defects: Uninitialized pointer * Complexity: Double int pointer partially initialized with 2D array */ void uninit_pointer_013 () { int **ptr = (int**) malloc(5*sizeof(int*)); int i,j; for(i=0;i<5;i++) ptr[i]=(int*) malloc(5*sizeof(int)); int arr[3][3] = {{1,2,3}, {11,12,13}, {21,22,23}}; for(i=0;i<3;i++) { for(j=0;j<3;j++) { *(*(ptr+i)+j)= arr[i][j];/*Tool should detect this line as error*/ /*ERROR:Uninitialized pointer*/ } free(ptr[i]); ptr[i] = NULL; } free(ptr); ptr = NULL; } /* * Types of defects: uninitialized variable * Complexity: Structure passed as function parameter and based on the return value of function another structure is initialized */ typedef struct { int a; int b; int uninit; } uninit_pointer_014_s_001; uninit_pointer_014_s_001 *s; void uninit_pointer_014_func_001 (int flag) { switch (flag) { case 1: { s = (uninit_pointer_014_s_001 *)calloc(1,sizeof(uninit_pointer_014_s_001)); if(s!=NULL) { s->a = 10; s->b = 10; } break; } case 2: { s = (uninit_pointer_014_s_001 *)calloc(1,sizeof(uninit_pointer_014_s_001)); if(s!=NULL) { s->a = 20; s->b = 20; } break; } default: { break; } } } void uninit_pointer_014 () { uninit_pointer_014_s_001 r; uninit_pointer_014_func_001 (1); if(s!=NULL) { r = *s;/*Tool should detect this line as error*/ /*ERROR:Uninitialized pointer*/ free(s); } } /* * Types of defects: Uninitialized pointer * Complexity: int variable initialized with function return value using enumeration */ typedef enum {ZERO, ONE, TWO } values; void uninit_pointer_015_func_001 (int *ptr ) { values val = ONE; *ptr = val; } void uninit_pointer_015 () { int *ptr; uninit_pointer_015_func_001(ptr);/*Tool should detect this line as error*/ /*ERROR:Uninitialized pointer*/ } /* * Types of defects: Uninitialized pointer * Complexity: global char double pointer int variable initialized in another function */ int uninit_pointer_016_func_001(int flag) { int ret =0; if (flag ==0) ret = 0; else ret=1; return ret; } void uninit_pointer_016_func_002() { int i; if(uninit_pointer_016_func_001(0)==0) { uninit_pointer_016_gbl_doubleptr=(char**) malloc(10*sizeof(char*)); for(i=0;i<10;i++) { uninit_pointer_016_gbl_doubleptr[i]=(char*) malloc(10*sizeof(char)); if(i<5) strcpy(uninit_pointer_016_gbl_doubleptr[i],"STRING00"); } } } void uninit_pointer_016() { int flag=0,i; char *s=(char*) malloc(10*sizeof(char)); if(uninit_pointer_016_func_001(flag)==0) { uninit_pointer_016_func_002(); } if(uninit_pointer_016_gbl_doubleptr!=NULL) { for(i=0;i<10;i++) { if(uninit_pointer_016_gbl_doubleptr[i] !=NULL) { if(i==7) strcpy(s,uninit_pointer_016_gbl_doubleptr[i]);/*Tool should detect this line as error*/ /*ERROR:Uninitialized pointer*/ free (uninit_pointer_016_gbl_doubleptr[i]); } } free(uninit_pointer_016_gbl_doubleptr); free(s); } } /* * Types of defects: Uninitialized pointer * Complexity:Uninitialized pointer main function */ extern volatile int vflag; void uninit_pointer_main () { if (vflag == 1 || vflag ==888) { uninit_pointer_001(); } if (vflag == 2 || vflag ==888) { uninit_pointer_002(); } if (vflag == 3 || vflag ==888) { uninit_pointer_003(); } if (vflag == 4 || vflag ==888) { uninit_pointer_004(); } if (vflag == 5 || vflag ==888) { uninit_pointer_005(); } if (vflag == 6 || vflag ==888) { uninit_pointer_006(); } if (vflag == 7 || vflag ==888) { uninit_pointer_007(); } if (vflag == 8 || vflag ==888) { uninit_pointer_008(); } if (vflag == 9 || vflag ==888) { uninit_pointer_009(); } if (vflag == 10 || vflag ==888) { uninit_pointer_010(); } if (vflag == 11 || vflag ==888) { uninit_pointer_011(); } if (vflag == 12 || vflag ==888) { uninit_pointer_012(); } if (vflag == 13 || vflag ==888) { uninit_pointer_013(); } if (vflag == 14 || vflag ==888) { uninit_pointer_014(); } if (vflag == 15 || vflag ==888) { uninit_pointer_015(); } if (vflag == 16 || vflag ==888) { uninit_pointer_016(); } }
19.662675
128
0.638108
3d14c7ce5e01f897bc88bba0f754f6ed158bb52a
7,737
h
C
lib/dnscore/include/dnscore/packet_reader.h
epo13/yadifa
b33a1badf250d4f86e93bd963544de7bbdf78555
[ "BSD-3-Clause" ]
null
null
null
lib/dnscore/include/dnscore/packet_reader.h
epo13/yadifa
b33a1badf250d4f86e93bd963544de7bbdf78555
[ "BSD-3-Clause" ]
null
null
null
lib/dnscore/include/dnscore/packet_reader.h
epo13/yadifa
b33a1badf250d4f86e93bd963544de7bbdf78555
[ "BSD-3-Clause" ]
null
null
null
/*------------------------------------------------------------------------------ * * Copyright (c) 2011-2020, EURid vzw. All rights reserved. * The YADIFA TM software product is provided under the BSD 3-clause license: * * 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 EURid 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. * *------------------------------------------------------------------------------ * */ /** @defgroup dnspacket DNS Messages * @ingroup dnscore * @brief * * * * @{ * *----------------------------------------------------------------------------*/ #ifndef _PACKET_READER_H #define _PACKET_READER_H #include <dnscore/sys_types.h> #include <dnscore/host_address.h> #include <dnscore/message.h> #include <dnscore/dns_resource_record.h> #ifdef __cplusplus extern "C" { #endif /* dynupdate */ /* reads and unpack */ typedef struct packet_unpack_reader_data packet_unpack_reader_data; struct packet_unpack_reader_data { const u8* packet; u32 packet_size; u32 offset; }; static inline void packet_reader_init_at(packet_unpack_reader_data* reader, const u8* buffer, u32 buffer_size, u32 position) { reader->packet = buffer; reader->packet_size = buffer_size; reader->offset = position; } static inline void packet_reader_init(packet_unpack_reader_data* reader, const u8* buffer, u32 buffer_size) { packet_reader_init_at(reader, buffer, buffer_size, 0); } static inline void packet_reader_init_from_message_at(packet_unpack_reader_data* reader, const message_data *mesg, u32 position) { packet_reader_init_at(reader, message_get_buffer_const(mesg), message_get_size(mesg), position); } static inline void packet_reader_init_from_message(packet_unpack_reader_data* reader, const message_data *mesg) { packet_reader_init_from_message_at(reader, mesg, DNS_HEADER_LENGTH); } static inline ya_result packet_reader_opcode(packet_unpack_reader_data* reader) { if(reader->packet_size >= DNS_HEADER_LENGTH) { return MESSAGE_OP(reader->packet) >> OPCODE_SHIFT; } else { return UNEXPECTED_EOF; } } /* fqdn + type + class */ ya_result packet_reader_read_zone_record(packet_unpack_reader_data* reader, u8* output_buffer, u32 len); ya_result packet_reader_skip_zone_record(packet_unpack_reader_data* reader); ya_result packet_reader_skip_query_section(packet_unpack_reader_data* reader); ya_result packet_reader_skip_section(packet_unpack_reader_data* reader, int section); /* fqdn + type + class + ttl + size + rdata */ ya_result packet_reader_read_record(packet_unpack_reader_data* reader, u8 *output_buffer, u32 len); ya_result packet_reader_read_dns_resource_record(packet_unpack_reader_data* reader, dns_resource_record *rr); /** * Note that the last parameter is the buffer size and the data size to be read is right after the type. */ ya_result packet_reader_read_rdata(packet_unpack_reader_data* reader, u16 type, u32 rdata_size, u8 *buffer, u32 buffer_size); ya_result packet_reader_read_fqdn(packet_unpack_reader_data* reader, u8 *output_buffer, u32 len); ya_result packet_reader_read(packet_unpack_reader_data* reader, void *output_buffer, u32 len); static inline void packet_reader_read_unchecked(packet_unpack_reader_data* reader, void *output_buffer, u32 len) { MEMCOPY(output_buffer, &reader->packet[reader->offset], len); reader->offset += len; } static inline const void *packet_reader_get_current_ptr_const(const packet_unpack_reader_data* reader, u16 size) { if(reader->offset + size <= reader->packet_size) { return &reader->packet[reader->offset]; } else { return NULL; } } ya_result packet_reader_read_u16(packet_unpack_reader_data* reader, u16 *val); ya_result packet_reader_read_dnstype(packet_unpack_reader_data* reader); ya_result packet_reader_read_dnsclass(packet_unpack_reader_data* reader); ya_result packet_reader_skip_query(packet_unpack_reader_data* reader, const u8 *domain, u16 dnstype, u16 dnsclass); ya_result packet_reader_read_u32(packet_unpack_reader_data* reader, u32 *val); static inline void packet_reader_read_u16_unchecked(packet_unpack_reader_data* reader, u16 *val) { *val = GET_U16_AT(reader->packet[reader->offset]); reader->offset += 2; } static inline void packet_reader_read_u32_unchecked(packet_unpack_reader_data* reader, u32 *val) { *val = GET_U32_AT(reader->packet[reader->offset]); reader->offset += 4; } static inline ya_result packet_reader_read_s32(packet_unpack_reader_data* reader, s32 *val) { return packet_reader_read_u32(reader, (u32*)val); } static inline void packet_reader_read_s32_unchecked(packet_unpack_reader_data* reader, s32 *val) { packet_reader_read_u32_unchecked(reader, (u32*)val); } static inline ya_result packet_reader_skip(packet_unpack_reader_data* reader, u32 len) { if((reader->offset += len) > reader->packet_size) { reader->offset = reader->packet_size; return UNEXPECTED_EOF; /* unexpected EOF */ } return len; } static inline void packet_reader_skip_unchecked(packet_unpack_reader_data* reader, u32 len) { reader->offset += len; } static inline size_t packet_reader_available(packet_unpack_reader_data* reader) { return reader->packet_size - reader->offset; } void packet_reader_rewind(packet_unpack_reader_data* reader); ya_result packet_reader_skip_fqdn(packet_unpack_reader_data* reader); ya_result packet_reader_skip_record(packet_unpack_reader_data* reader); /* two tools functions for the controller */ ya_result packet_reader_read_utf8(packet_unpack_reader_data *reader, u16 rdatasize, u16 rclass, char **txt, bool dryrun); ya_result packet_reader_read_remote_server(packet_unpack_reader_data *reader, u16 rdatasize, u16 rclass, host_address **ha, bool dryrun); /* static inline u8* packet_reader_get_next_u8_ptr(packet_unpack_reader_data *reader) { return &reader->packet[reader->offset]; } */ static inline const u8* packet_reader_get_next_u8_ptr_const(const packet_unpack_reader_data *reader) { return &reader->packet[reader->offset]; } static inline void packet_reader_set_position(packet_unpack_reader_data *reader, u32 position) { reader->offset = position; } #ifdef __cplusplus } #endif #endif /* _PACKET_READER_H */ /** @} */
33.349138
137
0.745638
fa0d038cd8a8eaec8ff358d7ba979385af2bc11f
8,635
c
C
unqlite_nif.c
cyoucmi/unqlite-nif
53df61bcde91c882af8741b2a0c3e98c9f443925
[ "MIT" ]
6
2015-09-26T04:41:14.000Z
2020-05-29T20:10:22.000Z
unqlite_nif.c
cyoucmi/unqlite-nif
53df61bcde91c882af8741b2a0c3e98c9f443925
[ "MIT" ]
null
null
null
unqlite_nif.c
cyoucmi/unqlite-nif
53df61bcde91c882af8741b2a0c3e98c9f443925
[ "MIT" ]
null
null
null
#include <stdlib.h> #include <stdio.h> #include <string.h> #include "unqlite/unqlite.h" #include "erl_nif.h" #define MAX_PATH 256 static ErlNifResourceType *UnqliteResourceType; static unqlite *pDb; static void UnqliteResourceDtor(ErlNifEnv *env, void *obj){ struct unqlite_kv_cursor **cursor = obj; unqlite_kv_cursor_release(pDb, *cursor); } /*加载unqlite_nif*/ static int unqlite_load(ErlNifEnv *env, void **priv_data, ERL_NIF_TERM load_info); /*卸载unqlite_nif*/ static void unqlite_unload(ErlNifEnv *env, void *priv_data); static ERL_NIF_TERM unqlite_init(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM make_fatal_tuple_info(unqlite *pDb, const char *zMsg, ErlNifEnv *env){ const char *zErr = NULL; if (pDb){ int iLen = 0; unqlite_config(pDb, UNQLITE_CONFIG_ERR_LOG, &zErr, &iLen); }else{ if(zMsg) { zErr = zMsg; } } return enif_make_tuple2(env, enif_make_atom(env, "error"), enif_make_string(env, zErr, ERL_NIF_LATIN1)); } static int unqlite_load(ErlNifEnv *env, void **priv_data, ERL_NIF_TERM load_info){ pDb = NULL; ErlNifResourceFlags tried; UnqliteResourceType = enif_open_resource_type(env, NULL, "unqlite", UnqliteResourceDtor, ERL_NIF_RT_CREATE,&tried); return 0; }; static void unqlite_unload(ErlNifEnv *env, void *priv_data){ unqlite_close(pDb); } static ERL_NIF_TERM unqlite_init(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){ char buf[MAX_PATH]; size_t buf_size = MAX_PATH; if( enif_get_atom(env, argv[0], buf, buf_size, ERL_NIF_LATIN1) <= 0){/*获取失败*/ strcpy(buf, "unqlite_test.db");/**读取默认值*/ } /* Open our database */ int rc = unqlite_open(&pDb, buf, UNQLITE_OPEN_CREATE); if( rc != UNQLITE_OK ){ return make_fatal_tuple_info(0,"Out of memory", env); } return enif_make_atom(env, "ok"); } static ERL_NIF_TERM unqlite_set(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){ ErlNifBinary key_bin; ErlNifBinary value_bin; enif_inspect_binary(env, argv[0], &key_bin); enif_inspect_binary(env, argv[1], &value_bin); int rc = unqlite_kv_store(pDb, key_bin.data, key_bin.size, value_bin.data, value_bin.size); if( rc != UNQLITE_OK ){ return make_fatal_tuple_info(pDb, 0, env); } return enif_make_atom(env, "ok"); } static ERL_NIF_TERM unqlite_get(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){ ErlNifBinary key_bin; unqlite_int64 nBytes; //Data length enif_inspect_binary(env, argv[0], &key_bin); int rc = unqlite_kv_fetch(pDb,key_bin.data,key_bin.size,NULL,&nBytes); if( rc != UNQLITE_OK ){ if( rc == UNQLITE_NOTFOUND){ return enif_make_tuple2(env, enif_make_atom(env, "error"), enif_make_atom(env, "not_found")); }else{ return make_fatal_tuple_info(pDb, 0, env); } } ErlNifBinary value_bin; if (!enif_alloc_binary(nBytes, &value_bin)) { return enif_make_badarg(env); } unqlite_kv_fetch(pDb,key_bin.data,key_bin.size,value_bin.data,&nBytes); return enif_make_binary(env, &value_bin); } static ERL_NIF_TERM unqlite_del(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){ ErlNifBinary key_bin; enif_inspect_binary(env, argv[0], &key_bin); int rc = unqlite_kv_delete(pDb, key_bin.data, key_bin.size); if( rc != UNQLITE_OK ){ if( rc == UNQLITE_NOTFOUND){ return enif_make_tuple2(env, enif_make_atom(env, "error"), enif_make_atom(env, "not_found")); }else{ return make_fatal_tuple_info(pDb, 0, env); } } return enif_make_atom(env, "ok"); } static ERL_NIF_TERM unqlite_commit1(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){ int rc = unqlite_commit(pDb); if( rc != UNQLITE_OK ){ return make_fatal_tuple_info(pDb, 0, env); } return enif_make_atom(env, "ok"); } static ERL_NIF_TERM unqlite_rollback1(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){ int rc = unqlite_rollback(pDb); if( rc != UNQLITE_OK ){ return make_fatal_tuple_info(pDb, 0, env); } return enif_make_atom(env, "ok"); } static ERL_NIF_TERM unqlite_init_cursor(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){ struct unqlite_kv_cursor **pp_cursor = (struct unqlite_kv_cursor**)enif_alloc_resource(UnqliteResourceType, sizeof(unqlite_kv_cursor*)); int rc = unqlite_kv_cursor_init(pDb, pp_cursor); if( rc != UNQLITE_OK ){ return make_fatal_tuple_info(pDb, 0, env); } ERL_NIF_TERM ret = enif_make_resource(env, (void*)pp_cursor); enif_release_resource(pp_cursor); return ret; } static ERL_NIF_TERM unqlite_cursor_first_entry(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){ struct unqlite_kv_cursor **pp_cursor = NULL; if (!enif_get_resource(env, argv[0], UnqliteResourceType, (void**)&pp_cursor)) { return enif_make_badarg(env); } int rc = unqlite_kv_cursor_first_entry(*pp_cursor); if( rc != UNQLITE_OK ){ return make_fatal_tuple_info(pDb, 0, env); } return enif_make_atom(env, "ok"); } static ERL_NIF_TERM unqlite_cursor_last_entry(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){ struct unqlite_kv_cursor **pp_cursor = NULL; if (!enif_get_resource(env, argv[0], UnqliteResourceType, (void**)&pp_cursor)) { return enif_make_badarg(env); } int rc = unqlite_kv_cursor_last_entry(*pp_cursor); if( rc != UNQLITE_OK ){ return make_fatal_tuple_info(pDb, 0, env); } return enif_make_atom(env, "ok"); } static ERL_NIF_TERM unqlite_cursor_valid_entry(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){ struct unqlite_kv_cursor **pp_cursor = NULL; if (!enif_get_resource(env, argv[0], UnqliteResourceType, (void**)&pp_cursor)) { return enif_make_badarg(env); } int rc = unqlite_kv_cursor_valid_entry(*pp_cursor); if( rc ){ return enif_make_atom(env, "true"); }else{ return enif_make_atom(env, "false"); } } static ERL_NIF_TERM unqlite_cursor_next_entry(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){ struct unqlite_kv_cursor **pp_cursor = NULL; if (!enif_get_resource(env, argv[0], UnqliteResourceType, (void**)&pp_cursor)) { return enif_make_badarg(env); } int rc = unqlite_kv_cursor_next_entry(*pp_cursor); if( rc != UNQLITE_OK ){ return make_fatal_tuple_info(pDb, 0, env); } return enif_make_atom(env, "ok"); } static ERL_NIF_TERM unqlite_cursor_prev_entry(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){ struct unqlite_kv_cursor **pp_cursor = NULL; if (!enif_get_resource(env, argv[0], UnqliteResourceType, (void**)&pp_cursor)) { return enif_make_badarg(env); } int rc = unqlite_kv_cursor_prev_entry(*pp_cursor); if( rc != UNQLITE_OK ){ return make_fatal_tuple_info(pDb, 0, env); } return enif_make_atom(env, "ok"); } static ERL_NIF_TERM unqlite_cursor_entry(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){ struct unqlite_kv_cursor **pp_cursor = NULL; if (!enif_get_resource(env, argv[0], UnqliteResourceType, (void**)&pp_cursor)) { return enif_make_badarg(env); } unqlite_int64 value_len; //Data length int key_len; int rc = unqlite_kv_cursor_key(*pp_cursor, NULL, &key_len); if( rc != UNQLITE_OK ){ return make_fatal_tuple_info(pDb, 0, env); } ErlNifBinary key_bin; if (!enif_alloc_binary(key_len, &key_bin)) { return enif_make_badarg(env); } unqlite_kv_cursor_key(*pp_cursor, key_bin.data, &key_len); rc = unqlite_kv_cursor_data(*pp_cursor, NULL, &value_len); if( rc != UNQLITE_OK ){ return make_fatal_tuple_info(pDb, 0, env); } ErlNifBinary value_bin; if (!enif_alloc_binary(value_len, &value_bin)) { return enif_make_badarg(env); } unqlite_kv_cursor_data(*pp_cursor, value_bin.data, &value_len); return enif_make_tuple2(env, enif_make_binary(env, &key_bin), enif_make_binary(env, &value_bin)) ; } static ErlNifFunc nif_funcs[] = { {"init", 1, unqlite_init}, {"set", 2, unqlite_set}, {"get", 1, unqlite_get}, {"del", 1, unqlite_del}, {"commit", 0, unqlite_commit1}, {"rollback", 0, unqlite_rollback1}, {"init_cursor", 0, unqlite_init_cursor}, {"cursor_first_entry", 1, unqlite_cursor_first_entry}, {"cursor_last_entry", 1, unqlite_cursor_last_entry}, {"cursor_valid_entry", 1, unqlite_cursor_valid_entry}, {"cursor_next_entry", 1, unqlite_cursor_next_entry}, {"cursor_prev_entry", 1, unqlite_cursor_prev_entry}, {"cursor_entry", 1, unqlite_cursor_entry}, }; ERL_NIF_INIT(unqlite_nif, nif_funcs, unqlite_load, NULL, NULL, unqlite_unload);
31.514599
140
0.701679
36516c8ddc7f054a18aeaccdcc6226050fa6217c
61,344
c
C
usr/src/sbin/ping6/ping6.c
sizeofvoid/ifconfigd
bdff4b2cec6d572c1450cb44f32c0bdab1b49e5f
[ "BSD-2-Clause" ]
2
2020-04-15T13:39:01.000Z
2020-08-28T01:27:00.000Z
usr/src/sbin/ping6/ping6.c
sizeofvoid/ifconfigd
bdff4b2cec6d572c1450cb44f32c0bdab1b49e5f
[ "BSD-2-Clause" ]
null
null
null
usr/src/sbin/ping6/ping6.c
sizeofvoid/ifconfigd
bdff4b2cec6d572c1450cb44f32c0bdab1b49e5f
[ "BSD-2-Clause" ]
1
2020-08-28T01:25:41.000Z
2020-08-28T01:25:41.000Z
/* $OpenBSD: ping6.c,v 1.81 2011/03/03 00:30:31 mikeb Exp $ */ /* $KAME: ping6.c,v 1.163 2002/10/25 02:19:06 itojun 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. */ /* BSDI ping.c,v 2.3 1996/01/21 17:56:50 jch Exp */ /* * Copyright (c) 1989, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Mike Muuss. * * 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 University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * Using the InterNet Control Message Protocol (ICMP) "ECHO" facility, * measure round-trip-delays and packet loss across network paths. * * Author - * Mike Muuss * U. S. Army Ballistic Research Laboratory * December, 1983 * * Status - * Public Domain. Distribution Unlimited. * Bugs - * More statistics could always be gathered. * This program has to run SUID to ROOT to access the ICMP socket. */ #include <sys/param.h> #include <sys/uio.h> #include <sys/socket.h> #include <sys/time.h> #include <net/if.h> #include <net/route.h> #include <netinet/in.h> #include <netinet/ip6.h> #include <netinet/icmp6.h> #include <netinet/ip_ah.h> #include <arpa/inet.h> #include <arpa/nameser.h> #include <netdb.h> #include <ctype.h> #include <err.h> #include <errno.h> #include <fcntl.h> #include <math.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <poll.h> #include <md5.h> struct tv32 { u_int32_t tv32_sec; u_int32_t tv32_usec; }; #define MAXPACKETLEN 131072 #define IP6LEN 40 #define ICMP6ECHOLEN 8 /* icmp echo header len excluding time */ #define ICMP6ECHOTMLEN sizeof(struct tv32) #define ICMP6_NIQLEN (ICMP6ECHOLEN + 8) /* FQDN case, 64 bits of nonce + 32 bits ttl */ #define ICMP6_NIRLEN (ICMP6ECHOLEN + 12) #define EXTRA 256 /* for AH and various other headers. weird. */ #define DEFDATALEN ICMP6ECHOTMLEN #define MAXDATALEN MAXPACKETLEN - IP6LEN - ICMP6ECHOLEN #define NROUTES 9 /* number of record route slots */ #define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */ #define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */ #define SET(bit) (A(bit) |= B(bit)) #define CLR(bit) (A(bit) &= (~B(bit))) #define TST(bit) (A(bit) & B(bit)) #define F_FLOOD 0x0001 #define F_INTERVAL 0x0002 #define F_PINGFILLED 0x0008 #define F_QUIET 0x0010 #define F_RROUTE 0x0020 #define F_SO_DEBUG 0x0040 #define F_VERBOSE 0x0100 #define F_NODEADDR 0x0800 #define F_FQDN 0x1000 #define F_INTERFACE 0x2000 #define F_SRCADDR 0x4000 #ifdef IPV6_REACHCONF #define F_REACHCONF 0x8000 #endif #define F_HOSTNAME 0x10000 #define F_FQDNOLD 0x20000 #define F_NIGROUP 0x40000 #define F_SUPTYPES 0x80000 #define F_NOMINMTU 0x100000 #define F_AUD_RECV 0x200000 #define F_AUD_MISS 0x400000 #define F_NOUSERDATA (F_NODEADDR | F_FQDN | F_FQDNOLD | F_SUPTYPES) u_int options; #define IN6LEN sizeof(struct in6_addr) #define SA6LEN sizeof(struct sockaddr_in6) #define DUMMY_PORT 10101 #define SIN6(s) ((struct sockaddr_in6 *)(s)) /* * MAX_DUP_CHK is the number of bits in received table, i.e. the maximum * number of received sequence numbers we can keep track of. Change 128 * to 8192 for complete accuracy... */ #define MAX_DUP_CHK (8 * 8192) int mx_dup_ck = MAX_DUP_CHK; char rcvd_tbl[MAX_DUP_CHK / 8]; struct addrinfo *res; struct sockaddr_in6 dst; /* who to ping6 */ struct sockaddr_in6 src; /* src addr of this packet */ socklen_t srclen; int datalen = DEFDATALEN; int s; /* socket file descriptor */ u_char outpack[MAXPACKETLEN]; char BSPACE = '\b'; /* characters written for flood */ char DOT = '.'; char *hostname; int ident; /* process id to identify our packets */ u_int8_t nonce[8]; /* nonce field for node information */ int hoplimit = -1; /* hoplimit */ /* counters */ long npackets; /* max packets to transmit */ long nreceived; /* # of packets we got back */ long nrepeats; /* number of duplicates */ long ntransmitted; /* sequence # for outbound packets = #sent */ unsigned long nmissedmax = 1; /* max value of ntransmitted - nreceived - 1 */ struct timeval interval = {1, 0}; /* interval between packets */ /* timing */ int timing; /* flag to do timing */ double tmin = 999999999.0; /* minimum round trip time */ double tmax = 0.0; /* maximum round trip time */ double tsum = 0.0; /* sum of all times, for doing average */ double tsumsq = 0.0; /* sum of all times squared, for std. dev. */ /* for node addresses */ u_short naflags; /* for ancillary data(advanced API) */ struct msghdr smsghdr; struct iovec smsgiov; char *scmsg = 0; volatile sig_atomic_t seenalrm; volatile sig_atomic_t seenint; #ifdef SIGINFO volatile sig_atomic_t seeninfo; #endif int main(int, char *[]); void fill(char *, char *); int get_hoplim(struct msghdr *); int get_pathmtu(struct msghdr *); struct in6_pktinfo *get_rcvpktinfo(struct msghdr *); void onsignal(int); void retransmit(void); void onint(int); size_t pingerlen(void); int pinger(void); const char *pr_addr(struct sockaddr *, int); void pr_icmph(struct icmp6_hdr *, u_char *); void pr_iph(struct ip6_hdr *); void pr_suptypes(struct icmp6_nodeinfo *, size_t); void pr_nodeaddr(struct icmp6_nodeinfo *, int); int myechoreply(const struct icmp6_hdr *); int mynireply(const struct icmp6_nodeinfo *); char *dnsdecode(const u_char **, const u_char *, const u_char *, char *, size_t); void pr_pack(u_char *, int, struct msghdr *); void pr_exthdrs(struct msghdr *); void pr_ip6opt(void *); void pr_rthdr(void *); int pr_bitrange(u_int32_t, int, int); void pr_retip(struct ip6_hdr *, u_char *); void summary(int); void tvsub(struct timeval *, struct timeval *); char *nigroup(char *); void usage(void); int main(int argc, char *argv[]) { struct itimerval itimer; struct sockaddr_in6 from; int timeout; struct addrinfo hints; struct pollfd fdmaskp[1]; int cc, i; int ch, hold, packlen, preload, optval, ret_ga; u_char *datap, *packet; char *e, *target, *ifname = NULL, *gateway = NULL; const char *errstr; int ip6optlen = 0; struct cmsghdr *scmsgp = NULL; #if defined(SO_SNDBUF) && defined(SO_RCVBUF) u_long lsockbufsize; int sockbufsize = 0; #endif int usepktinfo = 0; struct in6_pktinfo *pktinfo = NULL; struct ip6_rthdr *rthdr = NULL; double intval; size_t rthlen; int mflag = 0; uid_t uid; /* just to be sure */ memset(&smsghdr, 0, sizeof(smsghdr)); memset(&smsgiov, 0, sizeof(smsgiov)); preload = 0; datap = &outpack[ICMP6ECHOLEN + ICMP6ECHOTMLEN]; while ((ch = getopt(argc, argv, "a:b:c:dEefHg:h:I:i:l:mnNp:qRS:s:tvwW")) != -1) { switch (ch) { case 'a': { char *cp; options &= ~F_NOUSERDATA; options |= F_NODEADDR; for (cp = optarg; *cp != '\0'; cp++) { switch (*cp) { case 'a': naflags |= NI_NODEADDR_FLAG_ALL; break; case 'c': case 'C': naflags |= NI_NODEADDR_FLAG_COMPAT; break; case 'l': case 'L': naflags |= NI_NODEADDR_FLAG_LINKLOCAL; break; case 's': case 'S': naflags |= NI_NODEADDR_FLAG_SITELOCAL; break; case 'g': case 'G': naflags |= NI_NODEADDR_FLAG_GLOBAL; break; case 'A': /* experimental. not in the spec */ #ifdef NI_NODEADDR_FLAG_ANYCAST naflags |= NI_NODEADDR_FLAG_ANYCAST; break; #else errx(1, "-a A is not supported on the platform"); /*NOTREACHED*/ #endif default: usage(); /*NOTREACHED*/ } } break; } case 'b': #if defined(SO_SNDBUF) && defined(SO_RCVBUF) errno = 0; e = NULL; lsockbufsize = strtoul(optarg, &e, 10); sockbufsize = lsockbufsize; if (errno || !*optarg || *e || sockbufsize != lsockbufsize) errx(1, "invalid socket buffer size"); #else errx(1, "-b option ignored: SO_SNDBUF/SO_RCVBUF socket options not supported"); #endif break; case 'c': npackets = (unsigned long)strtonum(optarg, 0, INT_MAX, &errstr); if (errstr) errx(1, "number of packets to transmit is %s: %s", errstr, optarg); break; case 'd': options |= F_SO_DEBUG; break; case 'E': options |= F_AUD_MISS; break; case 'e': options |= F_AUD_RECV; break; case 'f': if (getuid()) { errno = EPERM; errx(1, "Must be superuser to flood ping"); } options |= F_FLOOD; setbuf(stdout, (char *)NULL); break; case 'g': gateway = optarg; break; case 'H': options |= F_HOSTNAME; break; case 'h': /* hoplimit */ hoplimit = strtol(optarg, &e, 10); if (*optarg == '\0' || *e != '\0') errx(1, "illegal hoplimit %s", optarg); if (255 < hoplimit || hoplimit < -1) errx(1, "illegal hoplimit -- %s", optarg); break; case 'I': ifname = optarg; options |= F_INTERFACE; usepktinfo++; break; case 'i': /* wait between sending packets */ intval = strtod(optarg, &e); if (*optarg == '\0' || *e != '\0') errx(1, "illegal timing interval %s", optarg); if (intval < 1 && getuid()) { errx(1, "%s: only root may use interval < 1s", strerror(EPERM)); } interval.tv_sec = (long)intval; interval.tv_usec = (long)((intval - interval.tv_sec) * 1000000); if (interval.tv_sec < 0) errx(1, "illegal timing interval %s", optarg); /* less than 1/Hz does not make sense */ if (interval.tv_sec == 0 && interval.tv_usec < 10000) { warnx("too small interval, raised to 0.01"); interval.tv_usec = 10000; } options |= F_INTERVAL; break; case 'l': if (getuid()) { errno = EPERM; errx(1, "Must be superuser to preload"); } preload = strtol(optarg, &e, 10); if (preload < 0 || *optarg == '\0' || *e != '\0') errx(1, "illegal preload value -- %s", optarg); break; case 'm': mflag++; break; case 'n': options &= ~F_HOSTNAME; break; case 'N': options |= F_NIGROUP; break; case 'p': /* fill buffer with user pattern */ options |= F_PINGFILLED; fill((char *)datap, optarg); break; case 'q': options |= F_QUIET; break; case 'R': #ifdef IPV6_REACHCONF options |= F_REACHCONF; break; #else errx(1, "-R is not supported in this configuration"); #endif case 'S': memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_flags = AI_NUMERICHOST; /* allow hostname? */ hints.ai_family = AF_INET6; hints.ai_socktype = SOCK_RAW; hints.ai_protocol = IPPROTO_ICMPV6; ret_ga = getaddrinfo(optarg, NULL, &hints, &res); if (ret_ga) { errx(1, "invalid source address: %s", gai_strerror(ret_ga)); } /* * res->ai_family must be AF_INET6 and res->ai_addrlen * must be sizeof(src). */ memcpy(&src, res->ai_addr, res->ai_addrlen); srclen = res->ai_addrlen; freeaddrinfo(res); options |= F_SRCADDR; break; case 's': /* size of packet to send */ datalen = strtol(optarg, &e, 10); if (datalen <= 0 || *optarg == '\0' || *e != '\0') errx(1, "illegal datalen value -- %s", optarg); if (datalen > MAXDATALEN) { errx(1, "datalen value too large, maximum is %d", MAXDATALEN); } break; case 't': options &= ~F_NOUSERDATA; options |= F_SUPTYPES; break; case 'v': options |= F_VERBOSE; break; case 'w': options &= ~F_NOUSERDATA; options |= F_FQDN; break; case 'W': options &= ~F_NOUSERDATA; options |= F_FQDNOLD; break; default: usage(); /*NOTREACHED*/ } } argc -= optind; argv += optind; if (argc < 1) { usage(); /*NOTREACHED*/ } if (argc > 1) { rthlen = inet6_rth_space(IPV6_RTHDR_TYPE_0, argc - 1); if (rthlen == 0) { errx(1, "too many intermediate hops"); /*NOTREACHED*/ } ip6optlen += CMSG_SPACE(rthlen); } if (options & F_NIGROUP) { target = nigroup(argv[argc - 1]); if (target == NULL) { usage(); /*NOTREACHED*/ } } else target = argv[argc - 1]; /* getaddrinfo */ memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_flags = AI_CANONNAME; hints.ai_family = AF_INET6; hints.ai_socktype = SOCK_RAW; hints.ai_protocol = IPPROTO_ICMPV6; ret_ga = getaddrinfo(target, NULL, &hints, &res); if (ret_ga) errx(1, "%s", gai_strerror(ret_ga)); if (res->ai_canonname) hostname = res->ai_canonname; else hostname = target; if (!res->ai_addr) errx(1, "getaddrinfo failed"); memcpy(&dst, res->ai_addr, res->ai_addrlen); if ((s = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) < 0) err(1, "socket"); /* set the source address if specified. */ if ((options & F_SRCADDR) && bind(s, (struct sockaddr *)&src, srclen) != 0) { err(1, "bind"); } /* set the gateway (next hop) if specified */ if (gateway) { struct addrinfo ghints, *gres; int error; memset(&ghints, 0, sizeof(ghints)); ghints.ai_family = AF_INET6; ghints.ai_socktype = SOCK_RAW; ghints.ai_protocol = IPPROTO_ICMPV6; error = getaddrinfo(gateway, NULL, &ghints, &gres); if (error) { errx(1, "getaddrinfo for the gateway %s: %s", gateway, gai_strerror(error)); } if (gres->ai_next && (options & F_VERBOSE)) warnx("gateway resolves to multiple addresses"); if (setsockopt(s, IPPROTO_IPV6, IPV6_NEXTHOP, gres->ai_addr, gres->ai_addrlen)) { err(1, "setsockopt(IPV6_NEXTHOP)"); } freeaddrinfo(gres); } /* * let the kernel pass extension headers of incoming packets, * for privileged socket options */ if ((options & F_VERBOSE) != 0) { int opton = 1; if (setsockopt(s, IPPROTO_IPV6, IPV6_RECVHOPOPTS, &opton, (socklen_t)sizeof(opton))) err(1, "setsockopt(IPV6_RECVHOPOPTS)"); if (setsockopt(s, IPPROTO_IPV6, IPV6_RECVDSTOPTS, &opton, (socklen_t)sizeof(opton))) err(1, "setsockopt(IPV6_RECVDSTOPTS)"); } /* revoke root privilege */ uid = getuid(); if (setresuid(uid, uid, uid) == -1) err(1, "setresuid"); if ((options & F_FLOOD) && (options & F_INTERVAL)) errx(1, "-f and -i incompatible options"); if ((options & F_FLOOD) && (options & (F_AUD_RECV | F_AUD_MISS))) warnx("No audible output for flood pings"); if ((options & F_NOUSERDATA) == 0) { if (datalen >= sizeof(struct tv32)) { /* we can time transfer */ timing = 1; } else timing = 0; /* in F_VERBOSE case, we may get non-echoreply packets*/ if (options & F_VERBOSE) packlen = 2048 + IP6LEN + ICMP6ECHOLEN + EXTRA; else packlen = datalen + IP6LEN + ICMP6ECHOLEN + EXTRA; } else { /* suppress timing for node information query */ timing = 0; datalen = 2048; packlen = 2048 + IP6LEN + ICMP6ECHOLEN + EXTRA; } if (!(packet = malloc(packlen))) err(1, "Unable to allocate packet"); if (!(options & F_PINGFILLED)) for (i = ICMP6ECHOLEN; i < packlen; ++i) *datap++ = i; ident = getpid() & 0xFFFF; memset(nonce, 0, sizeof(nonce)); for (i = 0; i < sizeof(nonce); i += sizeof(u_int32_t)) *((u_int32_t *)&nonce[i]) = arc4random(); hold = 1; if (options & F_SO_DEBUG) (void)setsockopt(s, SOL_SOCKET, SO_DEBUG, &hold, (socklen_t)sizeof(hold)); optval = IPV6_DEFHLIM; if (IN6_IS_ADDR_MULTICAST(&dst.sin6_addr)) if (setsockopt(s, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &optval, (socklen_t)sizeof(optval)) == -1) err(1, "IPV6_MULTICAST_HOPS"); if (mflag != 1) { optval = mflag > 1 ? 0 : 1; if (setsockopt(s, IPPROTO_IPV6, IPV6_USE_MIN_MTU, &optval, (socklen_t)sizeof(optval)) == -1) err(1, "setsockopt(IPV6_USE_MIN_MTU)"); } else { optval = 1; if (setsockopt(s, IPPROTO_IPV6, IPV6_RECVPATHMTU, &optval, sizeof(optval)) == -1) err(1, "setsockopt(IPV6_RECVPATHMTU)"); } #ifdef ICMP6_FILTER { struct icmp6_filter filt; if (!(options & F_VERBOSE)) { ICMP6_FILTER_SETBLOCKALL(&filt); if ((options & F_FQDN) || (options & F_FQDNOLD) || (options & F_NODEADDR) || (options & F_SUPTYPES)) ICMP6_FILTER_SETPASS(ICMP6_NI_REPLY, &filt); else ICMP6_FILTER_SETPASS(ICMP6_ECHO_REPLY, &filt); } else { ICMP6_FILTER_SETPASSALL(&filt); } if (setsockopt(s, IPPROTO_ICMPV6, ICMP6_FILTER, &filt, (socklen_t)sizeof(filt)) < 0) err(1, "setsockopt(ICMP6_FILTER)"); } #endif /*ICMP6_FILTER*/ /* let the kernel pass extension headers of incoming packets */ if ((options & F_VERBOSE) != 0) { int opton = 1; if (setsockopt(s, IPPROTO_IPV6, IPV6_RECVRTHDR, &opton, sizeof(opton))) err(1, "setsockopt(IPV6_RECVRTHDR)"); } /* optval = 1; if (IN6_IS_ADDR_MULTICAST(&dst.sin6_addr)) if (setsockopt(s, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &optval, sizeof(optval)) == -1) err(1, "IPV6_MULTICAST_LOOP"); */ /* Specify the outgoing interface and/or the source address */ if (usepktinfo) ip6optlen += CMSG_SPACE(sizeof(struct in6_pktinfo)); if (hoplimit != -1) ip6optlen += CMSG_SPACE(sizeof(int)); #ifdef IPV6_REACHCONF if (options & F_REACHCONF) ip6optlen += CMSG_SPACE(0); #endif /* set IP6 packet options */ if (ip6optlen) { if ((scmsg = malloc(ip6optlen)) == 0) errx(1, "can't allocate enough memory"); smsghdr.msg_control = (caddr_t)scmsg; smsghdr.msg_controllen = ip6optlen; scmsgp = (struct cmsghdr *)scmsg; } if (usepktinfo) { pktinfo = (struct in6_pktinfo *)(CMSG_DATA(scmsgp)); memset(pktinfo, 0, sizeof(*pktinfo)); scmsgp->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo)); scmsgp->cmsg_level = IPPROTO_IPV6; scmsgp->cmsg_type = IPV6_PKTINFO; scmsgp = CMSG_NXTHDR(&smsghdr, scmsgp); } /* set the outgoing interface */ if (ifname) { /* pktinfo must have already been allocated */ if ((pktinfo->ipi6_ifindex = if_nametoindex(ifname)) == 0) errx(1, "%s: invalid interface name", ifname); } if (hoplimit != -1) { scmsgp->cmsg_len = CMSG_LEN(sizeof(int)); scmsgp->cmsg_level = IPPROTO_IPV6; scmsgp->cmsg_type = IPV6_HOPLIMIT; *(int *)(CMSG_DATA(scmsgp)) = hoplimit; scmsgp = CMSG_NXTHDR(&smsghdr, scmsgp); } #ifdef IPV6_REACHCONF if (options & F_REACHCONF) { scmsgp->cmsg_len = CMSG_LEN(0); scmsgp->cmsg_level = IPPROTO_IPV6; scmsgp->cmsg_type = IPV6_REACHCONF; scmsgp = CMSG_NXTHDR(&smsghdr, scmsgp); } #endif if (argc > 1) { /* some intermediate addrs are specified */ int hops, error; int rthdrlen; rthdrlen = inet6_rth_space(IPV6_RTHDR_TYPE_0, argc - 1); scmsgp->cmsg_len = CMSG_LEN(rthdrlen); scmsgp->cmsg_level = IPPROTO_IPV6; scmsgp->cmsg_type = IPV6_RTHDR; rthdr = (struct ip6_rthdr *)CMSG_DATA(scmsgp); rthdr = inet6_rth_init((void *)rthdr, rthdrlen, IPV6_RTHDR_TYPE_0, argc - 1); if (rthdr == NULL) errx(1, "can't initialize rthdr"); for (hops = 0; hops < argc - 1; hops++) { struct addrinfo *iaip; if ((error = getaddrinfo(argv[hops], NULL, &hints, &iaip))) errx(1, "%s", gai_strerror(error)); if (SIN6(iaip->ai_addr)->sin6_family != AF_INET6) errx(1, "bad addr family of an intermediate addr"); if (inet6_rth_add(rthdr, &(SIN6(iaip->ai_addr))->sin6_addr)) errx(1, "can't add an intermediate node"); freeaddrinfo(iaip); } scmsgp = CMSG_NXTHDR(&smsghdr, scmsgp); } if (!(options & F_SRCADDR)) { /* * get the source address. XXX since we revoked the root * privilege, we cannot use a raw socket for this. */ int dummy; socklen_t len = sizeof(src); if ((dummy = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) err(1, "UDP socket"); src.sin6_family = AF_INET6; src.sin6_addr = dst.sin6_addr; src.sin6_port = ntohs(DUMMY_PORT); src.sin6_scope_id = dst.sin6_scope_id; if (pktinfo && setsockopt(dummy, IPPROTO_IPV6, IPV6_PKTINFO, (void *)pktinfo, sizeof(*pktinfo))) err(1, "UDP setsockopt(IPV6_PKTINFO)"); if (hoplimit != -1 && setsockopt(dummy, IPPROTO_IPV6, IPV6_UNICAST_HOPS, (void *)&hoplimit, sizeof(hoplimit))) err(1, "UDP setsockopt(IPV6_UNICAST_HOPS)"); if (hoplimit != -1 && setsockopt(dummy, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (void *)&hoplimit, sizeof(hoplimit))) err(1, "UDP setsockopt(IPV6_MULTICAST_HOPS)"); if (rthdr && setsockopt(dummy, IPPROTO_IPV6, IPV6_RTHDR, (void *)rthdr, (rthdr->ip6r_len + 1) << 3)) err(1, "UDP setsockopt(IPV6_RTHDR)"); if (connect(dummy, (struct sockaddr *)&src, len) < 0) err(1, "UDP connect"); if (getsockname(dummy, (struct sockaddr *)&src, &len) < 0) err(1, "getsockname"); close(dummy); } #if defined(SO_SNDBUF) && defined(SO_RCVBUF) if (sockbufsize) { if (datalen > sockbufsize) warnx("you need -b to increase socket buffer size"); if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, &sockbufsize, (socklen_t)sizeof(sockbufsize)) < 0) err(1, "setsockopt(SO_SNDBUF)"); if (setsockopt(s, SOL_SOCKET, SO_RCVBUF, &sockbufsize, (socklen_t)sizeof(sockbufsize)) < 0) err(1, "setsockopt(SO_RCVBUF)"); } else { if (datalen > 8 * 1024) /*XXX*/ warnx("you need -b to increase socket buffer size"); /* * When pinging the broadcast address, you can get a lot of * answers. Doing something so evil is useful if you are trying * to stress the ethernet, or just want to fill the arp cache * to get some stuff for /etc/ethers. */ hold = 48 * 1024; setsockopt(s, SOL_SOCKET, SO_RCVBUF, &hold, (socklen_t)sizeof(hold)); } #endif optval = 1; if (setsockopt(s, IPPROTO_IPV6, IPV6_RECVPKTINFO, &optval, (socklen_t)sizeof(optval)) < 0) warn("setsockopt(IPV6_RECVPKTINFO)"); /* XXX err? */ if (setsockopt(s, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &optval, (socklen_t)sizeof(optval)) < 0) warn("setsockopt(IPV6_RECVHOPLIMIT)"); /* XXX err? */ printf("PING6(%lu=40+8+%lu bytes) ", (unsigned long)(40 + pingerlen()), (unsigned long)(pingerlen() - 8)); printf("%s --> ", pr_addr((struct sockaddr *)&src, sizeof(src))); printf("%s\n", pr_addr((struct sockaddr *)&dst, sizeof(dst))); while (preload--) /* Fire off them quickies. */ (void)pinger(); (void)signal(SIGINT, onsignal); #ifdef SIGINFO (void)signal(SIGINFO, onsignal); #endif if ((options & F_FLOOD) == 0) { (void)signal(SIGALRM, onsignal); itimer.it_interval = interval; itimer.it_value = interval; (void)setitimer(ITIMER_REAL, &itimer, NULL); if (ntransmitted == 0) retransmit(); } seenalrm = seenint = 0; #ifdef SIGINFO seeninfo = 0; #endif for (;;) { struct msghdr m; union { struct cmsghdr hdr; u_char buf[CMSG_SPACE(1024)]; } cmsgbuf; struct iovec iov[2]; /* signal handling */ if (seenalrm) { retransmit(); seenalrm = 0; continue; } if (seenint) { onint(SIGINT); seenint = 0; continue; } #ifdef SIGINFO if (seeninfo) { summary(0); seeninfo = 0; continue; } #endif if (options & F_FLOOD) { (void)pinger(); timeout = 10; } else timeout = INFTIM; fdmaskp[0].fd = s; fdmaskp[0].events = POLLIN; cc = poll(fdmaskp, 1, timeout); if (cc < 0) { if (errno != EINTR) { warn("poll"); sleep(1); } continue; } else if (cc == 0) continue; m.msg_name = &from; m.msg_namelen = sizeof(from); memset(&iov, 0, sizeof(iov)); iov[0].iov_base = (caddr_t)packet; iov[0].iov_len = packlen; m.msg_iov = iov; m.msg_iovlen = 1; m.msg_control = (caddr_t)&cmsgbuf.buf; m.msg_controllen = sizeof(cmsgbuf.buf); cc = recvmsg(s, &m, 0); if (cc < 0) { if (errno != EINTR) { warn("recvmsg"); sleep(1); } continue; } else if (cc == 0) { int mtu; /* * receive control messages only. Process the * exceptions (currently the only possibility is * a path MTU notification.) */ if ((mtu = get_pathmtu(&m)) > 0) { if ((options & F_VERBOSE) != 0) { printf("new path MTU (%d) is " "notified\n", mtu); } } continue; } else { /* * an ICMPv6 message (probably an echoreply) arrived. */ pr_pack(packet, cc, &m); } if (npackets && nreceived >= npackets) break; if (ntransmitted - nreceived - 1 > nmissedmax) { nmissedmax = ntransmitted - nreceived - 1; if (!(options & F_FLOOD) && (options & F_AUD_MISS)) (void)fputc('\a', stderr); } } summary(0); exit(nreceived == 0); } void onsignal(int sig) { switch (sig) { case SIGALRM: seenalrm++; break; case SIGINT: seenint++; break; #ifdef SIGINFO case SIGINFO: seeninfo++; break; #endif } } /* * retransmit -- * This routine transmits another ping6. */ void retransmit(void) { struct itimerval itimer; if (pinger() == 0) return; /* * If we're not transmitting any more packets, change the timer * to wait two round-trip times if we've received any packets or * ten seconds if we haven't. */ #define MAXWAIT 10 if (nreceived) { itimer.it_value.tv_sec = 2 * tmax / 1000; if (itimer.it_value.tv_sec == 0) itimer.it_value.tv_sec = 1; } else itimer.it_value.tv_sec = MAXWAIT; itimer.it_interval.tv_sec = 0; itimer.it_interval.tv_usec = 0; itimer.it_value.tv_usec = 0; (void)signal(SIGALRM, onint); (void)setitimer(ITIMER_REAL, &itimer, NULL); } /* * pinger -- * Compose and transmit an ICMP ECHO REQUEST packet. The IP packet * will be added on by the kernel. The ID field is our UNIX process ID, * and the sequence number is an ascending integer. The first 8 bytes * of the data portion are used to hold a UNIX "timeval" struct in VAX * byte-order, to compute the round-trip time. */ size_t pingerlen(void) { size_t l; if (options & F_FQDN) l = ICMP6_NIQLEN + sizeof(dst.sin6_addr); else if (options & F_FQDNOLD) l = ICMP6_NIQLEN; else if (options & F_NODEADDR) l = ICMP6_NIQLEN + sizeof(dst.sin6_addr); else if (options & F_SUPTYPES) l = ICMP6_NIQLEN; else l = ICMP6ECHOLEN + datalen; return l; } int pinger(void) { struct icmp6_hdr *icp; struct iovec iov[2]; int i, cc; struct icmp6_nodeinfo *nip; int seq; if (npackets && ntransmitted >= npackets) return(-1); /* no more transmission */ icp = (struct icmp6_hdr *)outpack; nip = (struct icmp6_nodeinfo *)outpack; memset(icp, 0, sizeof(*icp)); icp->icmp6_cksum = 0; seq = ntransmitted++; CLR(seq % mx_dup_ck); if (options & F_FQDN) { icp->icmp6_type = ICMP6_NI_QUERY; icp->icmp6_code = ICMP6_NI_SUBJ_IPV6; nip->ni_qtype = htons(NI_QTYPE_FQDN); nip->ni_flags = htons(0); memcpy(nip->icmp6_ni_nonce, nonce, sizeof(nip->icmp6_ni_nonce)); *(u_int16_t *)nip->icmp6_ni_nonce = ntohs(seq); memcpy(&outpack[ICMP6_NIQLEN], &dst.sin6_addr, sizeof(dst.sin6_addr)); cc = ICMP6_NIQLEN + sizeof(dst.sin6_addr); datalen = 0; } else if (options & F_FQDNOLD) { /* packet format in 03 draft - no Subject data on queries */ icp->icmp6_type = ICMP6_NI_QUERY; icp->icmp6_code = 0; /* code field is always 0 */ nip->ni_qtype = htons(NI_QTYPE_FQDN); nip->ni_flags = htons(0); memcpy(nip->icmp6_ni_nonce, nonce, sizeof(nip->icmp6_ni_nonce)); *(u_int16_t *)nip->icmp6_ni_nonce = ntohs(seq); cc = ICMP6_NIQLEN; datalen = 0; } else if (options & F_NODEADDR) { icp->icmp6_type = ICMP6_NI_QUERY; icp->icmp6_code = ICMP6_NI_SUBJ_IPV6; nip->ni_qtype = htons(NI_QTYPE_NODEADDR); nip->ni_flags = naflags; memcpy(nip->icmp6_ni_nonce, nonce, sizeof(nip->icmp6_ni_nonce)); *(u_int16_t *)nip->icmp6_ni_nonce = ntohs(seq); memcpy(&outpack[ICMP6_NIQLEN], &dst.sin6_addr, sizeof(dst.sin6_addr)); cc = ICMP6_NIQLEN + sizeof(dst.sin6_addr); datalen = 0; } else if (options & F_SUPTYPES) { icp->icmp6_type = ICMP6_NI_QUERY; icp->icmp6_code = ICMP6_NI_SUBJ_FQDN; /*empty*/ nip->ni_qtype = htons(NI_QTYPE_SUPTYPES); /* we support compressed bitmap */ nip->ni_flags = NI_SUPTYPE_FLAG_COMPRESS; memcpy(nip->icmp6_ni_nonce, nonce, sizeof(nip->icmp6_ni_nonce)); *(u_int16_t *)nip->icmp6_ni_nonce = ntohs(seq); cc = ICMP6_NIQLEN; datalen = 0; } else { icp->icmp6_type = ICMP6_ECHO_REQUEST; icp->icmp6_code = 0; icp->icmp6_id = htons(ident); icp->icmp6_seq = ntohs(seq); if (timing) { struct timeval tv; struct tv32 tv32; (void)gettimeofday(&tv, NULL); tv32.tv32_sec = htonl(tv.tv_sec); tv32.tv32_usec = htonl(tv.tv_usec); bcopy(&tv32, &outpack[ICMP6ECHOLEN], sizeof(tv32)); } cc = ICMP6ECHOLEN + datalen; } #ifdef DIAGNOSTIC if (pingerlen() != cc) errx(1, "internal error; length mismatch"); #endif smsghdr.msg_name = &dst; smsghdr.msg_namelen = sizeof(dst); memset(&iov, 0, sizeof(iov)); iov[0].iov_base = (caddr_t)outpack; iov[0].iov_len = cc; smsghdr.msg_iov = iov; smsghdr.msg_iovlen = 1; i = sendmsg(s, &smsghdr, 0); if (i < 0 || i != cc) { if (i < 0) warn("sendmsg"); (void)printf("ping6: wrote %s %d chars, ret=%d\n", hostname, cc, i); } if (!(options & F_QUIET) && options & F_FLOOD) (void)write(STDOUT_FILENO, &DOT, 1); return(0); } int myechoreply(const struct icmp6_hdr *icp) { if (ntohs(icp->icmp6_id) == ident) return 1; else return 0; } int mynireply(const struct icmp6_nodeinfo *nip) { if (memcmp(nip->icmp6_ni_nonce + sizeof(u_int16_t), nonce + sizeof(u_int16_t), sizeof(nonce) - sizeof(u_int16_t)) == 0) return 1; else return 0; } char * dnsdecode(const u_char **sp, const u_char *ep, const u_char *base, char *buf, size_t bufsiz) { int i; const u_char *cp; char cresult[MAXDNAME + 1]; const u_char *comp; int l; cp = *sp; *buf = '\0'; if (cp >= ep) return NULL; while (cp < ep) { i = *cp; if (i == 0 || cp != *sp) { if (strlcat((char *)buf, ".", bufsiz) >= bufsiz) return NULL; /*result overrun*/ } if (i == 0) break; cp++; if ((i & 0xc0) == 0xc0 && cp - base > (i & 0x3f)) { /* DNS compression */ if (!base) return NULL; comp = base + (i & 0x3f); if (dnsdecode(&comp, cp, base, cresult, sizeof(cresult)) == NULL) return NULL; if (strlcat(buf, cresult, bufsiz) >= bufsiz) return NULL; /*result overrun*/ break; } else if ((i & 0x3f) == i) { if (i > ep - cp) return NULL; /*source overrun*/ while (i-- > 0 && cp < ep) { l = snprintf(cresult, sizeof(cresult), isprint(*cp) ? "%c" : "\\%03o", *cp & 0xff); if (l >= sizeof(cresult) || l < 0) return NULL; if (strlcat(buf, cresult, bufsiz) >= bufsiz) return NULL; /*result overrun*/ cp++; } } else return NULL; /*invalid label*/ } if (i != 0) return NULL; /*not terminated*/ cp++; *sp = cp; return buf; } /* * pr_pack -- * Print out the packet, if it came from us. This logic is necessary * because ALL readers of the ICMP socket get a copy of ALL ICMP packets * which arrive ('tis only fair). This permits multiple copies of this * program to be run without having intermingled output (or statistics!). */ void pr_pack(u_char *buf, int cc, struct msghdr *mhdr) { #define safeputc(c) printf((isprint((c)) ? "%c" : "\\%03o"), c) struct icmp6_hdr *icp; struct icmp6_nodeinfo *ni; int i; int hoplim; struct sockaddr *from; int fromlen; u_char *cp = NULL, *dp, *end = buf + cc; struct in6_pktinfo *pktinfo = NULL; struct timeval tv, tp; struct tv32 tv32; double triptime = 0; int dupflag; size_t off; int oldfqdn; u_int16_t seq; char dnsname[MAXDNAME + 1]; (void)gettimeofday(&tv, NULL); if (!mhdr || !mhdr->msg_name || mhdr->msg_namelen != sizeof(struct sockaddr_in6) || ((struct sockaddr *)mhdr->msg_name)->sa_family != AF_INET6) { if (options & F_VERBOSE) warnx("invalid peername"); return; } from = (struct sockaddr *)mhdr->msg_name; fromlen = mhdr->msg_namelen; if (cc < sizeof(struct icmp6_hdr)) { if (options & F_VERBOSE) warnx("packet too short (%d bytes) from %s", cc, pr_addr(from, fromlen)); return; } icp = (struct icmp6_hdr *)buf; ni = (struct icmp6_nodeinfo *)buf; off = 0; if ((hoplim = get_hoplim(mhdr)) == -1) { warnx("failed to get receiving hop limit"); return; } if ((pktinfo = get_rcvpktinfo(mhdr)) == NULL) { warnx("failed to get receiving packet information"); return; } if (icp->icmp6_type == ICMP6_ECHO_REPLY && myechoreply(icp)) { seq = ntohs(icp->icmp6_seq); ++nreceived; if (timing) { bcopy(icp + 1, &tv32, sizeof(tv32)); tp.tv_sec = ntohl(tv32.tv32_sec); tp.tv_usec = ntohl(tv32.tv32_usec); tvsub(&tv, &tp); triptime = ((double)tv.tv_sec) * 1000.0 + ((double)tv.tv_usec) / 1000.0; tsum += triptime; tsumsq += triptime * triptime; if (triptime < tmin) tmin = triptime; if (triptime > tmax) tmax = triptime; } if (TST(seq % mx_dup_ck)) { ++nrepeats; --nreceived; dupflag = 1; } else { SET(seq % mx_dup_ck); dupflag = 0; } if (options & F_QUIET) return; if (options & F_FLOOD) (void)write(STDOUT_FILENO, &BSPACE, 1); else { (void)printf("%d bytes from %s, icmp_seq=%u", cc, pr_addr(from, fromlen), seq); (void)printf(" hlim=%d", hoplim); if ((options & F_VERBOSE) != 0) { struct sockaddr_in6 dstsa; memset(&dstsa, 0, sizeof(dstsa)); dstsa.sin6_family = AF_INET6; dstsa.sin6_len = sizeof(dstsa); dstsa.sin6_scope_id = pktinfo->ipi6_ifindex; dstsa.sin6_addr = pktinfo->ipi6_addr; (void)printf(" dst=%s", pr_addr((struct sockaddr *)&dstsa, sizeof(dstsa))); } if (timing) (void)printf(" time=%g ms", triptime); if (dupflag) (void)printf("(DUP!)"); if (options & F_AUD_RECV) (void)fputc('\a', stderr); /* check the data */ cp = buf + off + ICMP6ECHOLEN + ICMP6ECHOTMLEN; dp = outpack + ICMP6ECHOLEN + ICMP6ECHOTMLEN; if (cc != ICMP6ECHOLEN + datalen) { int delta = cc - (datalen + ICMP6ECHOLEN); (void)printf(" (%d bytes %s)", abs(delta), delta > 0 ? "extra" : "short"); end = buf + MIN(cc, ICMP6ECHOLEN + datalen); } for (i = 8; cp < end; ++i, ++cp, ++dp) { if (*cp != *dp) { (void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x", i, *dp, *cp); break; } } } } else if (icp->icmp6_type == ICMP6_NI_REPLY && mynireply(ni)) { seq = ntohs(*(u_int16_t *)ni->icmp6_ni_nonce); ++nreceived; if (TST(seq % mx_dup_ck)) { ++nrepeats; --nreceived; dupflag = 1; } else { SET(seq % mx_dup_ck); dupflag = 0; } if (options & F_QUIET) return; (void)printf("%d bytes from %s: ", cc, pr_addr(from, fromlen)); switch (ntohs(ni->ni_code)) { case ICMP6_NI_SUCCESS: break; case ICMP6_NI_REFUSED: printf("refused, type 0x%x", ntohs(ni->ni_type)); goto fqdnend; case ICMP6_NI_UNKNOWN: printf("unknown, type 0x%x", ntohs(ni->ni_type)); goto fqdnend; default: printf("unknown code 0x%x, type 0x%x", ntohs(ni->ni_code), ntohs(ni->ni_type)); goto fqdnend; } switch (ntohs(ni->ni_qtype)) { case NI_QTYPE_NOOP: printf("NodeInfo NOOP"); break; case NI_QTYPE_SUPTYPES: pr_suptypes(ni, end - (u_char *)ni); break; case NI_QTYPE_NODEADDR: pr_nodeaddr(ni, end - (u_char *)ni); break; case NI_QTYPE_FQDN: default: /* XXX: for backward compatibility */ cp = (u_char *)ni + ICMP6_NIRLEN; if (buf[off + ICMP6_NIRLEN] == cc - off - ICMP6_NIRLEN - 1) oldfqdn = 1; else oldfqdn = 0; if (oldfqdn) { cp++; /* skip length */ while (cp < end) { safeputc(*cp & 0xff); cp++; } } else { i = 0; while (cp < end) { if (dnsdecode((const u_char **)&cp, end, (const u_char *)(ni + 1), dnsname, sizeof(dnsname)) == NULL) { printf("???"); break; } /* * name-lookup special handling for * truncated name */ if (cp + 1 <= end && !*cp && strlen(dnsname) > 0) { dnsname[strlen(dnsname) - 1] = '\0'; cp++; } printf("%s%s", i > 0 ? "," : "", dnsname); } } if (options & F_VERBOSE) { int32_t ttl; int comma = 0; (void)printf(" ("); /*)*/ switch (ni->ni_code) { case ICMP6_NI_REFUSED: (void)printf("refused"); comma++; break; case ICMP6_NI_UNKNOWN: (void)printf("unknown qtype"); comma++; break; } if ((end - (u_char *)ni) < ICMP6_NIRLEN) { /* case of refusion, unknown */ /*(*/ putchar(')'); goto fqdnend; } ttl = (int32_t)ntohl(*(u_long *) &buf[off+ICMP6ECHOLEN+8]); if (comma) printf(","); if (!(ni->ni_flags & NI_FQDN_FLAG_VALIDTTL)) { (void)printf("TTL=%d:meaningless", (int)ttl); } else { if (ttl < 0) { (void)printf("TTL=%d:invalid", ttl); } else (void)printf("TTL=%d", ttl); } comma++; if (oldfqdn) { if (comma) printf(","); printf("03 draft"); comma++; } else { cp = (u_char *)ni + ICMP6_NIRLEN; if (cp == end) { if (comma) printf(","); printf("no name"); comma++; } } if (buf[off + ICMP6_NIRLEN] != cc - off - ICMP6_NIRLEN - 1 && oldfqdn) { if (comma) printf(","); (void)printf("invalid namelen:%d/%lu", buf[off + ICMP6_NIRLEN], (u_long)cc - off - ICMP6_NIRLEN - 1); comma++; } /*(*/ putchar(')'); } fqdnend: ; } } else { /* We've got something other than an ECHOREPLY */ if (!(options & F_VERBOSE)) return; (void)printf("%d bytes from %s: ", cc, pr_addr(from, fromlen)); pr_icmph(icp, end); } if (!(options & F_FLOOD)) { (void)putchar('\n'); if (options & F_VERBOSE) pr_exthdrs(mhdr); (void)fflush(stdout); } #undef safeputc } void pr_exthdrs(struct msghdr *mhdr) { struct cmsghdr *cm; for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm; cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) { if (cm->cmsg_level != IPPROTO_IPV6) continue; switch (cm->cmsg_type) { case IPV6_HOPOPTS: printf(" HbH Options: "); pr_ip6opt(CMSG_DATA(cm)); break; case IPV6_DSTOPTS: case IPV6_RTHDRDSTOPTS: printf(" Dst Options: "); pr_ip6opt(CMSG_DATA(cm)); break; case IPV6_RTHDR: printf(" Routing: "); pr_rthdr(CMSG_DATA(cm)); break; } } } void pr_ip6opt(void *extbuf) { struct ip6_hbh *ext; int currentlen; u_int8_t type; size_t extlen; socklen_t len; void *databuf; size_t offset; u_int16_t value2; u_int32_t value4; ext = (struct ip6_hbh *)extbuf; extlen = (ext->ip6h_len + 1) * 8; printf("nxt %u, len %u (%lu bytes)\n", ext->ip6h_nxt, (unsigned int)ext->ip6h_len, (unsigned long)extlen); currentlen = 0; while (1) { currentlen = inet6_opt_next(extbuf, extlen, currentlen, &type, &len, &databuf); if (currentlen == -1) break; switch (type) { /* * Note that inet6_opt_next automatically skips any padding * options. */ case IP6OPT_JUMBO: offset = 0; offset = inet6_opt_get_val(databuf, offset, &value4, sizeof(value4)); printf(" Jumbo Payload Opt: Length %u\n", (u_int32_t)ntohl(value4)); break; case IP6OPT_ROUTER_ALERT: offset = 0; offset = inet6_opt_get_val(databuf, offset, &value2, sizeof(value2)); printf(" Router Alert Opt: Type %u\n", ntohs(value2)); break; default: printf(" Received Opt %u len %lu\n", type, (unsigned long)len); break; } } return; } void pr_rthdr(void *extbuf) { struct in6_addr *in6; char ntopbuf[INET6_ADDRSTRLEN]; struct ip6_rthdr *rh = (struct ip6_rthdr *)extbuf; int i, segments; /* print fixed part of the header */ printf("nxt %u, len %u (%d bytes), type %u, ", rh->ip6r_nxt, rh->ip6r_len, (rh->ip6r_len + 1) << 3, rh->ip6r_type); if ((segments = inet6_rth_segments(extbuf)) >= 0) printf("%d segments, ", segments); else printf("segments unknown, "); printf("%d left\n", rh->ip6r_segleft); for (i = 0; i < segments; i++) { in6 = inet6_rth_getaddr(extbuf, i); if (in6 == NULL) printf(" [%d]<NULL>\n", i); else { if (!inet_ntop(AF_INET6, in6, ntopbuf, sizeof(ntopbuf))) strncpy(ntopbuf, "?", sizeof(ntopbuf)); printf(" [%d]%s\n", i, ntopbuf); } } return; } int pr_bitrange(u_int32_t v, int soff, int ii) { int off; int i; off = 0; while (off < 32) { /* shift till we have 0x01 */ if ((v & 0x01) == 0) { if (ii > 1) printf("-%u", soff + off - 1); ii = 0; switch (v & 0x0f) { case 0x00: v >>= 4; off += 4; continue; case 0x08: v >>= 3; off += 3; continue; case 0x04: case 0x0c: v >>= 2; off += 2; continue; default: v >>= 1; off += 1; continue; } } /* we have 0x01 with us */ for (i = 0; i < 32 - off; i++) { if ((v & (0x01 << i)) == 0) break; } if (!ii) printf(" %u", soff + off); ii += i; v >>= i; off += i; } return ii; } /* ni->qtype must be SUPTYPES */ void pr_suptypes(struct icmp6_nodeinfo *ni, size_t nilen) { size_t clen; u_int32_t v; const u_char *cp, *end; u_int16_t cur; struct cbit { u_int16_t words; /*32bit count*/ u_int16_t skip; } cbit; #define MAXQTYPES (1 << 16) size_t off; int b; cp = (u_char *)(ni + 1); end = ((u_char *)ni) + nilen; cur = 0; b = 0; printf("NodeInfo Supported Qtypes"); if (options & F_VERBOSE) { if (ni->ni_flags & NI_SUPTYPE_FLAG_COMPRESS) printf(", compressed bitmap"); else printf(", raw bitmap"); } while (cp < end) { clen = (size_t)(end - cp); if ((ni->ni_flags & NI_SUPTYPE_FLAG_COMPRESS) == 0) { if (clen == 0 || clen > MAXQTYPES / 8 || clen % sizeof(v)) { printf("???"); return; } } else { if (clen < sizeof(cbit) || clen % sizeof(v)) return; memcpy(&cbit, cp, sizeof(cbit)); if (sizeof(cbit) + ntohs(cbit.words) * sizeof(v) > clen) return; cp += sizeof(cbit); clen = ntohs(cbit.words) * sizeof(v); if (cur + clen * 8 + (u_long)ntohs(cbit.skip) * 32 > MAXQTYPES) return; } for (off = 0; off < clen; off += sizeof(v)) { memcpy(&v, cp + off, sizeof(v)); v = (u_int32_t)ntohl(v); b = pr_bitrange(v, (int)(cur + off * 8), b); } /* flush the remaining bits */ b = pr_bitrange(0, (int)(cur + off * 8), b); cp += clen; cur += clen * 8; if ((ni->ni_flags & NI_SUPTYPE_FLAG_COMPRESS) != 0) cur += ntohs(cbit.skip) * 32; } } /* ni->qtype must be NODEADDR */ void pr_nodeaddr(struct icmp6_nodeinfo *ni, int nilen) { u_char *cp = (u_char *)(ni + 1); char ntop_buf[INET6_ADDRSTRLEN]; int withttl = 0; nilen -= sizeof(struct icmp6_nodeinfo); if (options & F_VERBOSE) { switch (ni->ni_code) { case ICMP6_NI_REFUSED: (void)printf("refused"); break; case ICMP6_NI_UNKNOWN: (void)printf("unknown qtype"); break; } if (ni->ni_flags & NI_NODEADDR_FLAG_TRUNCATE) (void)printf(" truncated"); } putchar('\n'); if (nilen <= 0) printf(" no address\n"); /* * In icmp-name-lookups 05 and later, TTL of each returned address * is contained in the response. We try to detect the version * by the length of the data, but note that the detection algorithm * is incomplete. We assume the latest draft by default. */ if (nilen % (sizeof(u_int32_t) + sizeof(struct in6_addr)) == 0) withttl = 1; while (nilen > 0) { u_int32_t ttl; if (withttl) { /* XXX: alignment? */ ttl = (u_int32_t)ntohl(*(u_int32_t *)cp); cp += sizeof(u_int32_t); nilen -= sizeof(u_int32_t); } if (inet_ntop(AF_INET6, cp, ntop_buf, sizeof(ntop_buf)) == NULL) strncpy(ntop_buf, "?", sizeof(ntop_buf)); printf(" %s", ntop_buf); if (withttl) { if (ttl == 0xffffffff) { /* * XXX: can this convention be applied to all * type of TTL (i.e. non-ND TTL)? */ printf("(TTL=infty)"); } else printf("(TTL=%u)", ttl); } putchar('\n'); nilen -= sizeof(struct in6_addr); cp += sizeof(struct in6_addr); } } int get_hoplim(struct msghdr *mhdr) { struct cmsghdr *cm; for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm; cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) { if (cm->cmsg_len == 0) return(-1); if (cm->cmsg_level == IPPROTO_IPV6 && cm->cmsg_type == IPV6_HOPLIMIT && cm->cmsg_len == CMSG_LEN(sizeof(int))) return(*(int *)CMSG_DATA(cm)); } return(-1); } struct in6_pktinfo * get_rcvpktinfo(struct msghdr *mhdr) { struct cmsghdr *cm; for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm; cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) { if (cm->cmsg_len == 0) return(NULL); if (cm->cmsg_level == IPPROTO_IPV6 && cm->cmsg_type == IPV6_PKTINFO && cm->cmsg_len == CMSG_LEN(sizeof(struct in6_pktinfo))) return((struct in6_pktinfo *)CMSG_DATA(cm)); } return(NULL); } int get_pathmtu(struct msghdr *mhdr) { struct cmsghdr *cm; struct ip6_mtuinfo *mtuctl = NULL; for (cm = (struct cmsghdr *)CMSG_FIRSTHDR(mhdr); cm; cm = (struct cmsghdr *)CMSG_NXTHDR(mhdr, cm)) { if (cm->cmsg_len == 0) return(0); if (cm->cmsg_level == IPPROTO_IPV6 && cm->cmsg_type == IPV6_PATHMTU && cm->cmsg_len == CMSG_LEN(sizeof(struct ip6_mtuinfo))) { mtuctl = (struct ip6_mtuinfo *)CMSG_DATA(cm); /* * If the notified destination is different from * the one we are pinging, just ignore the info. * We check the scope ID only when both notified value * and our own value have non-0 values, because we may * have used the default scope zone ID for sending, * in which case the scope ID value is 0. */ if (!IN6_ARE_ADDR_EQUAL(&mtuctl->ip6m_addr.sin6_addr, &dst.sin6_addr) || (mtuctl->ip6m_addr.sin6_scope_id && dst.sin6_scope_id && mtuctl->ip6m_addr.sin6_scope_id != dst.sin6_scope_id)) { if ((options & F_VERBOSE) != 0) { printf("path MTU for %s is notified. " "(ignored)\n", pr_addr((struct sockaddr *)&mtuctl->ip6m_addr, sizeof(mtuctl->ip6m_addr))); } return(0); } /* * Ignore an invalid MTU. XXX: can we just believe * the kernel check? */ if (mtuctl->ip6m_mtu < IPV6_MMTU) return(0); /* notification for our destination. return the MTU. */ return((int)mtuctl->ip6m_mtu); } } return(0); } /* * tvsub -- * Subtract 2 timeval structs: out = out - in. Out is assumed to * be >= in. */ void tvsub(struct timeval *out, struct timeval *in) { if ((out->tv_usec -= in->tv_usec) < 0) { --out->tv_sec; out->tv_usec += 1000000; } out->tv_sec -= in->tv_sec; } /* * onint -- * SIGINT handler. */ void onint(int signo) { summary(signo); (void)signal(SIGINT, SIG_DFL); (void)kill(getpid(), SIGINT); if (signo) _exit(nreceived ? 0 : 1); else exit(nreceived ? 0 : 1); } /* * summary -- * Print out statistics. */ void summary(int signo) { char buf[8192], buft[8192]; buf[0] = '\0'; snprintf(buft, sizeof(buft), "\n--- %s ping6 statistics ---\n", hostname); strlcat(buf, buft, sizeof(buf)); snprintf(buft, sizeof(buft), "%ld packets transmitted, ", ntransmitted); strlcat(buf, buft, sizeof(buf)); snprintf(buft, sizeof(buft), "%ld packets received, ", nreceived); strlcat(buf, buft, sizeof(buf)); if (nrepeats) { snprintf(buft, sizeof(buft), "+%ld duplicates, ", nrepeats); strlcat(buf, buft, sizeof(buf)); } if (ntransmitted) { if (nreceived > ntransmitted) snprintf(buft, sizeof(buft), "-- somebody's duplicating packets!"); else snprintf(buft, sizeof(buft), "%.1lf%% packet loss", ((((double)ntransmitted - nreceived) * 100) / ntransmitted)); strlcat(buf, buft, sizeof(buf)); } strlcat(buf, "\n", sizeof(buf)); if (nreceived && timing) { /* Only display average to microseconds */ double num = nreceived + nrepeats; double avg = tsum / num; double dev = sqrt(tsumsq / num - avg * avg); snprintf(buft, sizeof(buft), "round-trip min/avg/max/std-dev = %.3f/%.3f/%.3f/%.3f ms\n", tmin, avg, tmax, dev); strlcat(buf, buft, sizeof(buf)); } write(STDOUT_FILENO, buf, strlen(buf)); if (signo == 0) (void)fflush(stdout); } /*subject type*/ static const char *niqcode[] = { "IPv6 address", "DNS label", /*or empty*/ "IPv4 address", }; /*result code*/ static const char *nircode[] = { "Success", "Refused", "Unknown", }; /* * pr_icmph -- * Print a descriptive string about an ICMP header. */ void pr_icmph(struct icmp6_hdr *icp, u_char *end) { char ntop_buf[INET6_ADDRSTRLEN]; struct nd_redirect *red; struct icmp6_nodeinfo *ni; char dnsname[MAXDNAME + 1]; const u_char *cp; size_t l; switch (icp->icmp6_type) { case ICMP6_DST_UNREACH: switch (icp->icmp6_code) { case ICMP6_DST_UNREACH_NOROUTE: (void)printf("No Route to Destination\n"); break; case ICMP6_DST_UNREACH_ADMIN: (void)printf("Destination Administratively " "Unreachable\n"); break; case ICMP6_DST_UNREACH_BEYONDSCOPE: (void)printf("Destination Unreachable Beyond Scope\n"); break; case ICMP6_DST_UNREACH_ADDR: (void)printf("Destination Host Unreachable\n"); break; case ICMP6_DST_UNREACH_NOPORT: (void)printf("Destination Port Unreachable\n"); break; default: (void)printf("Destination Unreachable, Bad Code: %d\n", icp->icmp6_code); break; } /* Print returned IP header information */ pr_retip((struct ip6_hdr *)(icp + 1), end); break; case ICMP6_PACKET_TOO_BIG: (void)printf("Packet too big mtu = %d\n", (int)ntohl(icp->icmp6_mtu)); pr_retip((struct ip6_hdr *)(icp + 1), end); break; case ICMP6_TIME_EXCEEDED: switch (icp->icmp6_code) { case ICMP6_TIME_EXCEED_TRANSIT: (void)printf("Time to live exceeded\n"); break; case ICMP6_TIME_EXCEED_REASSEMBLY: (void)printf("Frag reassembly time exceeded\n"); break; default: (void)printf("Time exceeded, Bad Code: %d\n", icp->icmp6_code); break; } pr_retip((struct ip6_hdr *)(icp + 1), end); break; case ICMP6_PARAM_PROB: (void)printf("Parameter problem: "); switch (icp->icmp6_code) { case ICMP6_PARAMPROB_HEADER: (void)printf("Erroneous Header "); break; case ICMP6_PARAMPROB_NEXTHEADER: (void)printf("Unknown Nextheader "); break; case ICMP6_PARAMPROB_OPTION: (void)printf("Unrecognized Option "); break; default: (void)printf("Bad code(%d) ", icp->icmp6_code); break; } (void)printf("pointer = 0x%02x\n", (u_int32_t)ntohl(icp->icmp6_pptr)); pr_retip((struct ip6_hdr *)(icp + 1), end); break; case ICMP6_ECHO_REQUEST: (void)printf("Echo Request"); /* XXX ID + Seq + Data */ break; case ICMP6_ECHO_REPLY: (void)printf("Echo Reply"); /* XXX ID + Seq + Data */ break; case ICMP6_MEMBERSHIP_QUERY: (void)printf("Listener Query"); break; case ICMP6_MEMBERSHIP_REPORT: (void)printf("Listener Report"); break; case ICMP6_MEMBERSHIP_REDUCTION: (void)printf("Listener Done"); break; case ND_ROUTER_SOLICIT: (void)printf("Router Solicitation"); break; case ND_ROUTER_ADVERT: (void)printf("Router Advertisement"); break; case ND_NEIGHBOR_SOLICIT: (void)printf("Neighbor Solicitation"); break; case ND_NEIGHBOR_ADVERT: (void)printf("Neighbor Advertisement"); break; case ND_REDIRECT: red = (struct nd_redirect *)icp; (void)printf("Redirect\n"); if (!inet_ntop(AF_INET6, &red->nd_rd_dst, ntop_buf, sizeof(ntop_buf))) strncpy(ntop_buf, "?", sizeof(ntop_buf)); (void)printf("Destination: %s", ntop_buf); if (!inet_ntop(AF_INET6, &red->nd_rd_target, ntop_buf, sizeof(ntop_buf))) strncpy(ntop_buf, "?", sizeof(ntop_buf)); (void)printf(" New Target: %s", ntop_buf); break; case ICMP6_NI_QUERY: (void)printf("Node Information Query"); /* XXX ID + Seq + Data */ ni = (struct icmp6_nodeinfo *)icp; l = end - (u_char *)(ni + 1); printf(", "); switch (ntohs(ni->ni_qtype)) { case NI_QTYPE_NOOP: (void)printf("NOOP"); break; case NI_QTYPE_SUPTYPES: (void)printf("Supported qtypes"); break; case NI_QTYPE_FQDN: (void)printf("DNS name"); break; case NI_QTYPE_NODEADDR: (void)printf("nodeaddr"); break; case NI_QTYPE_IPV4ADDR: (void)printf("IPv4 nodeaddr"); break; default: (void)printf("unknown qtype"); break; } if (options & F_VERBOSE) { switch (ni->ni_code) { case ICMP6_NI_SUBJ_IPV6: if (l == sizeof(struct in6_addr) && inet_ntop(AF_INET6, ni + 1, ntop_buf, sizeof(ntop_buf)) != NULL) { (void)printf(", subject=%s(%s)", niqcode[ni->ni_code], ntop_buf); } else { #if 1 /* backward compat to -W */ (void)printf(", oldfqdn"); #else (void)printf(", invalid"); #endif } break; case ICMP6_NI_SUBJ_FQDN: if (end == (u_char *)(ni + 1)) { (void)printf(", no subject"); break; } printf(", subject=%s", niqcode[ni->ni_code]); cp = (const u_char *)(ni + 1); if (dnsdecode(&cp, end, NULL, dnsname, sizeof(dnsname)) != NULL) printf("(%s)", dnsname); else printf("(invalid)"); break; case ICMP6_NI_SUBJ_IPV4: if (l == sizeof(struct in_addr) && inet_ntop(AF_INET, ni + 1, ntop_buf, sizeof(ntop_buf)) != NULL) { (void)printf(", subject=%s(%s)", niqcode[ni->ni_code], ntop_buf); } else (void)printf(", invalid"); break; default: (void)printf(", invalid"); break; } } break; case ICMP6_NI_REPLY: (void)printf("Node Information Reply"); /* XXX ID + Seq + Data */ ni = (struct icmp6_nodeinfo *)icp; printf(", "); switch (ntohs(ni->ni_qtype)) { case NI_QTYPE_NOOP: (void)printf("NOOP"); break; case NI_QTYPE_SUPTYPES: (void)printf("Supported qtypes"); break; case NI_QTYPE_FQDN: (void)printf("DNS name"); break; case NI_QTYPE_NODEADDR: (void)printf("nodeaddr"); break; case NI_QTYPE_IPV4ADDR: (void)printf("IPv4 nodeaddr"); break; default: (void)printf("unknown qtype"); break; } if (options & F_VERBOSE) { if (ni->ni_code >= sizeof(nircode) / sizeof(nircode[0])) printf(", invalid"); else printf(", %s", nircode[ni->ni_code]); } break; default: (void)printf("Bad ICMP type: %d", icp->icmp6_type); } } /* * pr_iph -- * Print an IP6 header. */ void pr_iph(struct ip6_hdr *ip6) { u_int32_t flow = ip6->ip6_flow & IPV6_FLOWLABEL_MASK; u_int8_t tc; char ntop_buf[INET6_ADDRSTRLEN]; tc = *(&ip6->ip6_vfc + 1); /* XXX */ tc = (tc >> 4) & 0x0f; tc |= (ip6->ip6_vfc << 4); printf("Vr TC Flow Plen Nxt Hlim\n"); printf(" %1x %02x %05x %04x %02x %02x\n", (ip6->ip6_vfc & IPV6_VERSION_MASK) >> 4, tc, (u_int32_t)ntohl(flow), ntohs(ip6->ip6_plen), ip6->ip6_nxt, ip6->ip6_hlim); if (!inet_ntop(AF_INET6, &ip6->ip6_src, ntop_buf, sizeof(ntop_buf))) strncpy(ntop_buf, "?", sizeof(ntop_buf)); printf("%s->", ntop_buf); if (!inet_ntop(AF_INET6, &ip6->ip6_dst, ntop_buf, sizeof(ntop_buf))) strncpy(ntop_buf, "?", sizeof(ntop_buf)); printf("%s\n", ntop_buf); } /* * pr_addr -- * Return an ascii host address as a dotted quad and optionally with * a hostname. */ const char * pr_addr(struct sockaddr *addr, int addrlen) { static char buf[NI_MAXHOST]; int flag = 0; if ((options & F_HOSTNAME) == 0) flag |= NI_NUMERICHOST; if (getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0, flag) == 0) return (buf); else return "?"; } /* * pr_retip -- * Dump some info on a returned (via ICMPv6) IPv6 packet. */ void pr_retip(struct ip6_hdr *ip6, u_char *end) { u_char *cp = (u_char *)ip6, nh; int hlen; if (end - (u_char *)ip6 < sizeof(*ip6)) { printf("IP6"); goto trunc; } pr_iph(ip6); hlen = sizeof(*ip6); nh = ip6->ip6_nxt; cp += hlen; while (end - cp >= 8) { switch (nh) { case IPPROTO_HOPOPTS: printf("HBH "); hlen = (((struct ip6_hbh *)cp)->ip6h_len+1) << 3; nh = ((struct ip6_hbh *)cp)->ip6h_nxt; break; case IPPROTO_DSTOPTS: printf("DSTOPT "); hlen = (((struct ip6_dest *)cp)->ip6d_len+1) << 3; nh = ((struct ip6_dest *)cp)->ip6d_nxt; break; case IPPROTO_FRAGMENT: printf("FRAG "); hlen = sizeof(struct ip6_frag); nh = ((struct ip6_frag *)cp)->ip6f_nxt; break; case IPPROTO_ROUTING: printf("RTHDR "); hlen = (((struct ip6_rthdr *)cp)->ip6r_len+1) << 3; nh = ((struct ip6_rthdr *)cp)->ip6r_nxt; break; case IPPROTO_AH: printf("AH "); hlen = (((struct ah *)cp)->ah_hl+2) << 2; nh = ((struct ah *)cp)->ah_nh; break; case IPPROTO_ICMPV6: printf("ICMP6: type = %d, code = %d\n", *cp, *(cp + 1)); return; case IPPROTO_ESP: printf("ESP\n"); return; case IPPROTO_TCP: printf("TCP: from port %u, to port %u (decimal)\n", (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3))); return; case IPPROTO_UDP: printf("UDP: from port %u, to port %u (decimal)\n", (*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3))); return; default: printf("Unknown Header(%d)\n", nh); return; } if ((cp += hlen) >= end) goto trunc; } if (end - cp < 8) goto trunc; putchar('\n'); return; trunc: printf("...\n"); return; } void fill(char *bp, char *patp) { int ii, jj, kk; int pat[16]; char *cp; for (cp = patp; *cp; cp++) if (!isxdigit(*cp)) errx(1, "patterns must be specified as hex digits"); ii = sscanf(patp, "%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x", &pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6], &pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12], &pat[13], &pat[14], &pat[15]); /* xxx */ if (ii > 0) for (kk = 0; kk <= MAXDATALEN - (8 + sizeof(struct tv32) + ii); kk += ii) for (jj = 0; jj < ii; ++jj) bp[jj + kk] = pat[jj]; if (!(options & F_QUIET)) { (void)printf("PATTERN: 0x"); for (jj = 0; jj < ii; ++jj) (void)printf("%02x", bp[jj] & 0xFF); (void)printf("\n"); } } char * nigroup(char *name) { char *p; char *q; MD5_CTX ctxt; u_int8_t digest[16]; u_int8_t c; size_t l; char hbuf[NI_MAXHOST]; struct in6_addr in6; p = strchr(name, '.'); if (!p) p = name + strlen(name); l = p - name; if (l > 63 || l > sizeof(hbuf) - 1) return NULL; /*label too long*/ strncpy(hbuf, name, l); hbuf[(int)l] = '\0'; for (q = name; *q; q++) { if (isupper(*(unsigned char *)q)) *q = tolower(*(unsigned char *)q); } /* generate 8 bytes of pseudo-random value. */ memset(&ctxt, 0, sizeof(ctxt)); MD5Init(&ctxt); c = l & 0xff; MD5Update(&ctxt, &c, sizeof(c)); MD5Update(&ctxt, (unsigned char *)name, l); MD5Final(digest, &ctxt); if (inet_pton(AF_INET6, "ff02::2:0000:0000", &in6) != 1) return NULL; /*XXX*/ bcopy(digest, &in6.s6_addr[12], 4); if (inet_ntop(AF_INET6, &in6, hbuf, sizeof(hbuf)) == NULL) return NULL; return strdup(hbuf); } void usage(void) { (void)fprintf(stderr, "usage: ping6 [-dEefH" "m" "NnqtvWw" #ifdef IPV6_REACHCONF "R" #endif "] [-a addrtype] [-b bufsiz] [-c count] [-g gateway]\n\t" "[-h hoplimit] [-I interface] [-i wait] [-l preload] [-p pattern]" "\n\t[-S sourceaddr] [-s packetsize] [hops ...] host\n"); exit(1); }
24.855754
84
0.63064
d2515dafecde85a9bb5459cc516b33f28168fc34
3,900
h
C
3rdparty/flann/util/logger.h
taontech/open3d4iOS
589b074901cccf3d23d342fc00f1e917e7b19aee
[ "MIT" ]
5
2020-05-25T19:29:57.000Z
2021-07-16T17:15:31.000Z
3rdparty/flann/util/logger.h
taontech/open3dIos
589b074901cccf3d23d342fc00f1e917e7b19aee
[ "MIT" ]
4
2020-02-24T13:16:58.000Z
2021-07-16T17:14:01.000Z
3rdparty/flann/util/logger.h
taontech/open3dIos
589b074901cccf3d23d342fc00f1e917e7b19aee
[ "MIT" ]
2
2020-03-11T12:25:35.000Z
2020-12-11T03:10:49.000Z
/*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR 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 FLANN_LOGGER_H #define FLANN_LOGGER_H #include <stdio.h> #include <stdarg.h> #include "flann/defines.h" namespace flannO { class Logger { Logger() : stream(stdout), logLevel(FLANN_LOG_WARN) {} ~Logger() { if ((stream!=NULL)&&(stream!=stdout)) { fclose(stream); } } static Logger& instance() { static Logger logger; return logger; } void _setDestination(const char* name) { if (name==NULL) { stream = stdout; } else { stream = fopen(name,"w"); if (stream == NULL) { stream = stdout; } } } int _log(int level, const char* fmt, va_list arglist) { if (level > logLevel ) return -1; int ret = vfprintf(stream, fmt, arglist); return ret; } public: /** * Sets the logging level. All messages with lower priority will be ignored. * @param level Logging level */ static void setLevel(int level) { instance().logLevel = level; } /** * Returns the currently set logging level. * @return current logging level */ static int getLevel() { return instance().logLevel; } /** * Sets the logging destination * @param name Filename or NULL for console */ static void setDestination(const char* name) { instance()._setDestination(name); } /** * Print log message * @param level Log level * @param fmt Message format * @return */ static int log(int level, const char* fmt, ...) { va_list arglist; va_start(arglist, fmt); int ret = instance()._log(level,fmt,arglist); va_end(arglist); return ret; } #define LOG_METHOD(NAME,LEVEL) \ static int NAME(const char* fmt, ...) \ { \ va_list ap; \ va_start(ap, fmt); \ int ret = instance()._log(LEVEL, fmt, ap); \ va_end(ap); \ return ret; \ } LOG_METHOD(fatal, FLANN_LOG_FATAL) LOG_METHOD(error, FLANN_LOG_ERROR) LOG_METHOD(warn, FLANN_LOG_WARN) LOG_METHOD(info, FLANN_LOG_INFO) LOG_METHOD(debug, FLANN_LOG_DEBUG) private: FILE* stream; int logLevel; }; } #endif //FLANN_LOGGER_H
28.26087
86
0.618718
9ab61a5417594fe6e21898310fafe0a8ccaa6bab
1,387
h
C
include/tools/zet_driver.h
fogflower/level-zero
7b2002369e0671687f3986fd5085e205bb41be26
[ "MIT" ]
1
2020-04-30T03:55:17.000Z
2020-04-30T03:55:17.000Z
include/tools/zet_driver.h
fogflower/level-zero
7b2002369e0671687f3986fd5085e205bb41be26
[ "MIT" ]
null
null
null
include/tools/zet_driver.h
fogflower/level-zero
7b2002369e0671687f3986fd5085e205bb41be26
[ "MIT" ]
null
null
null
/* * * Copyright (C) 2019 Intel Corporation * * SPDX-License-Identifier: MIT * * @file zet_driver.h * * @brief Intel 'One API' Level-Zero APIs * */ #ifndef _ZET_DRIVER_H #define _ZET_DRIVER_H #if defined(__cplusplus) #pragma once #endif #if !defined(_ZET_API_H) #pragma message("warning: this file is not intended to be included directly") #endif #if defined(__cplusplus) extern "C" { #endif /////////////////////////////////////////////////////////////////////////////// /// @brief Initialize the 'One API' driver and must be called before any other /// API function. /// /// @details /// - If this function is not called then all other functions will return /// ::ZE_RESULT_ERROR_UNINITIALIZED. /// - Only one instance of a driver per process will be initialized. /// - This function is thread-safe for scenarios where multiple libraries /// may initialize the driver simultaneously. /// /// @returns /// - ::ZE_RESULT_SUCCESS /// - ::ZE_RESULT_ERROR_UNINITIALIZED /// - ::ZE_RESULT_ERROR_DEVICE_LOST /// - ::ZE_RESULT_ERROR_INVALID_ENUMERATION /// + flags /// - ::ZE_RESULT_ERROR_OUT_OF_HOST_MEMORY __ze_api_export ze_result_t __zecall zetInit( ze_init_flag_t flags ///< [in] initialization flags ); #if defined(__cplusplus) } // extern "C" #endif #endif // _ZET_DRIVER_H
25.685185
82
0.634463
82b1f1abfff0bf2d5c1f020143e772ecaf19835c
537
h
C
librumur/include/rumur/except.h
civic-fv/rumur-romp
194ad7307d9452bd265e6da5f4f6a5439fe01c10
[ "Unlicense" ]
4
2020-10-21T21:12:27.000Z
2021-10-05T23:22:10.000Z
librumur/include/rumur/except.h
civic-fv/rumur-romp
194ad7307d9452bd265e6da5f4f6a5439fe01c10
[ "Unlicense" ]
216
2018-02-11T00:05:20.000Z
2022-03-10T02:31:58.000Z
librumur/include/rumur/except.h
civic-fv/rumur-romp
194ad7307d9452bd265e6da5f4f6a5439fe01c10
[ "Unlicense" ]
6
2020-05-05T08:29:48.000Z
2022-03-08T20:15:52.000Z
#pragma once #include <cstddef> #include "location.hh" #include <stdexcept> #include <string> #ifndef RUMUR_API_WITH_RTTI #define RUMUR_API_WITH_RTTI __attribute__((visibility("default"))) #endif namespace rumur { /* A basic exception to allow us to easily catch only the errors thrown by * ourselves. */ class RUMUR_API_WITH_RTTI Error : public std::runtime_error { public: location loc; Error(const std::string &message, const location &loc_); Error(const std::string &prefix, const Error &sub); }; } // namespace rumur
19.888889
74
0.743017
190d8897311a4df445cf735fe73ccb8ca32e03ad
3,207
h
C
Frameworks/PhotosUI.framework/PUAlbumStreamActivity.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
36
2016-04-20T04:19:04.000Z
2018-10-08T04:12:25.000Z
Frameworks/PhotosUI.framework/PUAlbumStreamActivity.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
null
null
null
Frameworks/PhotosUI.framework/PUAlbumStreamActivity.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
10
2016-06-16T02:40:44.000Z
2019-01-15T03:31:45.000Z
/* Generated by RuntimeBrowser Image: /System/Library/Frameworks/PhotosUI.framework/PhotosUI */ @interface PUAlbumStreamActivity : PUActivity <PUPhotoStreamComposeServiceDelegate, PUVideoTrimQueueControllerDelegate> { UIViewController * _activityController; <PUAlbumStreamActivityDelegate> * _delegate; bool _destinationAlbumWasCreated; NSObject<PLUserEditableAlbumProtocol> * _destinationStreamingAlbum; double _endTime; bool _isPresentedFromActivityViewController; PUActivityItemSourceController * _itemSourceController; UIViewController * _presenterViewController; UIViewController * _referenceViewController; double _startTime; PUPhotoStreamComposeServiceViewController * _streamComposeVc; PUVideoTrimQueueController * _trimController; } @property (readonly, copy) NSString *debugDescription; @property (nonatomic) <PUAlbumStreamActivityDelegate> *delegate; @property (readonly, copy) NSString *description; @property bool destinationAlbumWasCreated; @property (nonatomic, retain) NSObject<PLUserEditableAlbumProtocol> *destinationStreamingAlbum; @property (readonly) unsigned long long hash; @property (setter=setPresentedFromActivityViewController:, nonatomic) bool isPresentedFromActivityViewController; @property (nonatomic) UIViewController *referenceViewController; @property (readonly) Class superclass; + (long long)activityCategory; - (void).cxx_destruct; - (id)_activityImage; - (id)_activitySettingsImage; - (void)_createStreamsPickerContainerWithExisting:(bool)arg1; - (void)_handleDismissWithSuccess:(bool)arg1; - (void)_performPresentationOnViewController:(id)arg1 completion:(id /* block */)arg2; - (void)_prepareToPost:(id)arg1 albumName:(id)arg2 recipients:(id)arg3 comments:(id)arg4; - (bool)_presentActivityOnViewController:(id)arg1 animated:(bool)arg2 completion:(id /* block */)arg3; - (void)_publishAssets:(id)arg1 withSharingInfos:(id)arg2 andTrimmedVideoPathInfo:(id)arg3 toAlbum:(id)arg4 orCreateWithName:(id)arg5 comment:(id)arg6 invitationRecipients:(id)arg7 wantsPublicWebsite:(bool)arg8 completion:(id /* block */)arg9; - (id)_selectedVideo; - (bool)_sharedAlbumAllowsAdding:(struct NSObject { Class x1; }*)arg1; - (id)activityTitle; - (id)activityType; - (id)activityViewController; - (bool)canPerformWithActivityItems:(id)arg1; - (void)controller:(id)arg1 didCancelTrimmingVideoSources:(id)arg2; - (void)controller:(id)arg1 didFinishTrimmingVideoSources:(id)arg2; - (id)delegate; - (bool)destinationAlbumWasCreated; - (id)destinationStreamingAlbum; - (id)init; - (bool)isPresentedFromActivityViewController; - (id)itemSourceController; - (void)photoStreamComposeService:(id)arg1 didPostComment:(id)arg2; - (void)photoStreamComposeServiceDidCancel:(id)arg1; - (void)prepareWithActivityItems:(id)arg1; - (void)presentActivityOnViewController:(id)arg1 animated:(bool)arg2 completion:(id /* block */)arg3; - (id)referenceViewController; - (void)setDelegate:(id)arg1; - (void)setDestinationAlbumWasCreated:(bool)arg1; - (void)setDestinationStreamingAlbum:(id)arg1; - (void)setItemSourceController:(id)arg1; - (void)setPresentedFromActivityViewController:(bool)arg1; - (void)setReferenceViewController:(id)arg1; @end
47.161765
243
0.80449
d2ed70694a2cd02c0eef1893b5182bea00bc95b8
4,258
h
C
searchlib/src/vespa/searchlib/predicate/predicate_index.h
amahussein/vespa
29d266ae1e5c95e25002b97822953fdd02b1451e
[ "Apache-2.0" ]
1
2020-06-02T13:28:29.000Z
2020-06-02T13:28:29.000Z
searchlib/src/vespa/searchlib/predicate/predicate_index.h
amahussein/vespa
29d266ae1e5c95e25002b97822953fdd02b1451e
[ "Apache-2.0" ]
1
2021-03-31T22:24:20.000Z
2021-03-31T22:24:20.000Z
searchlib/src/vespa/searchlib/predicate/predicate_index.h
amahussein/vespa
29d266ae1e5c95e25002b97822953fdd02b1451e
[ "Apache-2.0" ]
1
2020-09-03T11:39:52.000Z
2020-09-03T11:39:52.000Z
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #include "common.h" #include "document_features_store.h" #include "predicate_interval_store.h" #include "simple_index.h" #include "predicate_interval.h" #include <vespa/searchlib/common/bitvectorcache.h> #include <vespa/vespalib/data/databuffer.h> #include <vespa/vespalib/stllike/string.h> #include <unordered_map> namespace search::predicate { struct PredicateTreeAnnotations; /** * PredicateIndex keeps an index of boolean constraints for use with * the interval algorithm. It is the central component of * PredicateAttribute, and PredicateBlueprint uses it to obtain * posting lists for matching. */ class PredicateIndex : public PopulateInterface { typedef SimpleIndex<vespalib::datastore::EntryRef> IntervalIndex; typedef SimpleIndex<vespalib::datastore::EntryRef> BoundsIndex; template <typename IntervalT> using FeatureMap = std::unordered_map<uint64_t, std::vector<IntervalT>>; using generation_t = vespalib::GenerationHandler::generation_t; template <typename T> using optional = std::optional<T>; public: typedef std::unique_ptr<PredicateIndex> UP; typedef vespalib::GenerationHandler GenerationHandler; typedef vespalib::GenerationHolder GenerationHolder; using BTreeIterator = SimpleIndex<vespalib::datastore::EntryRef>::BTreeIterator; using VectorIterator = SimpleIndex<vespalib::datastore::EntryRef>::VectorIterator; private: uint32_t _arity; GenerationHandler &_generation_handler; const DocIdLimitProvider &_limit_provider; IntervalIndex _interval_index; BoundsIndex _bounds_index; PredicateIntervalStore _interval_store; BTreeSet _zero_constraint_docs; DocumentFeaturesStore _features_store; mutable BitVectorCache _cache; template <typename IntervalT> void addPosting(uint64_t feature, uint32_t doc_id, vespalib::datastore::EntryRef ref); template <typename IntervalT> void indexDocumentFeatures(uint32_t doc_id, const FeatureMap<IntervalT> &interval_map); PopulateInterface::Iterator::UP lookup(uint64_t key) const override; public: PredicateIndex(GenerationHandler &generation_handler, GenerationHolder &genHolder, const DocIdLimitProvider &limit_provider, const SimpleIndexConfig &simple_index_config, uint32_t arity); // deserializes PredicateIndex from buffer. // The observer can be used to gain some insight into what has been added to the index.. PredicateIndex(GenerationHandler &generation_handler, GenerationHolder &genHolder, const DocIdLimitProvider &limit_provider, const SimpleIndexConfig &simple_index_config, vespalib::DataBuffer &buffer, SimpleIndexDeserializeObserver<> & observer, uint32_t version); ~PredicateIndex() override; void serialize(vespalib::DataBuffer &buffer) const; void onDeserializationCompleted(); void indexEmptyDocument(uint32_t doc_id); void indexDocument(uint32_t doc_id, const PredicateTreeAnnotations &annotations); void removeDocument(uint32_t doc_id); void commit(); void trimHoldLists(generation_t used_generation); void transferHoldLists(generation_t generation); vespalib::MemoryUsage getMemoryUsage() const; int getArity() const { return _arity; } const ZeroConstraintDocs getZeroConstraintDocs() const { return _zero_constraint_docs.getFrozenView(); } const IntervalIndex &getIntervalIndex() const { return _interval_index; } const BoundsIndex &getBoundsIndex() const { return _bounds_index; } const PredicateIntervalStore &getIntervalStore() const { return _interval_store; } void populateIfNeeded(size_t doc_id_limit); BitVectorCache::KeySet lookupCachedSet(const BitVectorCache::KeyAndCountSet & keys) const; void computeCountVector(BitVectorCache::KeySet & keys, BitVectorCache::CountVector & v) const; /* * Adjust size of structures to have space for docId. */ void adjustDocIdLimit(uint32_t docId); }; extern template class SimpleIndex<vespalib::datastore::EntryRef>; }
37.350877
118
0.75458
cf455df1119c3be4b36faf1809cc19808382ff20
34,615
c
C
hw/drivers/bq27z561/src/bq27z561.c
zerog2k/mynewt-core
d822f91a9520ffdea5070ee343c5cb0c0ffef9e4
[ "Apache-2.0" ]
null
null
null
hw/drivers/bq27z561/src/bq27z561.c
zerog2k/mynewt-core
d822f91a9520ffdea5070ee343c5cb0c0ffef9e4
[ "Apache-2.0" ]
null
null
null
hw/drivers/bq27z561/src/bq27z561.c
zerog2k/mynewt-core
d822f91a9520ffdea5070ee343c5cb0c0ffef9e4
[ "Apache-2.0" ]
null
null
null
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include <math.h> #include <string.h> #include "os/mynewt.h" #include "bq27z561/bq27z561.h" #include "hal/hal_gpio.h" #include "hal/hal_i2c.h" #include "i2cn/i2cn.h" #include "battery/battery_prop.h" #if MYNEWT_VAL(BQ27Z561_LOG) #include "modlog/modlog.h" #endif #if MYNEWT_VAL(BQ27Z561_LOG) #define BQ27Z561_LOG(lvl_, ...) \ MODLOG_ ## lvl_(MYNEWT_VAL(BQ27Z561_LOG_MODULE), __VA_ARGS__) #else #define BQ27Z561_LOG(lvl_, ...) #endif static uint8_t bq27z561_calc_chksum(uint8_t *tmpbuf, uint8_t len) { uint8_t i; uint8_t chksum; chksum = 0; if (len != 0) { for (i = 0; i < len; ++i) { chksum += tmpbuf[i]; } chksum = 0xFF - chksum; } return chksum; } static float bq27z561_temp_to_celsius(uint16_t temp) { float temp_c; temp_c = ((float)temp * 0.1) - 273; return temp_c; } static int bq27z561_open(struct os_dev *dev, uint32_t timeout, void *arg) { return 0; } static int bq27z561_close(struct os_dev *dev) { return 0; } /** * Lock access to the bq27z561_itf specified by si. Blocks until lock acquired. * * @param The bq27z561_itf to lock * @param The timeout * * @return 0 on success, non-zero on failure. */ static int bq27z561_itf_lock(struct bq27z561_itf *bi, uint32_t timeout) { int rc; os_time_t ticks; if (!bi->itf_lock) { return 0; } rc = os_time_ms_to_ticks(timeout, &ticks); if (rc) { return rc; } rc = os_mutex_pend(bi->itf_lock, ticks); if (rc == 0 || rc == OS_NOT_STARTED) { return (0); } return (rc); } /** * Unlock access to the bq27z561_itf specified by bi. * * @param The bq27z561_itf to unlock access to * * @return 0 on success, non-zero on failure. */ static void bq27z561_itf_unlock(struct bq27z561_itf *bi) { if (!bi->itf_lock) { return; } os_mutex_release(bi->itf_lock); } static int bq27z561_rd_std_reg_byte(struct bq27z561 *dev, uint8_t reg, uint8_t *val) { int rc; struct hal_i2c_master_data i2c; i2c.address = dev->bq27_itf.itf_addr; i2c.len = 1; i2c.buffer = &reg; rc = bq27z561_itf_lock(&dev->bq27_itf, MYNEWT_VAL(BQ27Z561_ITF_LOCK_TMO)); if (rc) { return rc; } rc = i2cn_master_write(dev->bq27_itf.itf_num, &i2c, MYNEWT_VAL(BQ27Z561_I2C_TIMEOUT_TICKS), 0, MYNEWT_VAL(BQ27Z561_I2C_RETRIES)); if (rc != 0) { BQ27Z561_LOG(ERROR, "I2C reg read (wr) failed 0x%02X\n", reg); goto err; } i2c.len = 1; i2c.buffer = (uint8_t *)val; rc = i2cn_master_read(dev->bq27_itf.itf_num, &i2c, MYNEWT_VAL(BQ27Z561_I2C_TIMEOUT_TICKS), 1, MYNEWT_VAL(BQ27Z561_I2C_RETRIES)); if (rc != 0) { BQ27Z561_LOG(ERROR, "I2C reg read (rd) failed 0x%02X\n", reg); goto err; } err: bq27z561_itf_unlock(&dev->bq27_itf); return rc; } int bq27z561_rd_std_reg_word(struct bq27z561 *dev, uint8_t reg, uint16_t *val) { int rc; struct hal_i2c_master_data i2c; i2c.address = dev->bq27_itf.itf_addr; i2c.len = 1; i2c.buffer = &reg; rc = bq27z561_itf_lock(&dev->bq27_itf, MYNEWT_VAL(BQ27Z561_ITF_LOCK_TMO)); if (rc) { return rc; } rc = i2cn_master_write(dev->bq27_itf.itf_num, &i2c, MYNEWT_VAL(BQ27Z561_I2C_TIMEOUT_TICKS), 0, MYNEWT_VAL(BQ27Z561_I2C_RETRIES)); if (rc != 0) { BQ27Z561_LOG(ERROR, "I2C reg read (wr) failed 0x%02X\n", reg); goto err; } i2c.len = 2; i2c.buffer = (uint8_t *)val; rc = i2cn_master_read(dev->bq27_itf.itf_num, &i2c, MYNEWT_VAL(BQ27Z561_I2C_TIMEOUT_TICKS), 1, MYNEWT_VAL(BQ27Z561_I2C_RETRIES)); if (rc != 0) { BQ27Z561_LOG(ERROR, "I2C reg read (rd) failed 0x%02X\n", reg); goto err; } err: bq27z561_itf_unlock(&dev->bq27_itf); /* XXX: add big-endian support */ return rc; } static int bq27z561_wr_std_reg_byte(struct bq27z561 *dev, uint8_t reg, uint8_t val) { int rc; uint8_t buf[2]; struct hal_i2c_master_data i2c; buf[0] = reg; buf[1] = val; i2c.address = dev->bq27_itf.itf_num; i2c.len = 2; i2c.buffer = buf; rc = bq27z561_itf_lock(&dev->bq27_itf, MYNEWT_VAL(BQ27Z561_ITF_LOCK_TMO)); if (rc) { return rc; } rc = i2cn_master_write(dev->bq27_itf.itf_num, &i2c, MYNEWT_VAL(BQ27Z561_I2C_TIMEOUT_TICKS), 1, MYNEWT_VAL(BQ27Z561_I2C_RETRIES)); if (rc != 0) { BQ27Z561_LOG(ERROR, "I2C reg write 0x%02X failed\n", reg); } bq27z561_itf_unlock(&dev->bq27_itf); return rc; } static int bq27z561_wr_std_reg_word(struct bq27z561 *dev, uint8_t reg, uint16_t val) { int rc; uint8_t buf[3]; struct hal_i2c_master_data i2c; buf[0] = reg; buf[1] = (uint8_t)val; buf[2] = (uint8_t)(val >> 8); i2c.address = dev->bq27_itf.itf_num; i2c.len = 3; i2c.buffer = buf; rc = bq27z561_itf_lock(&dev->bq27_itf, MYNEWT_VAL(BQ27Z561_ITF_LOCK_TMO)); if (rc) { return rc; } rc = i2cn_master_write(dev->bq27_itf.itf_num, &i2c, MYNEWT_VAL(BQ27Z561_I2C_TIMEOUT_TICKS), 1, MYNEWT_VAL(BQ27Z561_I2C_RETRIES)); if (rc != 0) { BQ27Z561_LOG(ERROR, "I2C reg write 0x%02X failed\n", reg); goto err; } err: bq27z561_itf_unlock(&dev->bq27_itf); return rc; } bq27z561_err_t bq27x561_wr_alt_mfg_cmd(struct bq27z561 *dev, uint16_t cmd, uint8_t *buf, int len) { /* NOTE: add three here for register and two-byte command */ int rc; uint8_t tmpbuf[BQ27Z561_MAX_ALT_MFG_CMD_LEN + 3]; struct hal_i2c_master_data i2c; if ((len > 0) && (buf == NULL)) { return BQ27Z561_ERR_INV_PARAMS; } /* Make sure length is not too long */ if (len > BQ27Z561_MAX_ALT_MFG_CMD_LEN) { return BQ27Z561_ERR_CMD_LEN; } tmpbuf[0] = BQ27Z561_REG_MFRG_ACC; tmpbuf[1] = (uint8_t)cmd; tmpbuf[2] = (uint8_t)(cmd >> 8); if (len > 0) { memcpy(&tmpbuf[3], buf, len); } i2c.address = dev->bq27_itf.itf_addr; i2c.len = len + 3; i2c.buffer = tmpbuf; rc = bq27z561_itf_lock(&dev->bq27_itf, MYNEWT_VAL(BQ27Z561_ITF_LOCK_TMO)); if (rc) { return rc; } rc = i2cn_master_write(dev->bq27_itf.itf_num, &i2c, MYNEWT_VAL(BQ27Z561_I2C_TIMEOUT_TICKS), 1, MYNEWT_VAL(BQ27Z561_I2C_RETRIES)); if (rc != 0) { BQ27Z561_LOG(ERROR, "I2C reg read (wr) failed 0x%02X\n", tmpbuf[0]); rc = BQ27Z561_ERR_I2C_ERR; } bq27z561_itf_unlock(&dev->bq27_itf); return rc; } bq27z561_err_t bq27x561_rd_alt_mfg_cmd(struct bq27z561 *dev, uint16_t cmd, uint8_t *val, int val_len) { bq27z561_err_t rc; uint8_t tmpbuf[36]; uint8_t len; uint16_t cmd_read; uint8_t chksum; struct hal_i2c_master_data i2c; if ((val_len == 0) || (val == NULL)) { return BQ27Z561_ERR_INV_PARAMS; } tmpbuf[0] = BQ27Z561_REG_CNTL; tmpbuf[1] = (uint8_t)cmd; tmpbuf[2] = (uint8_t)(cmd >> 8); i2c.address = dev->bq27_itf.itf_addr; i2c.len = 3; i2c.buffer = tmpbuf; rc = bq27z561_itf_lock(&dev->bq27_itf, MYNEWT_VAL(BQ27Z561_ITF_LOCK_TMO)); if (rc) { return rc; } rc = i2cn_master_write(dev->bq27_itf.itf_num, &i2c, MYNEWT_VAL(BQ27Z561_I2C_TIMEOUT_TICKS), 1, MYNEWT_VAL(BQ27Z561_I2C_RETRIES)); if (rc != 0) { BQ27Z561_LOG(ERROR, "I2C reg read (wr) failed 0x%02X\n", tmpbuf[0]); rc = BQ27Z561_ERR_I2C_ERR; bq27z561_itf_unlock(&dev->bq27_itf); goto err; } tmpbuf[0] = BQ27Z561_REG_MFRG_ACC; i2c.len = 1; i2c.buffer = tmpbuf; rc = i2cn_master_write(dev->bq27_itf.itf_num, &i2c, MYNEWT_VAL(BQ27Z561_I2C_TIMEOUT_TICKS), 0, MYNEWT_VAL(BQ27Z561_I2C_RETRIES)); if (rc != 0) { BQ27Z561_LOG(ERROR, "I2C reg read (wr) failed 0x%02X\n", tmpbuf[0]); rc = BQ27Z561_ERR_I2C_ERR; bq27z561_itf_unlock(&dev->bq27_itf); goto err; } i2c.len = 36; i2c.buffer = tmpbuf; rc = i2cn_master_read(dev->bq27_itf.itf_num, &i2c, MYNEWT_VAL(BQ27Z561_I2C_TIMEOUT_TICKS), 1, MYNEWT_VAL(BQ27Z561_I2C_RETRIES)); if (rc != 0) { BQ27Z561_LOG(ERROR, "I2C reg read (rd) failed 0x%02X\n", tmpbuf[0]); rc = BQ27Z561_ERR_I2C_ERR; bq27z561_itf_unlock(&dev->bq27_itf); goto err; } bq27z561_itf_unlock(&dev->bq27_itf); /* Verify that first two bytes are the command */ cmd_read = tmpbuf[0]; cmd_read |= ((uint16_t)tmpbuf[1]) << 8; if (cmd_read != cmd) { BQ27Z561_LOG(ERROR, "cmd mismatch (cmd=%x cmd_ret=%x\n", cmd, cmd_read); rc = BQ27Z561_ERR_CMD_MISMATCH; goto err; } /* * Verify length. The length contains two bytes for the command and * another two for the checksum and length bytes. Thus, there better * be at least 5 bytes here */ len = tmpbuf[35]; if (len < 5) { rc = BQ27Z561_ERR_ALT_MFG_LEN; goto err; } /* Subtract out checksum and length bytes from length */ len -= 2; chksum = bq27z561_calc_chksum(tmpbuf, len); if (chksum != tmpbuf[34]) { BQ27Z561_LOG(ERROR, "chksum failure for cmd %u (calc=%u read=%u)", cmd, chksum, tmpbuf[34]); rc = BQ27Z561_ERR_CHKSUM_FAIL; } /* Now copy returned data. We subtract command from length */ len -= 2; if (val_len < len) { val_len = len; } memcpy(val, &tmpbuf[2], val_len); rc = BQ27Z561_OK; err: return rc; } bq27z561_err_t bq27x561_rd_flash(struct bq27z561 *dev, uint16_t addr, uint8_t *buf, int buflen) { uint8_t tmpbuf[BQ27Z561_MAX_FLASH_RW_LEN + 2]; uint16_t addr_read; bq27z561_err_t rc; struct hal_i2c_master_data i2c; if ((buflen == 0) || !buf || (buflen > BQ27Z561_MAX_FLASH_RW_LEN)) { return BQ27Z561_ERR_INV_PARAMS; } if ((addr < BQ27Z561_FLASH_BEG_ADDR) || (addr > BQ27Z561_FLASH_END_ADDR)) { return BQ27Z561_ERR_INV_FLASH_ADDR; } tmpbuf[0] = BQ27Z561_REG_MFRG_ACC; tmpbuf[1] = (uint8_t)addr; tmpbuf[2] = (uint8_t)(addr >> 8); i2c.address = dev->bq27_itf.itf_addr; i2c.len = 3; i2c.buffer = tmpbuf; rc = bq27z561_itf_lock(&dev->bq27_itf, MYNEWT_VAL(BQ27Z561_ITF_LOCK_TMO)); if (rc) { return rc; } rc = i2cn_master_write(dev->bq27_itf.itf_num, &i2c, MYNEWT_VAL(BQ27Z561_I2C_TIMEOUT_TICKS), 1, MYNEWT_VAL(BQ27Z561_I2C_RETRIES)); if (rc != 0) { BQ27Z561_LOG(ERROR, "I2C reg read (wr) failed 0x%02X\n", tmpbuf[0]); rc = BQ27Z561_ERR_I2C_ERR; bq27z561_itf_unlock(&dev->bq27_itf); goto err; } tmpbuf[0] = BQ27Z561_REG_MFRG_ACC; i2c.len = 1; i2c.buffer = tmpbuf; rc = i2cn_master_write(dev->bq27_itf.itf_num, &i2c, MYNEWT_VAL(BQ27Z561_I2C_TIMEOUT_TICKS), 0, MYNEWT_VAL(BQ27Z561_I2C_RETRIES)); if (rc != 0) { BQ27Z561_LOG(ERROR, "I2C reg read (wr) failed 0x%02X\n", tmpbuf[0]); rc = BQ27Z561_ERR_I2C_ERR; bq27z561_itf_unlock(&dev->bq27_itf); goto err; } i2c.len = buflen + 2; i2c.buffer = tmpbuf; rc = i2cn_master_read(dev->bq27_itf.itf_num, &i2c, MYNEWT_VAL(BQ27Z561_I2C_TIMEOUT_TICKS), 1, MYNEWT_VAL(BQ27Z561_I2C_RETRIES)); if (rc != 0) { BQ27Z561_LOG(ERROR, "I2C reg read (rd) failed 0x%02X\n", tmpbuf[0]); rc = BQ27Z561_ERR_I2C_ERR; bq27z561_itf_unlock(&dev->bq27_itf); goto err; } bq27z561_itf_unlock(&dev->bq27_itf); /* Verify that first two bytes are the address*/ addr_read = tmpbuf[0]; addr_read |= ((uint16_t)tmpbuf[1]) << 8; if (addr_read != addr) { BQ27Z561_LOG(ERROR, "addr mismatch (addr_read=%x addr_ret=%x\n", addr_read, addr); rc = BQ27Z561_ERR_FLASH_ADDR_MISMATCH; goto err; } /* Now copy returned data. */ memcpy(buf, &tmpbuf[2], buflen); rc = BQ27Z561_OK; err: return rc; } bq27z561_err_t bq27x561_wr_flash(struct bq27z561 *dev, uint16_t addr, uint8_t *buf, int buflen) { uint8_t tmpbuf[BQ27Z561_MAX_FLASH_RW_LEN + 2]; uint8_t chksum; bq27z561_err_t rc; struct hal_i2c_master_data i2c; if ((buflen == 0) || (!buf) || (buflen > BQ27Z561_MAX_FLASH_RW_LEN)) { return BQ27Z561_ERR_INV_PARAMS; } if ((addr < BQ27Z561_FLASH_BEG_ADDR) || (addr > BQ27Z561_FLASH_END_ADDR)) { return BQ27Z561_ERR_INV_FLASH_ADDR; } tmpbuf[0] = BQ27Z561_REG_MFRG_ACC; tmpbuf[1] = (uint8_t)addr; tmpbuf[2] = (uint8_t)(addr >> 8); memcpy(&tmpbuf[3], buf, buflen); i2c.address = dev->bq27_itf.itf_addr; i2c.len = buflen + 3; i2c.buffer = tmpbuf; rc = bq27z561_itf_lock(&dev->bq27_itf, MYNEWT_VAL(BQ27Z561_ITF_LOCK_TMO)); if (rc) { return rc; } rc = i2cn_master_write(dev->bq27_itf.itf_num, &i2c, MYNEWT_VAL(BQ27Z561_I2C_TIMEOUT_TICKS), 1, MYNEWT_VAL(BQ27Z561_I2C_RETRIES)); if (rc != 0) { BQ27Z561_LOG(ERROR, "I2C reg read (wr) failed 0x%02X\n", tmpbuf[0]); rc = BQ27Z561_ERR_I2C_ERR; goto err; } /* Calculate checksum */ chksum = bq27z561_calc_chksum(&tmpbuf[1], buflen + 2); /* Write checksum and length */ tmpbuf[0] = BQ27Z561_REG_CHKSUM; tmpbuf[1] = chksum; tmpbuf[2] = buflen + 4; i2c.len = 3; i2c.buffer = tmpbuf; rc = i2cn_master_write(dev->bq27_itf.itf_num, &i2c, MYNEWT_VAL(BQ27Z561_I2C_TIMEOUT_TICKS), 1, MYNEWT_VAL(BQ27Z561_I2C_RETRIES)); if (rc != 0) { BQ27Z561_LOG(ERROR, "I2C reg read (wr) failed 0x%02X\n", tmpbuf[0]); rc = BQ27Z561_ERR_I2C_ERR; } err: bq27z561_itf_unlock(&dev->bq27_itf); return rc; } #if 0 static int bq27z561_get_chip_id(struct bq27z561 *dev, uint8_t *chip_id) { return 0; } #endif /* Check if bq27z561 is initialized and sets bq27z561 initialized flag */ int bq27z561_get_init_status(struct bq27z561 *dev, uint8_t *init_flag) { int rc; uint16_t init; rc = bq27z561_rd_std_reg_word(dev, BQ27Z561_REG_FLAGS, &init); if (init & BQ27Z561_BATTERY_STATUS_INIT) { *init_flag = 1; } else { *init_flag = 0; } return rc; } /* XXX: no support for control register yet */ int bq27z561_set_at_rate(struct bq27z561 *dev, int16_t current) { int rc; rc = bq27z561_wr_std_reg_word(dev, BQ27Z561_REG_AR, (uint16_t)current); return rc; } int bq27z561_get_at_rate(struct bq27z561 *dev, int16_t *current) { int rc; rc = bq27z561_rd_std_reg_word(dev, BQ27Z561_REG_AR, (uint16_t *)current); return rc; } int bq27z561_get_time_to_empty(struct bq27z561 *dev, uint16_t *tte) { int rc; rc = bq27z561_rd_std_reg_word(dev, BQ27Z561_REG_ARTTE, tte); return rc; } int bq27z561_get_temp(struct bq27z561 *dev, float *temp_c) { int rc; uint16_t val; rc = bq27z561_rd_std_reg_word(dev, BQ27Z561_REG_TEMP, &val); if (!rc) { /* Kelvin to Celsius */ *temp_c = bq27z561_temp_to_celsius(val); } return rc; } int bq27z561_get_temp_lo_set_threshold(struct bq27z561 *dev, int8_t *temp_c) { int rc; rc = bq27z561_rd_std_reg_byte(dev, BQ27Z561_REG_TEMP_LO_SET_TH, (uint8_t *)temp_c); return rc; } int bq27z561_set_temp_lo_set_threshold(struct bq27z561 *dev, int8_t temp_c) { int rc; uint8_t temp = (uint8_t)(temp_c); rc = bq27z561_wr_std_reg_byte(dev, BQ27Z561_REG_TEMP_LO_SET_TH, temp); return rc; } int bq27z561_get_temp_lo_clr_threshold(struct bq27z561 *dev, int8_t *temp_c) { int rc; rc = bq27z561_rd_std_reg_byte(dev, BQ27Z561_REG_TEMP_LO_CLR_TH, (uint8_t *)temp_c); return rc; } int bq27z561_set_temp_lo_clr_threshold(struct bq27z561 *dev, int8_t temp_c) { int rc; rc = bq27z561_wr_std_reg_byte(dev, BQ27Z561_REG_TEMP_LO_CLR_TH, (uint8_t)temp_c); return rc; } int bq27z561_get_temp_hi_set_threshold(struct bq27z561 *dev, int8_t *temp_c) { int rc; rc = bq27z561_rd_std_reg_byte(dev, BQ27Z561_REG_TEMP_HI_SET_TH, (uint8_t *)temp_c); return rc; } int bq27z561_set_temp_hi_set_threshold(struct bq27z561 *dev, int8_t temp_c) { int rc; rc = bq27z561_wr_std_reg_byte(dev, BQ27Z561_REG_TEMP_HI_SET_TH, (uint8_t)temp_c); return rc; } int bq27z561_get_temp_hi_clr_threshold(struct bq27z561 *dev, int8_t *temp_c) { int rc; rc = bq27z561_rd_std_reg_byte(dev, BQ27Z561_REG_TEMP_HI_CLR_TH, (uint8_t *)temp_c); return rc; } int bq27z561_set_temp_hi_clr_threshold(struct bq27z561 *dev, int8_t temp_c) { int rc; rc = bq27z561_wr_std_reg_byte(dev, BQ27Z561_REG_TEMP_HI_CLR_TH, (uint8_t)temp_c); return rc; } int bq27z561_get_voltage(struct bq27z561 *dev, uint16_t *voltage) { int rc; rc = bq27z561_rd_std_reg_word(dev, BQ27Z561_REG_VOLT, voltage); return rc; } int bq27z561_get_voltage_lo_set_threshold(struct bq27z561 *dev, uint16_t *voltage) { int rc; rc = bq27z561_rd_std_reg_word(dev, BQ27Z561_REG_VOLT_LO_SET_TH, voltage); return rc; } int bq27z561_set_voltage_lo_set_threshold(struct bq27z561 *dev, uint16_t voltage) { int rc; rc = bq27z561_wr_std_reg_word(dev, BQ27Z561_REG_VOLT_LO_SET_TH, voltage); return rc; } int bq27z561_get_voltage_lo_clr_threshold(struct bq27z561 *dev, uint16_t *voltage) { int rc; rc = bq27z561_rd_std_reg_word(dev, BQ27Z561_REG_VOLT_LO_CLR_TH, voltage); return rc; } int bq27z561_set_voltage_lo_clr_threshold(struct bq27z561 *dev, uint16_t voltage) { int rc; rc = bq27z561_wr_std_reg_word(dev, BQ27Z561_REG_VOLT_LO_CLR_TH, voltage); return rc; } int bq27z561_get_voltage_hi_set_threshold(struct bq27z561 *dev, uint16_t *voltage) { int rc; rc = bq27z561_rd_std_reg_word(dev, BQ27Z561_REG_VOLT_HI_SET_TH, voltage); return rc; } int bq27z561_set_voltage_hi_set_threshold(struct bq27z561 *dev, uint16_t voltage) { int rc; rc = bq27z561_rd_std_reg_word(dev, BQ27Z561_REG_VOLT_HI_SET_TH, &voltage); return rc; } int bq27z561_get_voltage_hi_clr_threshold(struct bq27z561 *dev, uint16_t *voltage) { int rc; rc = bq27z561_rd_std_reg_word(dev, BQ27Z561_REG_VOLT_HI_CLR_TH, voltage); return rc; } int bq27z561_set_voltage_hi_clr_threshold(struct bq27z561 *dev, uint16_t voltage) { int rc; rc = bq27z561_wr_std_reg_word(dev, BQ27Z561_REG_VOLT_HI_CLR_TH, voltage); return rc; } int bq27z561_get_batt_status(struct bq27z561 *dev, uint16_t *status) { int rc; rc = bq27z561_rd_std_reg_word(dev, BQ27Z561_REG_FLAGS, status); return rc; } int bq27z561_get_current(struct bq27z561 *dev, int16_t *current) { int rc; rc = bq27z561_rd_std_reg_word(dev, BQ27Z561_REG_INSTCURR, (uint16_t *)current); return rc; } /* XXX: no support for register IMAX */ int bq27z561_get_rem_capacity(struct bq27z561 *dev, uint16_t *capacity) { int rc; rc = bq27z561_rd_std_reg_word(dev, BQ27Z561_REG_RM, capacity); return rc; } int bq27z561_get_full_chg_capacity(struct bq27z561 *dev, uint16_t *capacity) { int rc; rc = bq27z561_rd_std_reg_word(dev, BQ27Z561_REG_FCC, capacity); return rc; } int bq27z561_get_avg_current(struct bq27z561 *dev, int16_t *current) { int rc; rc = bq27z561_rd_std_reg_word(dev, BQ27Z561_REG_AI, (uint16_t *)current); return rc; } int bq27z561_get_avg_time_to_empty(struct bq27z561 *dev, uint16_t *tte) { int rc; rc = bq27z561_rd_std_reg_word(dev, BQ27Z561_REG_TTE, tte); return rc; } int bq27z561_get_avg_time_to_full(struct bq27z561 *dev, uint16_t *ttf) { int rc; rc = bq27z561_rd_std_reg_word(dev, BQ27Z561_REG_TTF, ttf); return rc; } int bq27z561_get_avg_power(struct bq27z561 *dev, int16_t *pwr) { int rc; rc = bq27z561_rd_std_reg_word(dev, BQ27Z561_REG_AP, (uint16_t *)pwr); return rc; } /* XXX: no support for max load current */ /* XXX: no support for max load time to empty */ int bq27z561_get_internal_temp(struct bq27z561 *dev, float *temp_c) { int rc; uint16_t val; rc = bq27z561_rd_std_reg_word(dev, BQ27Z561_REG_INT_TEMP, &val); if (!rc) { *temp_c = bq27z561_temp_to_celsius(val); } return rc; } int bq27z561_get_discharge_cycles(struct bq27z561 *dev, uint16_t *cycles) { int rc; rc = bq27z561_rd_std_reg_word(dev, BQ27Z561_REG_CC, cycles); return rc; } int bq27z561_get_relative_state_of_charge(struct bq27z561 *dev, uint8_t *pcnt) { int rc; uint16_t val; rc = bq27z561_rd_std_reg_word(dev, BQ27Z561_REG_RSOC, &val); if (!rc) { *pcnt = (uint8_t)val; } return rc; } int bq27z561_get_state_of_health(struct bq27z561 *dev, uint8_t *pcnt) { int rc; uint16_t val; rc = bq27z561_rd_std_reg_word(dev, BQ27Z561_REG_SOH, &val); if (!rc) { *pcnt = (uint8_t)val; } return rc; } int bq27z561_get_charging_voltage(struct bq27z561 *dev, uint16_t *voltage) { int rc; rc = bq27z561_rd_std_reg_word(dev, BQ27Z561_REG_CV, voltage); return rc; } int bq27z561_get_charging_current(struct bq27z561 *dev, uint16_t *current) { int rc; rc = bq27z561_rd_std_reg_word(dev, BQ27Z561_REG_CHGC, current); return rc; } int bq27z561_config(struct bq27z561 *dev, struct bq27z561_cfg *cfg) { return 0; } /* Battery manager interface functions */ static int bq27z561_battery_property_get(struct battery_driver *driver, struct battery_property *property, uint32_t timeout) { int rc = 0; struct bq27z561 * bq_dev; bq_dev = (struct bq27z561 *)&driver->dev; if (!bq_dev->bq27_initialized) { rc = bq27z561_get_init_status((struct bq27z561 *) driver->bd_driver_data, &bq_dev->bq27_initialized); if (!bq_dev->bq27_initialized) { rc = -2; property->bp_valid = 0; return rc; } } battery_property_value_t val; if (property->bp_type == BATTERY_PROP_VOLTAGE_NOW && property->bp_flags == 0) { rc = bq27z561_get_voltage((struct bq27z561 *) driver->bd_driver_data, &val.bpv_u16); property->bp_value.bpv_voltage = val.bpv_u16; } else if (property->bp_type == BATTERY_PROP_VOLTAGE_NOW && property->bp_flags == BATTERY_PROPERTY_FLAGS_LOW_ALARM_SET_THRESHOLD) { rc = bq27z561_get_voltage_lo_set_threshold( (struct bq27z561 *) driver->bd_driver_data, &val.bpv_u16); property->bp_value.bpv_voltage = val.bpv_u16; } else if (property->bp_type == BATTERY_PROP_VOLTAGE_NOW && property->bp_flags == BATTERY_PROPERTY_FLAGS_LOW_ALARM_CLEAR_THRESHOLD) { rc = bq27z561_get_voltage_lo_clr_threshold( (struct bq27z561 *) driver->bd_driver_data, &val.bpv_u16); property->bp_value.bpv_voltage = val.bpv_u16; } else if (property->bp_type == BATTERY_PROP_VOLTAGE_NOW && property->bp_flags == BATTERY_PROPERTY_FLAGS_HIGH_ALARM_SET_THRESHOLD) { rc = bq27z561_get_voltage_hi_set_threshold( (struct bq27z561 *) driver->bd_driver_data, &val.bpv_u16); property->bp_value.bpv_voltage = val.bpv_u16; } else if (property->bp_type == BATTERY_PROP_VOLTAGE_NOW && property->bp_flags == BATTERY_PROPERTY_FLAGS_HIGH_ALARM_CLEAR_THRESHOLD) { rc = bq27z561_get_voltage_hi_clr_threshold( (struct bq27z561 *) driver->bd_driver_data, &val.bpv_u16); property->bp_value.bpv_voltage = val.bpv_u16; } else if (property->bp_type == BATTERY_PROP_STATUS && property->bp_flags == 0) { rc = bq27z561_get_batt_status((struct bq27z561 *) driver->bd_driver_data, &val.bpv_u16); if (val.bpv_u16 & BQ27Z561_BATTERY_STATUS_DSG) { property->bp_value.bpv_status = BATTERY_STATUS_DISCHARGING; } else if (val.bpv_u16 & BQ27Z561_BATTERY_STATUS_FC) { property->bp_value.bpv_status = BATTERY_STATUS_FULL; } else { property->bp_value.bpv_status = BATTERY_STATUS_CHARGING; } } else if (property->bp_type == BATTERY_PROP_CURRENT_NOW && property->bp_flags == 0) { rc = bq27z561_get_current((struct bq27z561 *) driver->bd_driver_data, &val.bpv_i16); property->bp_value.bpv_current = val.bpv_i16; } else if (property->bp_type == BATTERY_PROP_CAPACITY && property->bp_flags == 0) { rc = bq27z561_get_rem_capacity((struct bq27z561 *) driver->bd_driver_data, &val.bpv_u16); property->bp_value.bpv_capacity = val.bpv_u16; } else if (property->bp_type == BATTERY_PROP_SOC && property->bp_flags == 0) { rc = bq27z561_get_relative_state_of_charge( (struct bq27z561 *) driver->bd_driver_data, &val.bpv_u8); property->bp_value.bpv_soc = val.bpv_u8; } else if (property->bp_type == BATTERY_PROP_SOH && property->bp_flags == 0) { rc = bq27z561_get_state_of_health( (struct bq27z561 *) driver->bd_driver_data, &val.bpv_u8); property->bp_value.bpv_soh = val.bpv_u8; } else if (property->bp_type == BATTERY_PROP_CYCLE_COUNT && property->bp_flags == 0) { rc = bq27z561_get_discharge_cycles( (struct bq27z561 *) driver->bd_driver_data, &val.bpv_u16); property->bp_value.bpv_cycle_count = val.bpv_u16; } else if (property->bp_type == BATTERY_PROP_TIME_TO_EMPTY_NOW && property->bp_flags == 0) { rc = bq27z561_get_time_to_empty( (struct bq27z561 *) driver->bd_driver_data, &val.bpv_u16); property->bp_value.bpv_time_in_s = (uint8_t)val.bpv_u16 * 60; } else if (property->bp_type == BATTERY_PROP_TIME_TO_FULL_NOW && property->bp_flags == 0) { rc = bq27z561_get_avg_time_to_full( (struct bq27z561 *) driver->bd_driver_data, &val.bpv_u16); property->bp_value.bpv_time_in_s = val.bpv_u16 * 60; } else if (property->bp_type == BATTERY_PROP_TEMP_NOW && property->bp_flags == 0) { rc = bq27z561_get_temp( (struct bq27z561 *) driver->bd_driver_data, &val.bpv_flt); property->bp_value.bpv_temperature = val.bpv_flt; } else if (property->bp_type == BATTERY_PROP_TEMP_NOW && property->bp_flags == BATTERY_PROPERTY_FLAGS_LOW_ALARM_SET_THRESHOLD) { rc = bq27z561_get_temp_lo_set_threshold( (struct bq27z561 *) driver->bd_driver_data, &val.bpv_i8); property->bp_value.bpv_temperature = val.bpv_i8; } else if (property->bp_type == BATTERY_PROP_TEMP_NOW && property->bp_flags == BATTERY_PROPERTY_FLAGS_LOW_ALARM_CLEAR_THRESHOLD) { rc = bq27z561_get_temp_lo_clr_threshold( (struct bq27z561 *) driver->bd_driver_data, &val.bpv_i8); property->bp_value.bpv_temperature = val.bpv_i8; } else if (property->bp_type == BATTERY_PROP_TEMP_NOW && property->bp_flags == BATTERY_PROPERTY_FLAGS_HIGH_ALARM_SET_THRESHOLD) { rc = bq27z561_get_temp_hi_set_threshold( (struct bq27z561 *) driver->bd_driver_data, &val.bpv_i8); property->bp_value.bpv_temperature = val.bpv_i8; } else if (property->bp_type == BATTERY_PROP_TEMP_NOW && property->bp_flags == BATTERY_PROPERTY_FLAGS_HIGH_ALARM_CLEAR_THRESHOLD) { rc = bq27z561_get_temp_hi_clr_threshold( (struct bq27z561 *) driver->bd_driver_data, &val.bpv_i8); property->bp_value.bpv_temperature = val.bpv_i8; } else { rc = -1; return rc; } if (rc == 0) { property->bp_valid = 1; } else { property->bp_valid = 0; } return rc; } static int bq27z561_battery_property_set(struct battery_driver *driver, struct battery_property *property) { int rc = 0; if (property->bp_type == BATTERY_PROP_VOLTAGE_NOW && property->bp_flags == BATTERY_PROPERTY_FLAGS_LOW_ALARM_SET_THRESHOLD) { rc = bq27z561_set_voltage_lo_set_threshold( (struct bq27z561 *)driver->bd_driver_data, property->bp_value.bpv_voltage); } else if (property->bp_type == BATTERY_PROP_VOLTAGE_NOW && property->bp_flags == BATTERY_PROPERTY_FLAGS_LOW_ALARM_CLEAR_THRESHOLD) { rc = bq27z561_set_voltage_lo_clr_threshold( (struct bq27z561 *)driver->bd_driver_data, property->bp_value.bpv_voltage); } else if (property->bp_type == BATTERY_PROP_VOLTAGE_NOW && property->bp_flags == BATTERY_PROPERTY_FLAGS_HIGH_ALARM_SET_THRESHOLD) { rc = bq27z561_set_voltage_hi_set_threshold( (struct bq27z561 *)driver->bd_driver_data, property->bp_value.bpv_voltage); } else if (property->bp_type == BATTERY_PROP_VOLTAGE_NOW && property->bp_flags == BATTERY_PROPERTY_FLAGS_HIGH_ALARM_CLEAR_THRESHOLD) { rc = bq27z561_set_voltage_hi_clr_threshold( (struct bq27z561 *)driver->bd_driver_data, property->bp_value.bpv_voltage); } else if (property->bp_type == BATTERY_PROP_TEMP_NOW && property->bp_flags == BATTERY_PROPERTY_FLAGS_LOW_ALARM_SET_THRESHOLD) { rc = bq27z561_set_temp_lo_set_threshold( (struct bq27z561 *) driver->bd_driver_data, (int8_t)property->bp_value.bpv_temperature); } else if (property->bp_type == BATTERY_PROP_TEMP_NOW && property->bp_flags == BATTERY_PROPERTY_FLAGS_LOW_ALARM_CLEAR_THRESHOLD) { rc = bq27z561_set_temp_lo_clr_threshold( (struct bq27z561 *) driver->bd_driver_data, (int16_t)property->bp_value.bpv_temperature); } else if (property->bp_type == BATTERY_PROP_TEMP_NOW && property->bp_flags == BATTERY_PROPERTY_FLAGS_HIGH_ALARM_SET_THRESHOLD) { rc = bq27z561_set_temp_hi_set_threshold( (struct bq27z561 *) driver->bd_driver_data, (int16_t)property->bp_value.bpv_temperature); } else if (property->bp_type == BATTERY_PROP_TEMP_NOW && property->bp_flags == BATTERY_PROPERTY_FLAGS_HIGH_ALARM_CLEAR_THRESHOLD) { rc = bq27z561_set_temp_hi_clr_threshold( (struct bq27z561 *) driver->bd_driver_data, (int16_t)property->bp_value.bpv_temperature); } else { rc = -1; } return rc; } static int bq27z561_enable(struct battery *battery) { return 0; } static int bq27z561_disable(struct battery *battery) { return 0; } static const struct battery_driver_functions bq27z561_drv_funcs = { .bdf_property_get = bq27z561_battery_property_get, .bdf_property_set = bq27z561_battery_property_set, .bdf_enable = bq27z561_enable, .bdf_disable = bq27z561_disable, }; static const struct battery_driver_property bq27z561_battery_properties[] = { { BATTERY_PROP_STATUS, 0, "Status" }, { BATTERY_PROP_CAPACITY, 0, "Capacity" }, { BATTERY_PROP_TEMP_NOW, 0, "Temperature" }, { BATTERY_PROP_VOLTAGE_NOW, 0, "Voltage" }, { BATTERY_PROP_CURRENT_NOW, 0, "Current" }, { BATTERY_PROP_SOC, 0, "SOC" }, { BATTERY_PROP_SOH, 0, "SOH" }, { BATTERY_PROP_TIME_TO_EMPTY_NOW, 0, "TimeToEmpty" }, { BATTERY_PROP_TIME_TO_FULL_NOW, 0, "TimeToFull" }, { BATTERY_PROP_CYCLE_COUNT, 0, "CycleCount" }, { BATTERY_PROP_VOLTAGE_NOW, BATTERY_PROPERTY_FLAGS_LOW_ALARM_SET_THRESHOLD, "LoVoltAlarmSet" }, { BATTERY_PROP_VOLTAGE_NOW, BATTERY_PROPERTY_FLAGS_LOW_ALARM_CLEAR_THRESHOLD, "LoVoltAlarmClear" }, { BATTERY_PROP_VOLTAGE_NOW, BATTERY_PROPERTY_FLAGS_HIGH_ALARM_SET_THRESHOLD, "HiVoltAlarmSet" }, { BATTERY_PROP_VOLTAGE_NOW, BATTERY_PROPERTY_FLAGS_HIGH_ALARM_CLEAR_THRESHOLD, "HiVoltAlarmClear" }, { BATTERY_PROP_TEMP_NOW, BATTERY_PROPERTY_FLAGS_LOW_ALARM_SET_THRESHOLD, "LoTempAlarmSet" }, { BATTERY_PROP_TEMP_NOW, BATTERY_PROPERTY_FLAGS_LOW_ALARM_CLEAR_THRESHOLD, "LoTempAlarmClear" }, { BATTERY_PROP_TEMP_NOW, BATTERY_PROPERTY_FLAGS_HIGH_ALARM_SET_THRESHOLD, "LoTempAlarmSet" }, { BATTERY_PROP_TEMP_NOW, BATTERY_PROPERTY_FLAGS_HIGH_ALARM_CLEAR_THRESHOLD, "HiTempAlarmClear" }, { BATTERY_PROP_NONE }, }; int bq27z561_init(struct os_dev *dev, void *arg) { struct bq27z561 *bq27; struct bq27z561_init_arg *init_arg = (struct bq27z561_init_arg *)arg; if (!dev || !arg) { return SYS_ENODEV; } OS_DEV_SETHANDLERS(dev, bq27z561_open, bq27z561_close); bq27 = (struct bq27z561 *)dev; bq27->bq27_initialized = 0; /* Copy the interface struct */ bq27->bq27_itf = init_arg->itf; bq27->dev.bd_funcs = &bq27z561_drv_funcs; bq27->dev.bd_driver_properties = bq27z561_battery_properties; bq27->dev.bd_driver_data = bq27; battery_add_driver(init_arg->battery, &bq27->dev); return 0; } int bq27z561_pkg_init(void) { #if MYNEWT_VAL(BQ27Z561_CLI) return bq27z561_shell_init(); #else return 0; #endif }
28.119415
98
0.650672
5cbb2d43a784dd429e9f67c8ffe9882778b4165a
490
h
C
src/renderer/vulkan/CommandBuffer.h
Ryp/reaper
da7b3aa4a69b95ced2496214e5cea4eb7823593a
[ "MIT" ]
10
2018-08-16T05:32:46.000Z
2022-02-04T09:55:54.000Z
src/renderer/vulkan/CommandBuffer.h
Ryp/reaper
da7b3aa4a69b95ced2496214e5cea4eb7823593a
[ "MIT" ]
null
null
null
src/renderer/vulkan/CommandBuffer.h
Ryp/reaper
da7b3aa4a69b95ced2496214e5cea4eb7823593a
[ "MIT" ]
1
2019-05-13T17:56:35.000Z
2019-05-13T17:56:35.000Z
//////////////////////////////////////////////////////////////////////////////// /// Reaper /// /// Copyright (c) 2015-2021 Thibault Schueller /// This file is distributed under the MIT License //////////////////////////////////////////////////////////////////////////////// #pragma once #include "api/Vulkan.h" struct MicroProfileThreadLogGpu; namespace Reaper { struct CommandBuffer { VkCommandBuffer handle; MicroProfileThreadLogGpu* mlog; }; } // namespace Reaper
22.272727
80
0.479592
a9ed6f36e6ead1d32bf754b50d5eaed3068d6cf2
11,450
c
C
SOFTWARE/A64-TERES/linux-a64/fs/minix/dir.c
xloem/DIY-LAPTOP
f2a410706f7a919ac644de073c570629d5601203
[ "Apache-2.0" ]
2
2017-10-30T12:25:44.000Z
2019-08-25T09:01:38.000Z
SOFTWARE/A64-TERES/linux-a64/fs/minix/dir.c
xloem/DIY-LAPTOP
f2a410706f7a919ac644de073c570629d5601203
[ "Apache-2.0" ]
null
null
null
SOFTWARE/A64-TERES/linux-a64/fs/minix/dir.c
xloem/DIY-LAPTOP
f2a410706f7a919ac644de073c570629d5601203
[ "Apache-2.0" ]
4
2017-12-19T10:52:20.000Z
2019-08-25T09:01:40.000Z
/* * linux/fs/minix/dir.c * * Copyright (C) 1991, 1992 Linus Torvalds * * minix directory handling functions * * Updated to filesystem version 3 by Daniel Aragones */ #include "minix.h" #include <linux/buffer_head.h> #include <linux/highmem.h> #include <linux/swap.h> typedef struct minix_dir_entry minix_dirent; typedef struct minix3_dir_entry minix3_dirent; static int minix_readdir(struct file *, void *, filldir_t); const struct file_operations minix_dir_operations = { .llseek = generic_file_llseek, .read = generic_read_dir, .readdir = minix_readdir, .fsync = generic_file_fsync, }; static inline void dir_put_page(struct page *page) { kunmap(page); page_cache_release(page); } /* * Return the offset into page `page_nr' of the last valid * byte in that page, plus one. */ static unsigned minix_last_byte(struct inode *inode, unsigned long page_nr) { unsigned last_byte = PAGE_CACHE_SIZE; if (page_nr == (inode->i_size >> PAGE_CACHE_SHIFT)) last_byte = inode->i_size & (PAGE_CACHE_SIZE - 1); return last_byte; } static inline unsigned long dir_pages(struct inode *inode) { return (inode->i_size+PAGE_CACHE_SIZE-1)>>PAGE_CACHE_SHIFT; } static int dir_commit_chunk(struct page *page, loff_t pos, unsigned len) { struct address_space *mapping = page->mapping; struct inode *dir = mapping->host; int err = 0; block_write_end(NULL, mapping, pos, len, len, page, NULL); if (pos+len > dir->i_size) { i_size_write(dir, pos+len); mark_inode_dirty(dir); } if (IS_DIRSYNC(dir)) err = write_one_page(page, 1); else unlock_page(page); return err; } static struct page * dir_get_page(struct inode *dir, unsigned long n) { struct address_space *mapping = dir->i_mapping; struct page *page = read_mapping_page(mapping, n, NULL); if (!IS_ERR(page)) kmap(page); return page; } static inline void *minix_next_entry(void *de, struct minix_sb_info *sbi) { return (void*)((char*)de + sbi->s_dirsize); } static int minix_readdir(struct file * filp, void * dirent, filldir_t filldir) { unsigned long pos = filp->f_pos; struct inode *inode = file_inode(filp); struct super_block *sb = inode->i_sb; unsigned offset = pos & ~PAGE_CACHE_MASK; unsigned long n = pos >> PAGE_CACHE_SHIFT; unsigned long npages = dir_pages(inode); struct minix_sb_info *sbi = minix_sb(sb); unsigned chunk_size = sbi->s_dirsize; char *name; __u32 inumber; pos = (pos + chunk_size-1) & ~(chunk_size-1); if (pos >= inode->i_size) goto done; for ( ; n < npages; n++, offset = 0) { char *p, *kaddr, *limit; struct page *page = dir_get_page(inode, n); if (IS_ERR(page)) continue; kaddr = (char *)page_address(page); p = kaddr+offset; limit = kaddr + minix_last_byte(inode, n) - chunk_size; for ( ; p <= limit; p = minix_next_entry(p, sbi)) { if (sbi->s_version == MINIX_V3) { minix3_dirent *de3 = (minix3_dirent *)p; name = de3->name; inumber = de3->inode; } else { minix_dirent *de = (minix_dirent *)p; name = de->name; inumber = de->inode; } if (inumber) { int over; unsigned l = strnlen(name, sbi->s_namelen); offset = p - kaddr; over = filldir(dirent, name, l, (n << PAGE_CACHE_SHIFT) | offset, inumber, DT_UNKNOWN); if (over) { dir_put_page(page); goto done; } } } dir_put_page(page); } done: filp->f_pos = (n << PAGE_CACHE_SHIFT) | offset; return 0; } static inline int namecompare(int len, int maxlen, const char * name, const char * buffer) { if (len < maxlen && buffer[len]) return 0; return !memcmp(name, buffer, len); } /* * minix_find_entry() * * finds an entry in the specified directory with the wanted name. It * returns the cache buffer in which the entry was found, and the entry * itself (as a parameter - res_dir). It does NOT read the inode of the * entry - you'll have to do that yourself if you want to. */ minix_dirent *minix_find_entry(struct dentry *dentry, struct page **res_page) { const char * name = dentry->d_name.name; int namelen = dentry->d_name.len; struct inode * dir = dentry->d_parent->d_inode; struct super_block * sb = dir->i_sb; struct minix_sb_info * sbi = minix_sb(sb); unsigned long n; unsigned long npages = dir_pages(dir); struct page *page = NULL; char *p; char *namx; __u32 inumber; *res_page = NULL; for (n = 0; n < npages; n++) { char *kaddr, *limit; page = dir_get_page(dir, n); if (IS_ERR(page)) continue; kaddr = (char*)page_address(page); limit = kaddr + minix_last_byte(dir, n) - sbi->s_dirsize; for (p = kaddr; p <= limit; p = minix_next_entry(p, sbi)) { if (sbi->s_version == MINIX_V3) { minix3_dirent *de3 = (minix3_dirent *)p; namx = de3->name; inumber = de3->inode; } else { minix_dirent *de = (minix_dirent *)p; namx = de->name; inumber = de->inode; } if (!inumber) continue; if (namecompare(namelen, sbi->s_namelen, name, namx)) goto found; } dir_put_page(page); } return NULL; found: *res_page = page; return (minix_dirent *)p; } int minix_add_link(struct dentry *dentry, struct inode *inode) { struct inode *dir = dentry->d_parent->d_inode; const char * name = dentry->d_name.name; int namelen = dentry->d_name.len; struct super_block * sb = dir->i_sb; struct minix_sb_info * sbi = minix_sb(sb); struct page *page = NULL; unsigned long npages = dir_pages(dir); unsigned long n; char *kaddr, *p; minix_dirent *de; minix3_dirent *de3; loff_t pos; int err; char *namx = NULL; __u32 inumber; /* * We take care of directory expansion in the same loop * This code plays outside i_size, so it locks the page * to protect that region. */ for (n = 0; n <= npages; n++) { char *limit, *dir_end; page = dir_get_page(dir, n); err = PTR_ERR(page); if (IS_ERR(page)) goto out; lock_page(page); kaddr = (char*)page_address(page); dir_end = kaddr + minix_last_byte(dir, n); limit = kaddr + PAGE_CACHE_SIZE - sbi->s_dirsize; for (p = kaddr; p <= limit; p = minix_next_entry(p, sbi)) { de = (minix_dirent *)p; de3 = (minix3_dirent *)p; if (sbi->s_version == MINIX_V3) { namx = de3->name; inumber = de3->inode; } else { namx = de->name; inumber = de->inode; } if (p == dir_end) { /* We hit i_size */ if (sbi->s_version == MINIX_V3) de3->inode = 0; else de->inode = 0; goto got_it; } if (!inumber) goto got_it; err = -EEXIST; if (namecompare(namelen, sbi->s_namelen, name, namx)) goto out_unlock; } unlock_page(page); dir_put_page(page); } BUG(); return -EINVAL; got_it: pos = page_offset(page) + p - (char *)page_address(page); err = minix_prepare_chunk(page, pos, sbi->s_dirsize); if (err) goto out_unlock; memcpy (namx, name, namelen); if (sbi->s_version == MINIX_V3) { memset (namx + namelen, 0, sbi->s_dirsize - namelen - 4); de3->inode = inode->i_ino; } else { memset (namx + namelen, 0, sbi->s_dirsize - namelen - 2); de->inode = inode->i_ino; } err = dir_commit_chunk(page, pos, sbi->s_dirsize); dir->i_mtime = dir->i_ctime = CURRENT_TIME_SEC; mark_inode_dirty(dir); out_put: dir_put_page(page); out: return err; out_unlock: unlock_page(page); goto out_put; } int minix_delete_entry(struct minix_dir_entry *de, struct page *page) { struct inode *inode = page->mapping->host; char *kaddr = page_address(page); loff_t pos = page_offset(page) + (char*)de - kaddr; struct minix_sb_info *sbi = minix_sb(inode->i_sb); unsigned len = sbi->s_dirsize; int err; lock_page(page); err = minix_prepare_chunk(page, pos, len); if (err == 0) { if (sbi->s_version == MINIX_V3) ((minix3_dirent *) de)->inode = 0; else de->inode = 0; err = dir_commit_chunk(page, pos, len); } else { unlock_page(page); } dir_put_page(page); inode->i_ctime = inode->i_mtime = CURRENT_TIME_SEC; mark_inode_dirty(inode); return err; } int minix_make_empty(struct inode *inode, struct inode *dir) { struct page *page = grab_cache_page(inode->i_mapping, 0); struct minix_sb_info *sbi = minix_sb(inode->i_sb); char *kaddr; int err; if (!page) return -ENOMEM; err = minix_prepare_chunk(page, 0, 2 * sbi->s_dirsize); if (err) { unlock_page(page); goto fail; } kaddr = kmap_atomic(page); memset(kaddr, 0, PAGE_CACHE_SIZE); if (sbi->s_version == MINIX_V3) { minix3_dirent *de3 = (minix3_dirent *)kaddr; de3->inode = inode->i_ino; strcpy(de3->name, "."); de3 = minix_next_entry(de3, sbi); de3->inode = dir->i_ino; strcpy(de3->name, ".."); } else { minix_dirent *de = (minix_dirent *)kaddr; de->inode = inode->i_ino; strcpy(de->name, "."); de = minix_next_entry(de, sbi); de->inode = dir->i_ino; strcpy(de->name, ".."); } kunmap_atomic(kaddr); err = dir_commit_chunk(page, 0, 2 * sbi->s_dirsize); fail: page_cache_release(page); return err; } /* * routine to check that the specified directory is empty (for rmdir) */ int minix_empty_dir(struct inode * inode) { struct page *page = NULL; unsigned long i, npages = dir_pages(inode); struct minix_sb_info *sbi = minix_sb(inode->i_sb); char *name; __u32 inumber; for (i = 0; i < npages; i++) { char *p, *kaddr, *limit; page = dir_get_page(inode, i); if (IS_ERR(page)) continue; kaddr = (char *)page_address(page); limit = kaddr + minix_last_byte(inode, i) - sbi->s_dirsize; for (p = kaddr; p <= limit; p = minix_next_entry(p, sbi)) { if (sbi->s_version == MINIX_V3) { minix3_dirent *de3 = (minix3_dirent *)p; name = de3->name; inumber = de3->inode; } else { minix_dirent *de = (minix_dirent *)p; name = de->name; inumber = de->inode; } if (inumber != 0) { /* check for . and .. */ if (name[0] != '.') goto not_empty; if (!name[1]) { if (inumber != inode->i_ino) goto not_empty; } else if (name[1] != '.') goto not_empty; else if (name[2]) goto not_empty; } } dir_put_page(page); } return 1; not_empty: dir_put_page(page); return 0; } /* Releases the page */ void minix_set_link(struct minix_dir_entry *de, struct page *page, struct inode *inode) { struct inode *dir = page->mapping->host; struct minix_sb_info *sbi = minix_sb(dir->i_sb); loff_t pos = page_offset(page) + (char *)de-(char*)page_address(page); int err; lock_page(page); err = minix_prepare_chunk(page, pos, sbi->s_dirsize); if (err == 0) { if (sbi->s_version == MINIX_V3) ((minix3_dirent *) de)->inode = inode->i_ino; else de->inode = inode->i_ino; err = dir_commit_chunk(page, pos, sbi->s_dirsize); } else { unlock_page(page); } dir_put_page(page); dir->i_mtime = dir->i_ctime = CURRENT_TIME_SEC; mark_inode_dirty(dir); } struct minix_dir_entry * minix_dotdot (struct inode *dir, struct page **p) { struct page *page = dir_get_page(dir, 0); struct minix_sb_info *sbi = minix_sb(dir->i_sb); struct minix_dir_entry *de = NULL; if (!IS_ERR(page)) { de = minix_next_entry(page_address(page), sbi); *p = page; } return de; } ino_t minix_inode_by_name(struct dentry *dentry) { struct page *page; struct minix_dir_entry *de = minix_find_entry(dentry, &page); ino_t res = 0; if (de) { struct address_space *mapping = page->mapping; struct inode *inode = mapping->host; struct minix_sb_info *sbi = minix_sb(inode->i_sb); if (sbi->s_version == MINIX_V3) res = ((minix3_dirent *) de)->inode; else res = de->inode; dir_put_page(page); } return res; }
23.953975
78
0.66131
b762b2f42f7b46e3b1a9fb83c605e1a3cf041414
4,376
h
C
decoder/ixheaacd_type_def.h
khadas/android_external_libxaac
a6f303c9320a81de4314e611d78b2afc11432785
[ "Apache-2.0" ]
null
null
null
decoder/ixheaacd_type_def.h
khadas/android_external_libxaac
a6f303c9320a81de4314e611d78b2afc11432785
[ "Apache-2.0" ]
null
null
null
decoder/ixheaacd_type_def.h
khadas/android_external_libxaac
a6f303c9320a81de4314e611d78b2afc11432785
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** * * * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************** * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore */ #ifndef IXHEAACD_TYPE_DEF_H #define IXHEAACD_TYPE_DEF_H /****************************************************************************/ /* types type define prefix examples * bytes */ /************************ *********** ****** **************** ***** */ #define SIZE_T size_t typedef char CHAR8; /* c CHAR8 c_name 1 */ typedef char* pCHAR8; /* pc pCHAR8 pc_nmae 1 */ typedef signed char WORD8; /* b WORD8 b_name 1 */ typedef signed char* pWORD8; /* pb pWORD8 pb_nmae 1 */ typedef unsigned char UWORD8; /* ub UWORD8 ub_count 1 */ typedef unsigned char* pUWORD8; /* pub pUWORD8 pub_count 1 */ typedef signed short WORD16; /* s WORD16 s_count 2 */ typedef signed short* pWORD16; /* ps pWORD16 ps_count 2 */ typedef unsigned short UWORD16; /* us UWORD16 us_count 2 */ typedef unsigned short* pUWORD16; /* pus pUWORD16 pus_count 2 */ typedef signed int WORD24; /* k WORD24 k_count 3 */ typedef signed int* pWORD24; /* pk pWORD24 pk_count 3 */ typedef unsigned int UWORD24; /* uk UWORD24 uk_count 3 */ typedef unsigned int* pUWORD24; /* puk pUWORD24 puk_count 3 */ typedef signed int WORD32; /* i WORD32 i_count 4 */ typedef signed int* pWORD32; /* pi pWORD32 pi_count 4 */ typedef unsigned int UWORD32; /* ui UWORD32 ui_count 4 */ typedef unsigned int* pUWORD32; /* pui pUWORD32 pui_count 4 */ typedef signed long long WORD40; /* m WORD40 m_count 5 */ typedef signed long long* pWORD40; /* pm pWORD40 pm_count 5 */ typedef unsigned long long UWORD40; /* um UWORD40 um_count 5 */ typedef unsigned long long* pUWORD40; /* pum pUWORD40 pum_count 5 */ typedef signed long long WORD64; /* h WORD64 h_count 8 */ typedef signed long long* pWORD64; /* ph pWORD64 ph_count 8 */ typedef unsigned long long UWORD64; /* uh UWORD64 uh_count 8 */ typedef unsigned long long* pUWORD64; /* puh pUWORD64 puh_count 8 */ typedef float FLOAT32; /* f FLOAT32 f_count 4 */ typedef float* pFLOAT32; /* pf pFLOAT32 pf_count 4 */ typedef double FLOAT64; /* d UFLOAT64 d_count 8 */ typedef double* pFlOAT64; /* pd pFLOAT64 pd_count 8 */ typedef void VOID; /* v VOID v_flag 4 */ typedef void* pVOID; /* pv pVOID pv_flag 4 */ /* variable size types: platform optimized implementation */ typedef signed int BOOL; /* bool BOOL bool_true */ typedef unsigned int UBOOL; /* ubool BOOL ubool_true */ typedef signed int FLAG; /* flag FLAG flag_false */ typedef unsigned int UFLAG; /* uflag FLAG uflag_false */ typedef signed int LOOPIDX; /* lp LOOPIDX lp_index */ typedef unsigned int ULOOPIDX; /* ulp SLOOPIDX ulp_index */ typedef signed int WORD; /* lp LOOPIDX lp_index */ typedef unsigned int UWORD; /* ulp SLOOPIDX ulp_index */ typedef LOOPIDX LOOPINDEX; /* lp LOOPIDX lp_index */ typedef ULOOPIDX ULOOPINDEX; /* ulp SLOOPIDX ulp_index */ #define PLATFORM_INLINE __inline #endif /* IXHEAACD_TYPE_DEF_H */
48.622222
79
0.561015
c84d7a7442f77f80a29c91aff0ceb7f0067ada0f
889
h
C
Part B/PhoneBook.h
burakkorki/Phonebook_Cs201
3bed6d2814e5d23360cade3188b8e2c98394b0e2
[ "MIT" ]
null
null
null
Part B/PhoneBook.h
burakkorki/Phonebook_Cs201
3bed6d2814e5d23360cade3188b8e2c98394b0e2
[ "MIT" ]
null
null
null
Part B/PhoneBook.h
burakkorki/Phonebook_Cs201
3bed6d2814e5d23360cade3188b8e2c98394b0e2
[ "MIT" ]
null
null
null
// // PhoneBook.hpp // Homework-3-PartB // // Created by Burak Korkmaz on 13.12.2018. // Copyright © 2018 Burak Korkmaz. All rights reserved. // #ifndef __PHONEBOOK_H #define __PHONEBOOK_H #include <string> using namespace std; #include "Person.h" class PhoneBook { public: PhoneBook(); ~PhoneBook(); PhoneBook( const PhoneBook& systemToCopy ); void operator=( const PhoneBook &right ); bool addPerson( string name ); bool removePerson( string name ); bool addPhone( string personName, int areaCode, int number ); bool removePhone( string personName, int areaCode, int number ); void displayPerson( string name ); void displayAreaCode( int areaCode ); void displayPeople(); private: struct Node { Person t; Node* next; }; Node *head; int numberOfPeople; Node* findPerson( string name ); }; #endif
22.225
68
0.667042
4e19aec666d252f5f2997837a28ace9291aff375
11,983
c
C
tests/pem_utils_test.c
grrtrr/aws-c-io
d4a2a8ba2f0bb27fb9fe29f6acb4b1a18820cb18
[ "Apache-2.0" ]
77
2018-11-21T12:00:44.000Z
2022-01-18T00:09:10.000Z
tests/pem_utils_test.c
grrtrr/aws-c-io
d4a2a8ba2f0bb27fb9fe29f6acb4b1a18820cb18
[ "Apache-2.0" ]
74
2018-10-20T02:13:53.000Z
2022-03-25T04:28:08.000Z
tests/pem_utils_test.c
grrtrr/aws-c-io
d4a2a8ba2f0bb27fb9fe29f6acb4b1a18820cb18
[ "Apache-2.0" ]
45
2019-02-27T21:47:20.000Z
2022-03-15T13:06:45.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/common/string.h> #include <aws/io/private/pem_utils.h> #include <aws/testing/aws_test_harness.h> static int s_check_clean_pem_result( struct aws_byte_cursor dirty_pem, struct aws_byte_cursor expected_clean_pem, struct aws_allocator *allocator) { struct aws_byte_buf pem_buf; ASSERT_SUCCESS(aws_byte_buf_init_copy_from_cursor(&pem_buf, allocator, dirty_pem)); ASSERT_SUCCESS(aws_sanitize_pem(&pem_buf, allocator)); ASSERT_TRUE(aws_byte_cursor_eq_byte_buf(&expected_clean_pem, &pem_buf)); aws_byte_buf_clean_up(&pem_buf); return AWS_OP_SUCCESS; } static int s_test_pem_sanitize_comments_around_pem_object_removed(struct aws_allocator *allocator, void *ctx) { (void)ctx; /* comments around pem object will be removed */ struct aws_byte_cursor dirty_pem = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("# comments\r\n" "-----BEGIN CERTIFICATE-----\n" "CERTIFICATES\n" "-----END CERTIFICATE-----\n" "# another comments\r\n" "-----BEGIN CERTIFICATE-----\n" "CERTIFICATES\n" "-----END CERTIFICATE-----\n" "# final comments\r\n"); struct aws_byte_cursor expected_clean_pem = AWS_BYTE_CUR_INIT_FROM_STRING_LITERAL("-----BEGIN CERTIFICATE-----\n" "CERTIFICATES\n" "-----END CERTIFICATE-----\n" "-----BEGIN CERTIFICATE-----\n" "CERTIFICATES\n" "-----END CERTIFICATE-----\n"); return s_check_clean_pem_result(dirty_pem, expected_clean_pem, allocator); } AWS_TEST_CASE(pem_sanitize_comments_around_pem_object_removed, s_test_pem_sanitize_comments_around_pem_object_removed); static int s_test_pem_sanitize_empty_file_rejected(struct aws_allocator *allocator, void *ctx) { (void)ctx; /* We don't allow empty files. */ struct aws_byte_buf pem; ASSERT_SUCCESS(aws_byte_buf_init(&pem, allocator, 512)); ASSERT_ERROR(AWS_ERROR_INVALID_ARGUMENT, aws_sanitize_pem(&pem, allocator)); aws_byte_buf_clean_up(&pem); return AWS_OP_SUCCESS; } AWS_TEST_CASE(pem_sanitize_empty_file_rejected, s_test_pem_sanitize_empty_file_rejected) AWS_TEST_CASE(pem_sanitize_wrong_format_rejected, s_test_pem_sanitize_wrong_format_rejected) static int s_test_pem_sanitize_wrong_format_rejected(struct aws_allocator *allocator, void *ctx) { (void)ctx; /* A file with the wrong format will "sanitize" to an empty PEM file, which we do not accept */ /* This is not a PEM file, it's a DER encoded binary x.509 certificate */ const uint8_t not_a_pem_src[] = { 0x30, 0x82, 0x04, 0xD3, 0x30, 0x82, 0x03, 0xBB, 0xA0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x10, 0x18, 0xDA, 0xD1, 0x9E, 0x26, 0x7D, 0xE8, 0xBB, 0x4A, 0x21, 0x58, 0xCD, 0xCC, 0x6B, 0x3B, 0x4A, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x05, 0x05, 0x00, 0x30, 0x81, 0xCA, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x17, 0x30, 0x15, 0x06, 0x03, 0x55, 0x04, 0x0A, 0x13, 0x0E, 0x56, 0x65, 0x72, 0x69, 0x53, 0x69, 0x67, 0x6E, 0x2C, 0x20, 0x49, 0x6E, 0x63, 0x2E, 0x31, 0x1F, 0x30, 0x1D, 0x06, 0x03, 0x55, 0x04, 0x0B, 0x13, 0x16, 0x56, 0x65, 0x72, 0x69, 0x53, 0x69, 0x67, 0x6E, 0x20, 0x54, 0x72, 0x75, 0x73, 0x74, 0x20, 0x4E, 0x65, 0x74, 0x77, 0x6F, 0x72, 0x6B, 0x31, 0x3A, 0x30, 0x38, 0x06, 0x03, 0x55, 0x04, 0x0B, 0x13, 0x31, 0x28, 0x63, 0x29, 0x20, 0x32, 0x30, 0x30, 0x36, 0x20, 0x56, 0x65, 0x72, 0x69, 0x53, 0x69, 0x67, 0x6E, 0x2C, 0x20, 0x49, 0x6E, 0x63, 0x2E, 0x20, 0x2D, 0x20, 0x46, 0x6F, 0x72, 0x20, 0x61, 0x75, 0x74, 0x68, 0x6F, 0x72, 0x69, 0x7A, 0x65, 0x64, 0x20, 0x75, 0x73, 0x65, 0x20, 0x6F, 0x6E, 0x6C, 0x79, 0x31, 0x45, 0x30, 0x43, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x3C, 0x56, 0x65, 0x72, 0x69, 0x53, 0x69, 0x67, 0x6E, 0x20, 0x43, 0x6C, 0x61, 0x73, 0x73, 0x20, 0x33, 0x20, 0x50, 0x75, 0x62, 0x6C, 0x69, 0x63, 0x20, 0x50, 0x72, 0x69, 0x6D, 0x61, 0x72, 0x79, 0x20, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x20, 0x41, 0x75, 0x74, 0x68, 0x6F, 0x72, 0x69, 0x74, 0x79, 0x20, 0x2D, 0x20, 0x47, 0x35, 0x30, 0x1E, 0x17, 0x0D, 0x30, 0x36, 0x31, 0x31, 0x30, 0x38, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x5A, 0x17, 0x0D, 0x33, 0x36, 0x30, 0x37, 0x31, 0x36, 0x32, 0x33, 0x35, 0x39, 0x35, 0x39, 0x5A, 0x30, 0x81, 0xCA, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x17, 0x30, 0x15, 0x06, 0x03, 0x55, 0x04, 0x0A, 0x13, 0x0E, 0x56, 0x65, 0x72, 0x69, 0x53, 0x69, 0x67, 0x6E, 0x2C, 0x20, 0x49, 0x6E, 0x63, 0x2E, 0x31, 0x1F, 0x30, 0x1D, 0x06, 0x03, 0x55, 0x04, 0x0B, 0x13, 0x16, 0x56, 0x65, 0x72, 0x69, 0x53, 0x69, 0x67, 0x6E, 0x20, 0x54, 0x72, 0x75, 0x73, 0x74, 0x20, 0x4E, 0x65, 0x74, 0x77, 0x6F, 0x72, 0x6B, 0x31, 0x3A, 0x30, 0x38, 0x06, 0x03, 0x55, 0x04, 0x0B, 0x13, 0x31, 0x28, 0x63, 0x29, 0x20, 0x32, 0x30, 0x30, 0x36, 0x20, 0x56, 0x65, 0x72, 0x69, 0x53, 0x69, 0x67, 0x6E, 0x2C, 0x20, 0x49, 0x6E, 0x63, 0x2E, 0x20, 0x2D, 0x20, 0x46, 0x6F, 0x72, 0x20, 0x61, 0x75, 0x74, 0x68, 0x6F, 0x72, 0x69, 0x7A, 0x65, 0x64, 0x20, 0x75, 0x73, 0x65, 0x20, 0x6F, 0x6E, 0x6C, 0x79, 0x31, 0x45, 0x30, 0x43, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x3C, 0x56, 0x65, 0x72, 0x69, 0x53, 0x69, 0x67, 0x6E, 0x20, 0x43, 0x6C, 0x61, 0x73, 0x73, 0x20, 0x33, 0x20, 0x50, 0x75, 0x62, 0x6C, 0x69, 0x63, 0x20, 0x50, 0x72, 0x69, 0x6D, 0x61, 0x72, 0x79, 0x20, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x20, 0x41, 0x75, 0x74, 0x68, 0x6F, 0x72, 0x69, 0x74, 0x79, 0x20, 0x2D, 0x20, 0x47, 0x35, 0x30, 0x82, 0x01, 0x22, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0F, 0x00, 0x30, 0x82, 0x01, 0x0A, 0x02, 0x82, 0x01, 0x01, 0x00, 0xAF, 0x24, 0x08, 0x08, 0x29, 0x7A, 0x35, 0x9E, 0x60, 0x0C, 0xAA, 0xE7, 0x4B, 0x3B, 0x4E, 0xDC, 0x7C, 0xBC, 0x3C, 0x45, 0x1C, 0xBB, 0x2B, 0xE0, 0xFE, 0x29, 0x02, 0xF9, 0x57, 0x08, 0xA3, 0x64, 0x85, 0x15, 0x27, 0xF5, 0xF1, 0xAD, 0xC8, 0x31, 0x89, 0x5D, 0x22, 0xE8, 0x2A, 0xAA, 0xA6, 0x42, 0xB3, 0x8F, 0xF8, 0xB9, 0x55, 0xB7, 0xB1, 0xB7, 0x4B, 0xB3, 0xFE, 0x8F, 0x7E, 0x07, 0x57, 0xEC, 0xEF, 0x43, 0xDB, 0x66, 0x62, 0x15, 0x61, 0xCF, 0x60, 0x0D, 0xA4, 0xD8, 0xDE, 0xF8, 0xE0, 0xC3, 0x62, 0x08, 0x3D, 0x54, 0x13, 0xEB, 0x49, 0xCA, 0x59, 0x54, 0x85, 0x26, 0xE5, 0x2B, 0x8F, 0x1B, 0x9F, 0xEB, 0xF5, 0xA1, 0x91, 0xC2, 0x33, 0x49, 0xD8, 0x43, 0x63, 0x6A, 0x52, 0x4B, 0xD2, 0x8F, 0xE8, 0x70, 0x51, 0x4D, 0xD1, 0x89, 0x69, 0x7B, 0xC7, 0x70, 0xF6, 0xB3, 0xDC, 0x12, 0x74, 0xDB, 0x7B, 0x5D, 0x4B, 0x56, 0xD3, 0x96, 0xBF, 0x15, 0x77, 0xA1, 0xB0, 0xF4, 0xA2, 0x25, 0xF2, 0xAF, 0x1C, 0x92, 0x67, 0x18, 0xE5, 0xF4, 0x06, 0x04, 0xEF, 0x90, 0xB9, 0xE4, 0x00, 0xE4, 0xDD, 0x3A, 0xB5, 0x19, 0xFF, 0x02, 0xBA, 0xF4, 0x3C, 0xEE, 0xE0, 0x8B, 0xEB, 0x37, 0x8B, 0xEC, 0xF4, 0xD7, 0xAC, 0xF2, 0xF6, 0xF0, 0x3D, 0xAF, 0xDD, 0x75, 0x91, 0x33, 0x19, 0x1D, 0x1C, 0x40, 0xCB, 0x74, 0x24, 0x19, 0x21, 0x93, 0xD9, 0x14, 0xFE, 0xAC, 0x2A, 0x52, 0xC7, 0x8F, 0xD5, 0x04, 0x49, 0xE4, 0x8D, 0x63, 0x47, 0x88, 0x3C, 0x69, 0x83, 0xCB, 0xFE, 0x47, 0xBD, 0x2B, 0x7E, 0x4F, 0xC5, 0x95, 0xAE, 0x0E, 0x9D, 0xD4, 0xD1, 0x43, 0xC0, 0x67, 0x73, 0xE3, 0x14, 0x08, 0x7E, 0xE5, 0x3F, 0x9F, 0x73, 0xB8, 0x33, 0x0A, 0xCF, 0x5D, 0x3F, 0x34, 0x87, 0x96, 0x8A, 0xEE, 0x53, 0xE8, 0x25, 0x15, 0x02, 0x03, 0x01, 0x00, 0x01, 0xA3, 0x81, 0xB2, 0x30, 0x81, 0xAF, 0x30, 0x0F, 0x06, 0x03, 0x55, 0x1D, 0x13, 0x01, 0x01, 0xFF, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xFF, 0x30, 0x0E, 0x06, 0x03, 0x55, 0x1D, 0x0F, 0x01, 0x01, 0xFF, 0x04, 0x04, 0x03, 0x02, 0x01, 0x06, 0x30, 0x6D, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x01, 0x0C, 0x04, 0x61, 0x30, 0x5F, 0xA1, 0x5D, 0xA0, 0x5B, 0x30, 0x59, 0x30, 0x57, 0x30, 0x55, 0x16, 0x09, 0x69, 0x6D, 0x61, 0x67, 0x65, 0x2F, 0x67, 0x69, 0x66, 0x30, 0x21, 0x30, 0x1F, 0x30, 0x07, 0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1A, 0x04, 0x14, 0x8F, 0xE5, 0xD3, 0x1A, 0x86, 0xAC, 0x8D, 0x8E, 0x6B, 0xC3, 0xCF, 0x80, 0x6A, 0xD4, 0x48, 0x18, 0x2C, 0x7B, 0x19, 0x2E, 0x30, 0x25, 0x16, 0x23, 0x68, 0x74, 0x74, 0x70, 0x3A, 0x2F, 0x2F, 0x6C, 0x6F, 0x67, 0x6F, 0x2E, 0x76, 0x65, 0x72, 0x69, 0x73, 0x69, 0x67, 0x6E, 0x2E, 0x63, 0x6F, 0x6D, 0x2F, 0x76, 0x73, 0x6C, 0x6F, 0x67, 0x6F, 0x2E, 0x67, 0x69, 0x66, 0x30, 0x1D, 0x06, 0x03, 0x55, 0x1D, 0x0E, 0x04, 0x16, 0x04, 0x14, 0x7F, 0xD3, 0x65, 0xA7, 0xC2, 0xDD, 0xEC, 0xBB, 0xF0, 0x30, 0x09, 0xF3, 0x43, 0x39, 0xFA, 0x02, 0xAF, 0x33, 0x31, 0x33, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x05, 0x05, 0x00, 0x03, 0x82, 0x01, 0x01, 0x00, 0x93, 0x24, 0x4A, 0x30, 0x5F, 0x62, 0xCF, 0xD8, 0x1A, 0x98, 0x2F, 0x3D, 0xEA, 0xDC, 0x99, 0x2D, 0xBD, 0x77, 0xF6, 0xA5, 0x79, 0x22, 0x38, 0xEC, 0xC4, 0xA7, 0xA0, 0x78, 0x12, 0xAD, 0x62, 0x0E, 0x45, 0x70, 0x64, 0xC5, 0xE7, 0x97, 0x66, 0x2D, 0x98, 0x09, 0x7E, 0x5F, 0xAF, 0xD6, 0xCC, 0x28, 0x65, 0xF2, 0x01, 0xAA, 0x08, 0x1A, 0x47, 0xDE, 0xF9, 0xF9, 0x7C, 0x92, 0x5A, 0x08, 0x69, 0x20, 0x0D, 0xD9, 0x3E, 0x6D, 0x6E, 0x3C, 0x0D, 0x6E, 0xD8, 0xE6, 0x06, 0x91, 0x40, 0x18, 0xB9, 0xF8, 0xC1, 0xED, 0xDF, 0xDB, 0x41, 0xAA, 0xE0, 0x96, 0x20, 0xC9, 0xCD, 0x64, 0x15, 0x38, 0x81, 0xC9, 0x94, 0xEE, 0xA2, 0x84, 0x29, 0x0B, 0x13, 0x6F, 0x8E, 0xDB, 0x0C, 0xDD, 0x25, 0x02, 0xDB, 0xA4, 0x8B, 0x19, 0x44, 0xD2, 0x41, 0x7A, 0x05, 0x69, 0x4A, 0x58, 0x4F, 0x60, 0xCA, 0x7E, 0x82, 0x6A, 0x0B, 0x02, 0xAA, 0x25, 0x17, 0x39, 0xB5, 0xDB, 0x7F, 0xE7, 0x84, 0x65, 0x2A, 0x95, 0x8A, 0xBD, 0x86, 0xDE, 0x5E, 0x81, 0x16, 0x83, 0x2D, 0x10, 0xCC, 0xDE, 0xFD, 0xA8, 0x82, 0x2A, 0x6D, 0x28, 0x1F, 0x0D, 0x0B, 0xC4, 0xE5, 0xE7, 0x1A, 0x26, 0x19, 0xE1, 0xF4, 0x11, 0x6F, 0x10, 0xB5, 0x95, 0xFC, 0xE7, 0x42, 0x05, 0x32, 0xDB, 0xCE, 0x9D, 0x51, 0x5E, 0x28, 0xB6, 0x9E, 0x85, 0xD3, 0x5B, 0xEF, 0xA5, 0x7D, 0x45, 0x40, 0x72, 0x8E, 0xB7, 0x0E, 0x6B, 0x0E, 0x06, 0xFB, 0x33, 0x35, 0x48, 0x71, 0xB8, 0x9D, 0x27, 0x8B, 0xC4, 0x65, 0x5F, 0x0D, 0x86, 0x76, 0x9C, 0x44, 0x7A, 0xF6, 0x95, 0x5C, 0xF6, 0x5D, 0x32, 0x08, 0x33, 0xA4, 0x54, 0xB6, 0x18, 0x3F, 0x68, 0x5C, 0xF2, 0x42, 0x4A, 0x85, 0x38, 0x54, 0x83, 0x5F, 0xD1, 0xE8, 0x2C, 0xF2, 0xAC, 0x11, 0xD6, 0xA8, 0xED, 0x63, 0x6A}; struct aws_byte_cursor not_a_pem_cursor = aws_byte_cursor_from_array(not_a_pem_src, sizeof(not_a_pem_src)); struct aws_byte_buf not_a_pem; ASSERT_SUCCESS(aws_byte_buf_init_copy_from_cursor(&not_a_pem, allocator, not_a_pem_cursor)); ASSERT_ERROR(AWS_ERROR_INVALID_ARGUMENT, aws_sanitize_pem(&not_a_pem, allocator)); aws_byte_buf_clean_up(&not_a_pem); return AWS_OP_SUCCESS; }
82.075342
119
0.602437
eccece153c5e70dc876a0352961498a5c9425ef3
1,594
c
C
feladatok_megoldas/4_Programozasi_tetelek/4.5_Rendezes/example_4.5.5.c
pekmil/CTutorial
e5d8e1b2d7cbab98669757219dfa212267d5f14a
[ "MIT" ]
null
null
null
feladatok_megoldas/4_Programozasi_tetelek/4.5_Rendezes/example_4.5.5.c
pekmil/CTutorial
e5d8e1b2d7cbab98669757219dfa212267d5f14a
[ "MIT" ]
null
null
null
feladatok_megoldas/4_Programozasi_tetelek/4.5_Rendezes/example_4.5.5.c
pekmil/CTutorial
e5d8e1b2d7cbab98669757219dfa212267d5f14a
[ "MIT" ]
null
null
null
/******************************************************************************************************************** * 4.5.5 Feladat(!) * * Olvass be egy tízelemű tömböt * * Tárold el maxden elemhez a prímtényezős felbontásában szereplő legkisebb prímszámot * * Rendezd a beolvasott tömböt a prímtényezős felbontásban szereplő legkisebb prímszám szerinti csökkenő sorrendbe * ********************************************************************************************************************/ #include <stdio.h> #define N 10 int main() { int tomb[N]; int i, j; printf("Kerem a tomb elemeit:\n"); for (i=0; i<N; i++) { scanf("%d", &tomb[i]); } int primek[N]; for (i=0; i<N; i++) { if (tomb[i]<=1) { primek[i]=tomb[i]; } else { int oszto=2; while (tomb[i]%oszto!=0) oszto++; primek[i]=oszto; } } printf("A legkisebb primteyezok:\n"); for (i=0; i<N; i++) { printf("%d ", primek[i]); } printf("\n"); int max_idx; int csere; for (i=0; i<N-1; i++) { max_idx=i; for (j=i+1; j<N; j++) { if (primek[j]>primek[max_idx]) max_idx=j; } if (max_idx!=i) { csere=tomb[i]; tomb[i]=tomb[max_idx]; tomb[max_idx]=csere; csere=primek[i]; primek[i]=primek[max_idx]; primek[max_idx]=csere; } } printf("A rendezett tomb:\n"); for (i=0; i<N; i++) { printf("%d ", tomb[i]); } printf("\n"); return 0; }
22.771429
118
0.417189
bd0fae7a47538736b220aab09569143406ed7c4d
18,925
h
C
moveit_planners/pilz_industrial_motion_planner/test/test_utils.h
predystopic-dev/moveit2
42afeea561949b1af197655c1cbb63b851e7dd8d
[ "BSD-3-Clause" ]
null
null
null
moveit_planners/pilz_industrial_motion_planner/test/test_utils.h
predystopic-dev/moveit2
42afeea561949b1af197655c1cbb63b851e7dd8d
[ "BSD-3-Clause" ]
null
null
null
moveit_planners/pilz_industrial_motion_planner/test/test_utils.h
predystopic-dev/moveit2
42afeea561949b1af197655c1cbb63b851e7dd8d
[ "BSD-3-Clause" ]
null
null
null
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2018 Pilz GmbH & Co. KG * 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 Pilz GmbH & Co. KG nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ #pragma once #include <gtest/gtest.h> #ifndef INSTANTIATE_TEST_SUITE_P // prior to gtest 1.10 #define INSTANTIATE_TEST_SUITE_P(...) INSTANTIATE_TEST_CASE_P(__VA_ARGS__) #endif #ifndef TYPED_TEST_SUITE // prior to gtest 1.10 #define TYPED_TEST_SUITE(...) TYPED_TEST_CASE(__VA_ARGS__) #endif #include "moveit_msgs/MotionSequenceRequest.h" #include "pilz_industrial_motion_planner/limits_container.h" #include "pilz_industrial_motion_planner/trajectory_blend_request.h" #include "pilz_industrial_motion_planner/trajectory_blend_response.h" #include "pilz_industrial_motion_planner/trajectory_generator.h" #include <boost/core/demangle.hpp> #include <math.h> #include <moveit/kinematic_constraints/utils.h> #include <moveit/planning_interface/planning_interface.h> #include <moveit/robot_trajectory/robot_trajectory.h> #include <moveit_msgs/Constraints.h> #include <moveit_msgs/MoveGroupAction.h> #include <ros/console.h> #include <sensor_msgs/JointState.h> #include <string> #include <tf2/LinearMath/Quaternion.h> #include <tf2/convert.h> #if __has_include(<tf2_geometry_msgs/tf2_geometry_msgs.hpp>) #include <tf2_geometry_msgs/tf2_geometry_msgs.hpp> #else #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #endif #include <utility> namespace testutils { const std::string JOINT_NAME_PREFIX("prbt_joint_"); static constexpr int32_t DEFAULT_SERVICE_TIMEOUT(10); static constexpr double DEFAULT_ACCELERATION_EQUALITY_TOLERANCE{ 1e-6 }; static constexpr double DEFAULT_ROTATION_AXIS_EQUALITY_TOLERANCE{ 1e-8 }; /** * @brief Convert degree to rad. */ inline static constexpr double deg2Rad(double angle) { return (angle / 180.0) * M_PI; } inline std::string getJointName(size_t joint_number, const std::string& joint_prefix) { return joint_prefix + std::to_string(joint_number); } /** * @brief Create limits for tests to avoid the need to get the limits from the * parameter server */ pilz_industrial_motion_planner::JointLimitsContainer createFakeLimits(const std::vector<std::string>& joint_names); inline std::string demangel(char const* name) { return boost::core::demangle(name); } //******************************************** // Motion plan requests //******************************************** inline sensor_msgs::JointState generateJointState(const std::vector<double>& pos, const std::vector<double>& vel, const std::string& joint_prefix = testutils::JOINT_NAME_PREFIX) { sensor_msgs::JointState state; auto posit = pos.cbegin(); size_t i = 0; while (posit != pos.cend()) { state.name.push_back(testutils::getJointName(i + 1, joint_prefix)); state.position.push_back(*posit); i++; posit++; } for (const auto& one_vel : vel) { state.velocity.push_back(one_vel); } return state; } inline sensor_msgs::JointState generateJointState(const std::vector<double>& pos, const std::string& joint_prefix = testutils::JOINT_NAME_PREFIX) { return generateJointState(pos, std::vector<double>(), joint_prefix); } inline moveit_msgs::Constraints generateJointConstraint(const std::vector<double>& pos_list, const std::string& joint_prefix = testutils::JOINT_NAME_PREFIX) { moveit_msgs::Constraints gc; auto pos_it = pos_list.begin(); for (size_t i = 0; i < pos_list.size(); ++i) { moveit_msgs::JointConstraint jc; jc.joint_name = testutils::getJointName(i + 1, joint_prefix); jc.position = *pos_it; gc.joint_constraints.push_back(jc); ++pos_it; } return gc; } /** * @brief Determines the goal position from the given request. * TRUE if successful, FALSE otherwise. */ bool getExpectedGoalPose(const moveit::core::RobotModelConstPtr& robot_model, const planning_interface::MotionPlanRequest& req, std::string& link_name, Eigen::Isometry3d& goal_pose_expect); /** * @brief create a dummy motion plan request with zero start state * No goal constraint is given. * @param robot_model * @param planning_group * @param req */ void createDummyRequest(const moveit::core::RobotModelConstPtr& robot_model, const std::string& planning_group, planning_interface::MotionPlanRequest& req); void createPTPRequest(const std::string& planning_group, const moveit::core::RobotState& start_state, const moveit::core::RobotState& goal_state, planning_interface::MotionPlanRequest& req); /** * @brief check if the goal given in joint space is reached * Only the last point in the trajectory is veryfied. * @param trajectory: generated trajectory * @param goal: goal in joint space * @param joint_position_tolerance * @param joint_velocity_tolerance * @return true if satisfied */ bool isGoalReached(const trajectory_msgs::JointTrajectory& trajectory, const std::vector<moveit_msgs::JointConstraint>& goal, const double joint_position_tolerance, const double joint_velocity_tolerance = 1.0e-6); /** * @brief check if the goal given in cartesian space is reached * Only the last point in the trajectory is veryfied. * @param robot_model * @param trajectory * @param req * @param matrix_norm_tolerance: used to compare the transformation matrix * @param joint_velocity_tolerance * @return */ bool isGoalReached(const robot_model::RobotModelConstPtr& robot_model, const trajectory_msgs::JointTrajectory& trajectory, const planning_interface::MotionPlanRequest& req, const double pos_tolerance, const double orientation_tolerance); bool isGoalReached(const moveit::core::RobotModelConstPtr& robot_model, const trajectory_msgs::JointTrajectory& trajectory, const planning_interface::MotionPlanRequest& req, const double tolerance); /** * @brief Check that given trajectory is straight line. */ bool checkCartesianLinearity(const robot_model::RobotModelConstPtr& robot_model, const trajectory_msgs::JointTrajectory& trajectory, const planning_interface::MotionPlanRequest& req, const double translation_norm_tolerance, const double rot_axis_norm_tolerance, const double rot_angle_tolerance = 10e-5); /** * @brief check SLERP. The orientation should rotate around the same axis * linearly. * @param start_pose * @param goal_pose * @param wp_pose * @param rot_axis_norm_tolerance * @return */ bool checkSLERP(const Eigen::Isometry3d& start_pose, const Eigen::Isometry3d& goal_pose, const Eigen::Isometry3d& wp_pose, const double rot_axis_norm_tolerance, const double rot_angle_tolerance = 10e-5); /** * @brief get the waypoint index from time from start * @param trajectory * @param time_from_start * @return */ inline int getWayPointIndex(const robot_trajectory::RobotTrajectoryPtr& trajectory, const double time_from_start) { int index_before, index_after; double blend; trajectory->findWayPointIndicesForDurationAfterStart(time_from_start, index_before, index_after, blend); return blend > 0.5 ? index_after : index_before; } /** * @brief check joint trajectory of consistency, position, velocity and * acceleration limits * @param trajectory * @param joint_limits * @return */ bool checkJointTrajectory(const trajectory_msgs::JointTrajectory& trajectory, const pilz_industrial_motion_planner::JointLimitsContainer& joint_limits); /** * @brief Checks that every waypoint in the trajectory has a non-zero duration * between itself and its predecessor * * Usage in tests: * @code * EXPECT_TRUE(HasStrictlyIncreasingTime(trajectory)); * @endcode */ ::testing::AssertionResult hasStrictlyIncreasingTime(const robot_trajectory::RobotTrajectoryPtr& trajectory); /** * @brief check if the sizes of the joint position/veloicty/acceleration are * correct * @param trajectory * @return */ bool isTrajectoryConsistent(const trajectory_msgs::JointTrajectory& trajectory); /** * @brief is Position Bounded * @param trajectory * @param joint_limits * @return */ bool isPositionBounded(const trajectory_msgs::JointTrajectory& trajectory, const pilz_industrial_motion_planner::JointLimitsContainer& joint_limits); /** * @brief is Velocity Bounded * @param trajectory * @param joint_limits * @return */ bool isVelocityBounded(const trajectory_msgs::JointTrajectory& trajectory, const pilz_industrial_motion_planner::JointLimitsContainer& joint_limits); /** * @brief is Acceleration Bounded * @param trajectory * @param joint_limits * @return */ bool isAccelerationBounded(const trajectory_msgs::JointTrajectory& trajectory, const pilz_industrial_motion_planner::JointLimitsContainer& joint_limits); /** * @brief compute the tcp pose from joint values * @param robot_model * @param link_name * @param joint_values * @param pose * @param joint_prefix Prefix of the joint names * @return false if forward kinematics failed */ bool toTCPPose(const moveit::core::RobotModelConstPtr& robot_model, const std::string& link_name, const std::vector<double>& joint_values, geometry_msgs::Pose& pose, const std::string& joint_prefix = testutils::JOINT_NAME_PREFIX); /** * @brief computeLinkFK * @param robot_model * @param link_name * @param joint_state * @param pose * @return */ bool computeLinkFK(const robot_model::RobotModelConstPtr& robot_model, const std::string& link_name, const std::map<std::string, double>& joint_state, Eigen::Isometry3d& pose); /** * @brief checkOriginalTrajectoryAfterBlending * @param blend_res * @param traj_1_res * @param traj_2_res * @param time_tolerance * @return */ bool checkOriginalTrajectoryAfterBlending(const pilz_industrial_motion_planner::TrajectoryBlendRequest& req, const pilz_industrial_motion_planner::TrajectoryBlendResponse& res, const double time_tolerance); /** * @brief check the blending result, if the joint space continuity is fulfilled * @param res: trajectory blending response, contains three trajectories. * Between these three trajectories should be continuous. * @return true if joint position/velocity is continuous. joint acceleration can * have jumps. */ bool checkBlendingJointSpaceContinuity(const pilz_industrial_motion_planner::TrajectoryBlendResponse& res, double joint_velocity_tolerance, double joint_accleration_tolerance); bool checkBlendingCartSpaceContinuity(const pilz_industrial_motion_planner::TrajectoryBlendRequest& req, const pilz_industrial_motion_planner::TrajectoryBlendResponse& res, const pilz_industrial_motion_planner::LimitsContainer& planner_limits); /** * @brief Checks if all points of the blending trajectory lie within the * blending radius. */ bool checkThatPointsInRadius(const std::string& link_name, const double& r, Eigen::Isometry3d& circ_pose, const pilz_industrial_motion_planner::TrajectoryBlendResponse& res); /** * @brief compute Cartesian velocity * @param pose_1 * @param pose_2 * @param duration * @param v * @param w */ void computeCartVelocity(const Eigen::Isometry3d& pose_1, const Eigen::Isometry3d& pose_2, double duration, Eigen::Vector3d& v, Eigen::Vector3d& w); /** * @brief Returns an initial joint state and two poses which * can be used to perform a Lin-Lin movement. * * @param frame_id * @param initialJointState As cartesian position: (0.3, 0, 0.65, 0, 0, 0) * @param p1 (0.05, 0, 0.65, 0, 0, 0) * @param p2 (0.05, 0.4, 0.65, 0, 0, 0) */ void getLinLinPosesWithoutOriChange(const std::string& frame_id, sensor_msgs::JointState& initialJointState, geometry_msgs::PoseStamped& p1, geometry_msgs::PoseStamped& p2); void getOriChange(Eigen::Matrix3d& ori1, Eigen::Matrix3d& ori2); void createFakeCartTraj(const robot_trajectory::RobotTrajectoryPtr& traj, const std::string& link_name, moveit_msgs::RobotTrajectory& fake_traj); inline geometry_msgs::Quaternion fromEuler(double a, double b, double c) { tf2::Vector3 qvz(0., 0., 1.); tf2::Vector3 qvy(0., 1., 0.); tf2::Quaternion q1(qvz, a); q1 = q1 * tf2::Quaternion(qvy, b); q1 = q1 * tf2::Quaternion(qvz, c); return tf2::toMsg(q1); } /** * @brief Test data for blending, which contains three joint position vectors of * three robot state. */ struct BlendTestData { std::vector<double> start_position; std::vector<double> mid_position; std::vector<double> end_position; }; /** * @brief fetch test datasets from parameter server * @param nh * @return */ bool getBlendTestData(const ros::NodeHandle& nh, const size_t& dataset_num, const std::string& name_prefix, std::vector<BlendTestData>& datasets); /** * @brief check the blending result of lin-lin * @param lin_res_1 * @param lin_res_2 * @param blend_req * @param blend_res * @param checkAcceleration */ bool checkBlendResult(const pilz_industrial_motion_planner::TrajectoryBlendRequest& blend_req, const pilz_industrial_motion_planner::TrajectoryBlendResponse& blend_res, const pilz_industrial_motion_planner::LimitsContainer& limits, double joint_velocity_tolerance, double joint_acceleration_tolerance, double cartesian_velocity_tolerance, double cartesian_angular_velocity_tolerance); /** * @brief generate two LIN trajectories from test data set * @param data: contains joint poisitons of start/mid/end states * @param sampling_time_1: sampling time for first LIN * @param sampling_time_2: sampling time for second LIN * @param[out] res_lin_1: result of the first LIN motion planning * @param[out] res_lin_2: result of the second LIN motion planning * @param[out] dis_lin_1: translational distance of the first LIN * @param[out] dis_lin_2: translational distance of the second LIN * @return true if succeed */ bool generateTrajFromBlendTestData(const planning_scene::PlanningSceneConstPtr& scene, const std::shared_ptr<pilz_industrial_motion_planner::TrajectoryGenerator>& tg, const std::string& group_name, const std::string& link_name, const BlendTestData& data, const double& sampling_time_1, const double& sampling_time_2, planning_interface::MotionPlanResponse& res_lin_1, planning_interface::MotionPlanResponse& res_lin_2, double& dis_lin_1, double& dis_lin_2); void generateRequestMsgFromBlendTestData(const moveit::core::RobotModelConstPtr& robot_model, const BlendTestData& data, const std::string& planner_id, const std::string& group_name, const std::string& link_name, moveit_msgs::MotionSequenceRequest& req_list); void checkRobotModel(const moveit::core::RobotModelConstPtr& robot_model, const std::string& group_name, const std::string& link_name); /** @brief Check that a given vector of accelerations represents a trapezoid * velocity profile * @param acc_tol: tolerance for comparing acceleration values */ ::testing::AssertionResult hasTrapezoidVelocity(std::vector<double> accelerations, const double acc_tol); /** * @brief Check that the translational path of a given trajectory has a * trapezoid velocity profile * @param acc_tol: tolerance for comparing acceleration values */ ::testing::AssertionResult checkCartesianTranslationalPath(const robot_trajectory::RobotTrajectoryConstPtr& trajectory, const std::string& link_name, const double acc_tol = DEFAULT_ACCELERATION_EQUALITY_TOLERANCE); /** * @brief Check that the rotational path of a given trajectory is a quaternion * slerp. * @param rot_axis_tol: tolerance for comparing rotation axes (in the L2 norm) * @param acc_tol: tolerance for comparing angular acceleration values */ ::testing::AssertionResult checkCartesianRotationalPath(const robot_trajectory::RobotTrajectoryConstPtr& trajectory, const std::string& link_name, const double rot_axis_tol = DEFAULT_ROTATION_AXIS_EQUALITY_TOLERANCE, const double acc_tol = DEFAULT_ACCELERATION_EQUALITY_TOLERANCE); inline bool isMonotonouslyDecreasing(const std::vector<double>& vec, const double& tol) { return std::is_sorted(vec.begin(), vec.end(), [tol](double a, double b) { return !(std::abs(a - b) < tol || a < b); // true -> a is ordered before b -> list is not sorted }); } } // namespace testutils
38.86037
120
0.705258
08b58c3b4f957e84c067f625d4c1a064c3e39a36
1,656
h
C
src/burstmath.h
spebern/cpp-burst-pool-node
0cbf0759cd166ef7c3f850059180d3a8ceb158eb
[ "MIT" ]
null
null
null
src/burstmath.h
spebern/cpp-burst-pool-node
0cbf0759cd166ef7c3f850059180d3a8ceb158eb
[ "MIT" ]
null
null
null
src/burstmath.h
spebern/cpp-burst-pool-node
0cbf0759cd166ef7c3f850059180d3a8ceb158eb
[ "MIT" ]
2
2018-09-20T16:11:14.000Z
2018-12-12T08:46:30.000Z
#ifdef __cplusplus extern "C" { #endif #include <stdint.h> #include <stdbool.h> uint32_t calculate_scoop(const uint64_t height, const uint8_t *gensig); void calculate_deadlines_sse4( bool poc2, uint64_t base_target1, uint64_t base_target2, uint64_t base_target3, uint64_t base_target4, uint32_t scoop_nr1, uint32_t scoop_nr2, uint32_t scoop_nr3, uint32_t scoop_nr4, uint8_t *gensig1, uint8_t *gensig2, uint8_t *gensig3, uint8_t *gensig4, uint64_t addr1, uint64_t addr2, uint64_t addr3, uint64_t addr4, uint64_t nonce1, uint64_t nonce2, uint64_t nonce3, uint64_t nonce4, uint64_t deadlines[4]); void calculate_deadlines_avx2( bool poc2, uint64_t base_target1, uint64_t base_target2, uint64_t base_target3, uint64_t base_target4, uint64_t base_target5, uint64_t base_target6, uint64_t base_target7, uint64_t base_target8, uint32_t scoop_nr1, uint32_t scoop_nr2, uint32_t scoop_nr3, uint32_t scoop_nr4, uint32_t scoop_nr5, uint32_t scoop_nr6, uint32_t scoop_nr7, uint32_t scoop_nr8, uint8_t *gensig1, uint8_t *gensig2, uint8_t *gensig3, uint8_t *gensig4, uint8_t *gensig5, uint8_t *gensig6, uint8_t *gensig7, uint8_t *gensig8, uint64_t addr1, uint64_t addr2, uint64_t addr3, uint64_t addr4, uint64_t addr5, uint64_t addr6, uint64_t addr7, uint64_t addr8, uint64_t nonce1, uint64_t nonce2, uint64_t nonce3, uint64_t nonce4, uint64_t nonce5, uint64_t nonce6, uint64_t nonce7, uint64_t nonce8, uint64_t deadlines[8]); #ifdef __cplusplus } #endif
32.470588
101
0.713768
2645f73304177b4d5810752b3b6008e0e636f5b2
418
h
C
bsp/gd32vf103v-eval/libraries/n22/drivers/n22_tmr.h
Tigerots/rt-thread
c95987e75772ebc6a6fdd0c19d12001aef810cb2
[ "Apache-2.0" ]
7,482
2015-01-01T09:23:08.000Z
2022-03-31T19:34:05.000Z
bsp/gd32vf103v-eval/libraries/n22/drivers/n22_tmr.h
Tigerots/rt-thread
c95987e75772ebc6a6fdd0c19d12001aef810cb2
[ "Apache-2.0" ]
2,543
2015-01-09T02:01:34.000Z
2022-03-31T23:10:14.000Z
bsp/gd32vf103v-eval/libraries/n22/drivers/n22_tmr.h
Tigerots/rt-thread
c95987e75772ebc6a6fdd0c19d12001aef810cb2
[ "Apache-2.0" ]
4,645
2015-01-06T07:05:31.000Z
2022-03-31T18:21:50.000Z
// See LICENSE file for licence details #ifndef N22_TMR_H #define N22_TMR_H #define TMR_MSIP 0xFFC #define TMR_MSIP_size 0x4 #define TMR_MTIMECMP 0x8 #define TMR_MTIMECMP_size 0x8 #define TMR_MTIME 0x0 #define TMR_MTIME_size 0x8 #define TMR_CTRL_ADDR 0xd1000000 #define TMR_REG(offset) _REG32(TMR_CTRL_ADDR, offset) #define TMR_FREQ ((uint32_t)SystemCoreClock/4) //units HZ #endif
23.222222
70
0.748804
237194b47c181b1e842c7384d1379510f91dd6aa
3,237
c
C
utils/wav2pcm.c
spxnndl/wav-file
1fb4f1a1cbc21e35830bab191c8895f3a493b1a6
[ "MIT" ]
null
null
null
utils/wav2pcm.c
spxnndl/wav-file
1fb4f1a1cbc21e35830bab191c8895f3a493b1a6
[ "MIT" ]
null
null
null
utils/wav2pcm.c
spxnndl/wav-file
1fb4f1a1cbc21e35830bab191c8895f3a493b1a6
[ "MIT" ]
null
null
null
#include "wav_file.h" #include <errno.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> static const char* wav_file = NULL; static const char* pcm_file = NULL; static SampleFormat sample_format = kSampleFormatInvalid; static void print_help(const char* program) { printf("Usage: %s [options]\n", program); printf(" -h, --help show this help message and exit\n"); printf(" -i WAV_FILE wav file\n"); printf(" -o PCM_FILE pcm file\n"); printf(" -f SAMPLE_FORMAT sample format [i16|f32], default the same as wav file\n"); } int main(int argc, const char* argv[]) { if (argc < 2) { print_help(argv[0]); return -1; } for (int i = 1; i < argc; ++i) { if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) { print_help(argv[0]); return 0; } else if (strcmp(argv[i], "-i") == 0) { wav_file = argv[++i]; } else if (strcmp(argv[i], "-o") == 0) { pcm_file = argv[++i]; } else if (strcmp(argv[i], "-f") == 0) { const char* format = argv[++i]; if (format != NULL) { if (strcmp(format, "i16") == 0) { sample_format = kSampleFormatI16; } else if (strcmp(format, "f32") == 0) { sample_format = kSampleFormatF32; } else { printf("invalid sample format %s\n\n", format); return -1; } } } else { printf("unknown option %s\n\n", argv[i]); return -1; } } if (wav_file == NULL || pcm_file == NULL) { printf("both wav file pcm file are required\n"); return -1; } if (access(wav_file, R_OK)) { printf("read wav file %s failed (%s)\n", wav_file, strerror(errno)); return -1; } WavReader* reader = wav_reader_open(wav_file); if (reader == NULL) { printf("open wav file %s failed\n", wav_file); return -1; } FILE* fp_pcm = fopen(pcm_file, "wb"); if (fp_pcm == NULL) { printf("create pcm file %s failed (%s)\n", pcm_file, strerror(errno)); wav_reader_close(reader); return -1; } int num_channels = wav_reader_get_num_channels(reader); int sample_rate = wav_reader_get_sample_rate(reader); if (sample_format == kSampleFormatInvalid) { sample_format = wav_reader_get_sample_format(reader); } int num_samples = sample_rate / 10; int block_align = num_channels * sample_format_get_bytes_per_sample(sample_format); char* sample_buf = (char*)malloc(num_samples * block_align); while (1) { int ret = 0; if (sample_format == kSampleFormatI16) { ret = wav_reader_read_i16(reader, num_samples, (int16_t*)sample_buf); } else { ret = wav_reader_read_f32(reader, num_samples, (float*)sample_buf); } if (ret > 0) { fwrite(sample_buf, block_align, ret, fp_pcm); } if (ret < num_samples) { break; } } fclose(fp_pcm); wav_reader_close(reader); return 0; }
29.162162
94
0.539697
23be2d446cf129143ecad3df2458033cc4fc14ba
65
h
C
src/keyboard.h
sporeball/nn
fb894706521db9d44135817ba21e9922e370d1e5
[ "MIT" ]
2
2022-01-28T06:52:15.000Z
2022-01-28T22:19:36.000Z
src/keyboard.h
sporeball/nn
fb894706521db9d44135817ba21e9922e370d1e5
[ "MIT" ]
null
null
null
src/keyboard.h
sporeball/nn
fb894706521db9d44135817ba21e9922e370d1e5
[ "MIT" ]
null
null
null
#ifndef KEYBOARD_H #define KEYBOARD_H void kb_handle(); #endif
9.285714
18
0.769231
1ebdf2d9b2b3107e135c958203e34c2dcbceb377
1,147
h
C
src/MassHandler.h
BR903/percolator
2d9315699cf3309421b83c4c21ce8275ede87089
[ "Apache-2.0" ]
71
2015-03-30T17:22:52.000Z
2022-01-01T14:19:23.000Z
src/MassHandler.h
BR903/percolator
2d9315699cf3309421b83c4c21ce8275ede87089
[ "Apache-2.0" ]
190
2015-01-27T16:18:58.000Z
2022-03-31T16:49:58.000Z
src/MassHandler.h
BR903/percolator
2d9315699cf3309421b83c4c21ce8275ede87089
[ "Apache-2.0" ]
45
2015-04-13T13:42:35.000Z
2021-12-17T08:26:21.000Z
/******************************************************************************* Copyright 2006-2012 Lukas Käll <lukas.kall@scilifelab.se> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *******************************************************************************/ #ifndef MASSHANDLER_H_ #define MASSHANDLER_H_ #include<string> using namespace std; class MassHandler { public: MassHandler(); virtual ~MassHandler(); static void setMonoisotopicMass(bool mi) { monoisotopic = mi; } static double massDiff(double observedMass, double calculatedMass, unsigned int charge); static bool monoisotopic; }; #endif /*MASSHANDLER_H_*/
32.771429
92
0.653008
14607bef1396cc435369e89efe2f786e4817ef9a
1,504
h
C
BasiliskII/src/Windows/cdenable/cache.h
jvernet/macemu
c616a0dae0f451fc15016765c896175fae3f46cf
[ "Intel", "X11" ]
940
2015-01-04T12:20:10.000Z
2022-03-29T12:35:27.000Z
BasiliskII/src/Windows/cdenable/cache.h
Seanpm2001-virtual-machines/macemu
c616a0dae0f451fc15016765c896175fae3f46cf
[ "Intel", "X11" ]
163
2015-02-10T09:08:10.000Z
2022-03-13T05:48:10.000Z
BasiliskII/src/Windows/cdenable/cache.h
Seanpm2001-virtual-machines/macemu
c616a0dae0f451fc15016765c896175fae3f46cf
[ "Intel", "X11" ]
188
2015-01-07T19:46:11.000Z
2022-03-26T19:06:00.000Z
/* * cache.cpp - simple floppy/cd cache for Win32 * * Basilisk II (C) 1997-2008 Christian Bauer * * Windows platform specific code copyright (C) Lauri Pesonen * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifdef __cplusplus extern "C" { #endif #ifndef _CACHE_H_ #define _CACHE_H_ #define NBLOCKS 1000 typedef struct { int inited; int res_count; int sector_size; char *blocks; int *block; DWORD *LRU; } cachetype; void cache_init( cachetype *cptr ); void cache_clear( cachetype *cptr ); void cache_final( cachetype *cptr ); int cache_get( cachetype *cptr, int block, char *buf ); void cache_put( cachetype *cptr, int block, char *buf, int ss ); void cache_remove( cachetype *cptr, int block, int ss ); #endif #ifdef __cplusplus } // extern "C" #endif
29.490196
78
0.702793
e7e2a8ad2a8d3d6192a499fb40967c425e6904bc
2,544
h
C
smbprovider/id_map.h
ascii33/platform2
b78891020724e9ff26b11ca89c2a53f949e99748
[ "BSD-3-Clause" ]
null
null
null
smbprovider/id_map.h
ascii33/platform2
b78891020724e9ff26b11ca89c2a53f949e99748
[ "BSD-3-Clause" ]
null
null
null
smbprovider/id_map.h
ascii33/platform2
b78891020724e9ff26b11ca89c2a53f949e99748
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2018 The Chromium OS 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 SMBPROVIDER_ID_MAP_H_ #define SMBPROVIDER_ID_MAP_H_ #include <algorithm> #include <stack> #include <unordered_map> #include <utility> #include <base/check_op.h> #include <base/logging.h> namespace smbprovider { // Class that maps an int32_t ID to another type. Each new ID is not currently // in use, but IDs can be reused after that item is removed from the map. // Primarily used for handing out pseudo file descriptors. template <typename T> class IdMap { public: using MapType = std::unordered_map<int32_t, T>; explicit IdMap(int initial_value) : initial_id_(initial_value), next_unused_id_(initial_value) {} IdMap(const IdMap&) = delete; IdMap& operator=(const IdMap&) = delete; ~IdMap() = default; int32_t Insert(T value) { const int32_t next_id = GetNextId(); DCHECK_EQ(0, ids_.count(next_id)); ids_.emplace(next_id, std::move(value)); return next_id; } typename MapType::const_iterator Find(int32_t id) const { return ids_.find(id); } typename MapType::iterator Find(int32_t id) { return ids_.find(id); } const T& At(int32_t id) const { return ids_.at(id); } bool Contains(int32_t id) const { return ids_.count(id) > 0; } bool Remove(int32_t id) { // If the id was being used add to the free list to be reused. if (ids_.erase(id) > 0) { free_ids_.push(id); return true; } return false; } void Reset() { ids_.clear(); // Empty out |free_ids_|. free_ids_ = {}; next_unused_id_ = initial_id_; } size_t Count() const { return ids_.size(); } bool Empty() const { return ids_.empty(); } typename MapType::const_iterator Begin() const { return ids_.begin(); } typename MapType::iterator Begin() { return ids_.begin(); } typename MapType::const_iterator End() const { return ids_.end(); } typename MapType::iterator End() { return ids_.end(); } private: // Returns the next ID and updates the internal state to ensure that // an ID that is already in use is not returned. int32_t GetNextId() { if (!free_ids_.empty()) { int32_t next_id = free_ids_.top(); free_ids_.pop(); return next_id; } return next_unused_id_++; } MapType ids_; std::stack<int32_t> free_ids_; const int32_t initial_id_; int32_t next_unused_id_; }; } // namespace smbprovider #endif // SMBPROVIDER_ID_MAP_H_
24.941176
78
0.684355
9b482e7a84fc2bbf31c47b074ccd214f19090f4e
1,033
h
C
Kernel/include/hashMap.h
juangod1/SO-TP2
1e2487acac3e64b4e135e3a733102fe9142f8805
[ "BSD-3-Clause" ]
1
2020-04-22T02:39:31.000Z
2020-04-22T02:39:31.000Z
Kernel/include/hashMap.h
juangod1/SO-TP2
1e2487acac3e64b4e135e3a733102fe9142f8805
[ "BSD-3-Clause" ]
null
null
null
Kernel/include/hashMap.h
juangod1/SO-TP2
1e2487acac3e64b4e135e3a733102fe9142f8805
[ "BSD-3-Clause" ]
null
null
null
#ifndef SO_TP2_HASHMAP_H #define SO_TP2_HASHMAP_H #define INITIAL_SIZE (256) #define MAX_CHAIN_LENGTH (8) #define MAP_MISSING -3 /* No such element */ #define MAP_FULL -2 /* Hashmap is full */ #define MAP_OMEM -1 /* Out of Memory */ #define MAP_OK 0 /* OK */ typedef void *any_t; typedef int (*PFany)(any_t, any_t); typedef any_t map_t; typedef struct _hashmapElement{ char* key; int inUse; any_t data; } hashmapElement; typedef struct _hashmap_map{ int tableSize; int size; hashmapElement *data; } hashmapMap; map_t newHashMap(); unsigned long crc32(const unsigned char *s, unsigned int len); unsigned int hashmapHashInt(hashmapMap* m, char* keystring); int hashmapHash(map_t in, char* key); int hashmapRehash(map_t in); int hashmapPut(map_t in, char* key, any_t value); int hashmapGet(map_t in, char* key, any_t *arg); int hashmapIterate(map_t in, PFany f, any_t item); int hashmapRemove(map_t in, char* key); void hashmapFree(map_t in); int hashmapLength(map_t in); #endif //SO_TP2_HASHMAP_H
23.477273
62
0.730881
bb552e9970d822060260fae90f5ffd84d0c86284
757
h
C
src/Parallelizer2OpenMP.h
g1257/PsimagLite
1cdeb4530c66cd41bd0c59af9ad2ecb1069ca010
[ "Unlicense" ]
8
2015-08-19T16:06:52.000Z
2021-12-05T02:37:47.000Z
src/Parallelizer2OpenMP.h
g1257/PsimagLite
1cdeb4530c66cd41bd0c59af9ad2ecb1069ca010
[ "Unlicense" ]
5
2016-02-02T20:28:21.000Z
2019-07-08T22:56:12.000Z
src/Parallelizer2OpenMP.h
g1257/PsimagLite
1cdeb4530c66cd41bd0c59af9ad2ecb1069ca010
[ "Unlicense" ]
5
2016-04-29T17:28:00.000Z
2019-11-22T03:33:19.000Z
#ifndef PARALLELIZER2OPENMP_H #define PARALLELIZER2OPENMP_H #include "Vector.h" #include <omp.h> #include "CodeSectionParams.h" namespace PsimagLite { template<typename = int> class Parallelizer2 { public: Parallelizer2(const CodeSectionParams& codeParams) : threads_(codeParams.npthreads) { omp_set_num_threads(codeParams.npthreads); } template<typename SomeLambdaType> void parallelFor(SizeType start, SizeType end, const SomeLambdaType& lambda) { #pragma omp parallel for for (SizeType i = start; i < end; ++i) lambda(i, omp_get_thread_num()); } SizeType numberOfThreads() const { return omp_get_num_threads(); } String name() const { return "openmp"; } private: SizeType threads_; }; } #endif // PARALLELIZER2OPENMP_H
18.463415
77
0.747688
bb937156a30e5165b8bf44bed8809276958a531c
1,793
h
C
include/fengine/docu.h
LukasBanana/ForkENGINE
8b575bd1d47741ad5025a499cb87909dbabc3492
[ "BSD-3-Clause" ]
13
2017-03-21T22:46:18.000Z
2020-07-30T01:31:57.000Z
include/fengine/docu.h
LukasBanana/ForkENGINE
8b575bd1d47741ad5025a499cb87909dbabc3492
[ "BSD-3-Clause" ]
null
null
null
include/fengine/docu.h
LukasBanana/ForkENGINE
8b575bd1d47741ad5025a499cb87909dbabc3492
[ "BSD-3-Clause" ]
2
2018-07-23T19:56:41.000Z
2020-07-30T01:32:01.000Z
/* * Doxygen docu extensions header * * This file is part of the "ForkENGINE" (Copyright (c) 2014 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #ifndef __FORK_DOCU_H__ #define __FORK_DOCU_H__ /** \defgroup math_core Core Math Functionality (Vectors, Matrices, Quaternions etc.). \defgroup lang_forkscript ForkSCript Language. \defgroup fork_exception All Engine Specific Exception Classes. \defgroup vertex_struct Default Vertex Structures. \defgroup std_geometries Standard Geometry Classes. \defgroup std_materials Standard Material Classes. \defgroup texture_classes Texture Classes. \defgroup network Network System. \defgroup xml_parser XML Parser. \defgroup animation Animation System. \defgroup postprocessor Post Processors. \defgroup gbuffer G-Buffer Classes. */ /** \page page_global_macros Global Macros Platform dependent macros: \code // Is defined on Microsoft Windows platforms. #define FORK_WINDOWS // Is defined on Posix platforms (e.g. GNU/Linux) (Not supported yet). #define FORK_POSIX // Is defined for Apple OSX and MacOSX platforms (Not supported yet). #define FORK_OSX // Is defined for Apple iOS platforms (Not supported yet). #define FORK_IOS // Is defined for Microsoft XBox platforms (Not supported yet). #define FORK_XBOX \endcode Compiler dependent macros: \code // Is defined for Microsoft VisualC++ compilers. #define FORK_MSVC // Is defined for GNU/C++ compilers. #define FORK_GCC \endcode */ /** \mainpage ForkENGINE 0.1 Alpha API Documentation \section section_intro Introduction Welcome to the API documentation of the ForkENGINE, a high level game engine. \section section_editor World Editor Here is a screenshot from the world editor: \image html images/MainPage.Cover.png */ #endif // ========================
24.561644
82
0.773006
f4d68aa22fdb97d17b242b6f27359a157e79e543
1,178
h
C
ServerKeeper/MPatchCheckMap.h
WhyWolfie/source2007
324257e9c69bbaec872ebb7ae4f96ab2ce98f520
[ "FSFAP" ]
null
null
null
ServerKeeper/MPatchCheckMap.h
WhyWolfie/source2007
324257e9c69bbaec872ebb7ae4f96ab2ce98f520
[ "FSFAP" ]
null
null
null
ServerKeeper/MPatchCheckMap.h
WhyWolfie/source2007
324257e9c69bbaec872ebb7ae4f96ab2ce98f520
[ "FSFAP" ]
null
null
null
#ifndef _PATCH_CHECK_MAP #define _PATCH_CHECK_MAP #include <windows.h> #include <map> using namespace std; #include "ServerKeeperConst.h" class MPatchCheckMap : private map< JOB_STATE, JOB_STATE > { public : MPatchCheckMap(); ~MPatchCheckMap(); void Init(); void Check( const JOB_STATE nJob, const JOB_STATE nState ); void Reset(); bool IsPossibleAgentPatchDownload(); bool IsPossibleServerPatchDownload(); bool IsPossibleReset(); bool IsJobSuccess( const JOB_STATE nJob ); bool IsServerPrepareComplete(); bool IsServerPatchComplete(); bool IsAgentPrepareComplete(); bool IsServerPatchDownloadComplete(); bool IsAgentPatchDownloadComplete(); const JOB_STATE GetLastJob() { return m_nLastJob; } const JOB_STATE GetLastResult() { return m_nLastResult; } const JOB_STATE GetJobState( const JOB_STATE nJob ); private : void Lock() { EnterCriticalSection( &m_csJob ); } void Unlock() { LeaveCriticalSection( &m_csJob ); } void SetState( const JOB_STATE nJob, const JOB_STATE nState ); void InsertJob( const JOB_STATE nJob, const JOB_STATE nState ); private : JOB_STATE m_nLastJob; JOB_STATE m_nLastResult; CRITICAL_SECTION m_csJob; }; #endif
23.56
64
0.765705
a584a56ac44a173c37209ca73f3ba8cb21adf516
29,334
c
C
libeasyice/src/H264DecDll/JM17.2/ldecod/src/block.c
codetalks-new/libeasyice
56781ff4a1c5a070526c87790fc34594c25a5846
[ "MIT" ]
45
2019-07-22T02:43:47.000Z
2021-08-02T01:53:43.000Z
libeasyice/src/H264DecDll/JM17.2/ldecod/src/block.c
codetalks-new/libeasyice
56781ff4a1c5a070526c87790fc34594c25a5846
[ "MIT" ]
null
null
null
libeasyice/src/H264DecDll/JM17.2/ldecod/src/block.c
codetalks-new/libeasyice
56781ff4a1c5a070526c87790fc34594c25a5846
[ "MIT" ]
19
2019-09-04T01:31:18.000Z
2021-11-03T05:32:14.000Z
/*! *********************************************************************** * \file * block.c * * \brief * Block functions * * \author * Main contributors (see contributors.h for copyright, address and affiliation details) * - Inge Lille-Langoy <inge.lille-langoy@telenor.com> * - Rickard Sjoberg <rickard.sjoberg@era.ericsson.se> *********************************************************************** */ #include "contributors.h" #include "global.h" #include "block.h" #include "blk_prediction.h" #include "image.h" #include "mb_access.h" #include "transform.h" #include "quant.h" #include "memalloc.h" /*! *********************************************************************** * \brief * Inverse 4x4 transformation, transforms cof to mb_rres *********************************************************************** */ void itrans4x4(Macroblock *currMB, //!< current macroblock ColorPlane pl, //!< used color plane int ioff, //!< index to 4x4 block int joff) //!< index to 4x4 block { Slice *currSlice = currMB->p_Slice; int **mb_rres = currSlice->mb_rres[pl]; inverse4x4(currSlice->cof[pl],mb_rres,joff,ioff); sample_reconstruct (&currSlice->mb_rec[pl][joff], &currSlice->mb_pred[pl][joff], &mb_rres[joff], ioff, ioff, BLOCK_SIZE, BLOCK_SIZE, currMB->p_Vid->max_pel_value_comp[pl], DQ_BITS); } /*! **************************************************************************** * \brief * Inverse 4x4 lossless_qpprime transformation, transforms cof to mb_rres **************************************************************************** */ void itrans4x4_ls(Macroblock *currMB, //!< current macroblock ColorPlane pl, //!< Color plane (for 4:4:4) int ioff, //!< index to 4x4 block int joff) //!< index to 4x4 block { int i,j; Slice *currSlice = currMB->p_Slice; VideoParameters *p_Vid = currMB->p_Vid; int max_imgpel_value = p_Vid->max_pel_value_comp[pl]; imgpel **mb_pred = currSlice->mb_pred[pl]; imgpel **mb_rec = currSlice->mb_rec[pl]; int **mb_rres = currSlice->mb_rres [pl]; for (j = joff; j < joff + BLOCK_SIZE; ++j) { for (i = ioff; i < ioff + BLOCK_SIZE; ++i) { mb_rec[j][i] = (imgpel) iClip1(max_imgpel_value, mb_pred[j][i] + mb_rres[j][i]); } } } /*! ************************************************************************ * \brief * Inverse residual DPCM for Intra lossless coding * ************************************************************************ */ void Inv_Residual_trans_4x4(Macroblock *currMB, //!< current macroblock ColorPlane pl, //!< used color plane int ioff, //!< index to 4x4 block int joff) //!< index to 4x4 block { int i,j; int temp[4][4]; Slice *currSlice = currMB->p_Slice; imgpel **mb_pred = currSlice->mb_pred[pl]; imgpel **mb_rec = currSlice->mb_rec[pl]; int **mb_rres = currSlice->mb_rres[pl]; int **cof = currSlice->cof[pl]; if(currMB->ipmode_DPCM == VERT_PRED) { for(i=0; i<4; ++i) { temp[0][i] = cof[joff + 0][ioff + i]; temp[1][i] = cof[joff + 1][ioff + i] + temp[0][i]; temp[2][i] = cof[joff + 2][ioff + i] + temp[1][i]; temp[3][i] = cof[joff + 3][ioff + i] + temp[2][i]; } for(i=0; i<4; ++i) { mb_rres[joff ][ioff + i]=temp[0][i]; mb_rres[joff + 1][ioff + i]=temp[1][i]; mb_rres[joff + 2][ioff + i]=temp[2][i]; mb_rres[joff + 3][ioff + i]=temp[3][i]; } } else if(currMB->ipmode_DPCM == HOR_PRED) { for(j=0; j<4; ++j) { temp[j][0] = cof[joff + j][ioff ]; temp[j][1] = cof[joff + j][ioff + 1] + temp[j][0]; temp[j][2] = cof[joff + j][ioff + 2] + temp[j][1]; temp[j][3] = cof[joff + j][ioff + 3] + temp[j][2]; } for(j=0; j<4; ++j) { mb_rres[joff + j][ioff ]=temp[j][0]; mb_rres[joff + j][ioff + 1]=temp[j][1]; mb_rres[joff + j][ioff + 2]=temp[j][2]; mb_rres[joff + j][ioff + 3]=temp[j][3]; } } else { for (j = joff; j < joff + BLOCK_SIZE; ++j) for (i = ioff; i < ioff + BLOCK_SIZE; ++i) mb_rres[j][i] = cof[j][i]; } for (j = joff; j < joff + BLOCK_SIZE; ++j) { for (i = ioff; i < ioff + BLOCK_SIZE; ++i) { mb_rec[j][i] = (imgpel) (mb_rres[j][i] + mb_pred[j][i]); } } } /*! ************************************************************************ * \brief * Inverse residual DPCM for Intra lossless coding * * \par Input: * ioff_x,joff_y: Block position inside a macro block (0,8). ************************************************************************ */ //For residual DPCM void Inv_Residual_trans_8x8(Macroblock *currMB, ColorPlane pl, int ioff,int joff) { Slice *currSlice = currMB->p_Slice; int i, j; int temp[8][8]; imgpel **mb_pred = currSlice->mb_pred[pl]; imgpel **mb_rec = currSlice->mb_rec[pl]; int **mb_rres = currSlice->mb_rres[pl]; if(currMB->ipmode_DPCM == VERT_PRED) { for(i=0; i<8; ++i) { temp[0][i] = mb_rres[joff + 0][ioff + i]; temp[1][i] = mb_rres[joff + 1][ioff + i] + temp[0][i]; temp[2][i] = mb_rres[joff + 2][ioff + i] + temp[1][i]; temp[3][i] = mb_rres[joff + 3][ioff + i] + temp[2][i]; temp[4][i] = mb_rres[joff + 4][ioff + i] + temp[3][i]; temp[5][i] = mb_rres[joff + 5][ioff + i] + temp[4][i]; temp[6][i] = mb_rres[joff + 6][ioff + i] + temp[5][i]; temp[7][i] = mb_rres[joff + 7][ioff + i] + temp[6][i]; } for(i=0; i<8; ++i) { mb_rres[joff ][ioff+i]=temp[0][i]; mb_rres[joff+1][ioff+i]=temp[1][i]; mb_rres[joff+2][ioff+i]=temp[2][i]; mb_rres[joff+3][ioff+i]=temp[3][i]; mb_rres[joff+4][ioff+i]=temp[4][i]; mb_rres[joff+5][ioff+i]=temp[5][i]; mb_rres[joff+6][ioff+i]=temp[6][i]; mb_rres[joff+7][ioff+i]=temp[7][i]; } } else if(currMB->ipmode_DPCM == HOR_PRED)//HOR_PRED { for(i=0; i<8; ++i) { temp[i][0] = mb_rres[joff + i][ioff + 0]; temp[i][1] = mb_rres[joff + i][ioff + 1] + temp[i][0]; temp[i][2] = mb_rres[joff + i][ioff + 2] + temp[i][1]; temp[i][3] = mb_rres[joff + i][ioff + 3] + temp[i][2]; temp[i][4] = mb_rres[joff + i][ioff + 4] + temp[i][3]; temp[i][5] = mb_rres[joff + i][ioff + 5] + temp[i][4]; temp[i][6] = mb_rres[joff + i][ioff + 6] + temp[i][5]; temp[i][7] = mb_rres[joff + i][ioff + 7] + temp[i][6]; } for(i=0; i<8; ++i) { mb_rres[joff+i][ioff+0]=temp[i][0]; mb_rres[joff+i][ioff+1]=temp[i][1]; mb_rres[joff+i][ioff+2]=temp[i][2]; mb_rres[joff+i][ioff+3]=temp[i][3]; mb_rres[joff+i][ioff+4]=temp[i][4]; mb_rres[joff+i][ioff+5]=temp[i][5]; mb_rres[joff+i][ioff+6]=temp[i][6]; mb_rres[joff+i][ioff+7]=temp[i][7]; } } for (j = joff; j < joff + BLOCK_SIZE*2; ++j) { for (i = ioff; i < ioff + BLOCK_SIZE*2; ++i) { mb_rec [j][i] = (imgpel) (mb_rres[j][i] + mb_pred[j][i]); } } } /*! ************************************************************************ * \brief * Inverse residual DPCM for Intra lossless coding * ************************************************************************ */ void Inv_Residual_trans_16x16(Macroblock *currMB, //!< current macroblock ColorPlane pl) //!< used color plane { int i,j; int temp[16][16]; Slice *currSlice = currMB->p_Slice; imgpel **mb_pred = currSlice->mb_pred[pl]; imgpel **mb_rec = currSlice->mb_rec[pl]; int **mb_rres = currSlice->mb_rres[pl]; int **cof = currSlice->cof[pl]; if(currMB->ipmode_DPCM == VERT_PRED_16) { for(i=0; i<MB_BLOCK_SIZE; ++i) { temp[0][i] = cof[0][i]; for(j = 1; j < MB_BLOCK_SIZE; j++) temp[j][i] = cof[j][i] + temp[j-1][i]; } for(i=0; i<MB_BLOCK_SIZE; ++i) { for(j = 0; j < MB_BLOCK_SIZE; j++) mb_rres[j][i]=temp[j][i]; } } else if(currMB->ipmode_DPCM == HOR_PRED_16) { for(j=0; j<MB_BLOCK_SIZE; ++j) { temp[j][ 0] = cof[j][ 0 ]; for(i = 1; i < MB_BLOCK_SIZE; i++) temp[j][i] = cof[j][i] + temp[j][i-1]; } for(j=0; j<MB_BLOCK_SIZE; ++j) { for(i = 0; i < MB_BLOCK_SIZE; ++i) mb_rres[j][i]=temp[j][i]; } } else { for (j = 0; j < MB_BLOCK_SIZE; ++j) for (i = 0; i < MB_BLOCK_SIZE; ++i) mb_rres[j][i] = cof[j][i]; } for (j = 0; j < MB_BLOCK_SIZE; ++j) { for (i = 0; i < MB_BLOCK_SIZE; ++i) { mb_rec[j][i] = (imgpel) (mb_rres[j][i] + mb_pred[j][i]); } } } /*! ************************************************************************ * \brief * Inverse residual DPCM for Intra lossless coding * ************************************************************************ */ void Inv_Residual_trans_Chroma(Macroblock *currMB, int uv) { int i, j; int temp[16][16]; Slice *currSlice = currMB->p_Slice; //imgpel **mb_pred = currSlice->mb_pred[uv+1]; //imgpel **mb_rec = currSlice->mb_rec[uv+1]; int **mb_rres = currSlice->mb_rres[uv+1]; int **cof = currSlice->cof[uv+1]; int width, height; width = currMB->p_Vid->mb_cr_size_x; height = currMB->p_Vid->mb_cr_size_y; if(currMB->c_ipred_mode == VERT_PRED_8) { for(i=0; i<width; i++) { temp[0][i] = cof[0][i]; for(j = 1; j < height; j++) temp[j][i] = temp[j-1][i] + cof[j][i]; } for(i=0; i<width; i++) { for(j = 0; j < height; j++) mb_rres[j][i] = temp[j][i]; } } else //HOR_PRED_8 { for(i=0; i<height; i++) { temp[i][0] = cof[i][0]; for(j = 1; j < width; j++) temp[i][j] = temp[i][j-1] + cof[i][j]; } for(i=0; i<height; i++) { for(j = 0; j < width; j++) mb_rres[i][j] = temp[i][j]; } } } /*! *********************************************************************** * \brief * Luma DC inverse transform *********************************************************************** */ void itrans_2(Macroblock *currMB, //!< current macroblock ColorPlane pl) //!< used color plane { Slice *currSlice = currMB->p_Slice; VideoParameters *p_Vid = currMB->p_Vid; int j; int transform_pl = (p_Vid->separate_colour_plane_flag != 0) ? PLANE_Y /*p_Vid->colour_plane_id*/ : pl; int **cof = currSlice->cof[transform_pl]; int qp_scaled = currMB->qp_scaled[pl]; int qp_per = p_Vid->qp_per_matrix[ qp_scaled ]; int qp_rem = p_Vid->qp_rem_matrix[ qp_scaled ]; int invLevelScale = currSlice->InvLevelScale4x4_Intra[pl][qp_rem][0][0]; int **M4; get_mem2Dint(&M4, BLOCK_SIZE, BLOCK_SIZE); // horizontal for (j=0; j < 4;++j) { M4[j][0]=cof[j<<2][0]; M4[j][1]=cof[j<<2][4]; M4[j][2]=cof[j<<2][8]; M4[j][3]=cof[j<<2][12]; } ihadamard4x4(M4, M4); // vertical for (j=0; j < 4;++j) { cof[j<<2][0] = rshift_rnd((( M4[j][0] * invLevelScale) << qp_per), 6); cof[j<<2][4] = rshift_rnd((( M4[j][1] * invLevelScale) << qp_per), 6); cof[j<<2][8] = rshift_rnd((( M4[j][2] * invLevelScale) << qp_per), 6); cof[j<<2][12] = rshift_rnd((( M4[j][3] * invLevelScale) << qp_per), 6); } free_mem2Dint(M4); } void itrans_sp(Macroblock *currMB, //!< current macroblock ColorPlane pl, //!< used color plane int ioff, //!< index to 4x4 block int joff) //!< index to 4x4 block { VideoParameters *p_Vid = currMB->p_Vid; Slice *currSlice = currMB->p_Slice; int i,j; int ilev, icof; int qp = (currSlice->slice_type == SI_SLICE) ? currSlice->qs : currSlice->qp; int qp_per = p_Vid->qp_per_matrix[ qp ]; int qp_rem = p_Vid->qp_rem_matrix[ qp ]; int qp_per_sp = p_Vid->qp_per_matrix[ currSlice->qs ]; int qp_rem_sp = p_Vid->qp_rem_matrix[ currSlice->qs ]; int q_bits_sp = Q_BITS + qp_per_sp; imgpel **mb_pred = currSlice->mb_pred[pl]; imgpel **mb_rec = currSlice->mb_rec[pl]; int **mb_rres = currSlice->mb_rres[pl]; int **cof = currSlice->cof[pl]; int max_imgpel_value = p_Vid->max_pel_value_comp[pl]; const int (*InvLevelScale4x4) [4] = dequant_coef[qp_rem]; const int (*InvLevelScale4x4SP)[4] = dequant_coef[qp_rem_sp]; int **PBlock; get_mem2Dint(&PBlock, MB_BLOCK_SIZE, MB_BLOCK_SIZE); for (j=0; j< BLOCK_SIZE; ++j) { PBlock[j][0] = mb_pred[j+joff][ioff ]; PBlock[j][1] = mb_pred[j+joff][ioff + 1]; PBlock[j][2] = mb_pred[j+joff][ioff + 2]; PBlock[j][3] = mb_pred[j+joff][ioff + 3]; } forward4x4(PBlock, PBlock, 0, 0); if(currSlice->sp_switch || currSlice->slice_type==SI_SLICE) { for (j=0;j<BLOCK_SIZE;++j) { for (i=0;i<BLOCK_SIZE;++i) { // recovering coefficient since they are already dequantized earlier icof = (cof[joff + j][ioff + i] >> qp_per) / InvLevelScale4x4[j][i]; //icof = ((cof[joff + j][ioff + i] * quant_coef[qp_rem][j][i])>> (qp_per + 15)) ; // icof = rshift_rnd_sf(cof[joff + j][ioff + i] * quant_coef[qp_rem][j][i], qp_per + 15); ilev = rshift_rnd_sf(iabs(PBlock[j][i]) * quant_coef[qp_rem_sp][j][i], q_bits_sp); ilev = isignab(ilev, PBlock[j][i]) + icof; cof[joff + j][ioff + i] = ilev * InvLevelScale4x4SP[j][i] << qp_per_sp; } } } else { for (j=0;j<BLOCK_SIZE;++j) { for (i=0;i<BLOCK_SIZE;++i) { // recovering coefficient since they are already dequantized earlier icof = (cof[joff + j][ioff + i] >> qp_per) / InvLevelScale4x4[j][i]; //icof = cof[joff + j][ioff + i]; //icof = rshift_rnd_sf(cof[joff + j][ioff + i] * quant_coef[qp_rem][j][i], qp_per + 15); ilev = PBlock[j][i] + ((icof * InvLevelScale4x4[j][i] * A[j][i] << qp_per) >> 6); ilev = isign(ilev) * rshift_rnd_sf(iabs(ilev) * quant_coef[qp_rem_sp][j][i], q_bits_sp); //cof[joff + j][ioff + i] = ilev * InvLevelScale4x4SP[j][i] << qp_per_sp; cof[joff + j][ioff + i] = ilev * InvLevelScale4x4SP[j][i] << qp_per_sp; } } } inverse4x4(cof, mb_rres, joff, ioff); for (j=joff; j<joff +BLOCK_SIZE;++j) { mb_rec[j][ioff ] = (imgpel) iClip1(max_imgpel_value,rshift_rnd_sf(mb_rres[j][ioff ], DQ_BITS)); mb_rec[j][ioff+ 1] = (imgpel) iClip1(max_imgpel_value,rshift_rnd_sf(mb_rres[j][ioff+ 1], DQ_BITS)); mb_rec[j][ioff+ 2] = (imgpel) iClip1(max_imgpel_value,rshift_rnd_sf(mb_rres[j][ioff+ 2], DQ_BITS)); mb_rec[j][ioff+ 3] = (imgpel) iClip1(max_imgpel_value,rshift_rnd_sf(mb_rres[j][ioff+ 3], DQ_BITS)); } free_mem2Dint(PBlock); } void itrans_sp_cr(Macroblock *currMB, int uv) { Slice *currSlice = currMB->p_Slice; VideoParameters *p_Vid = currMB->p_Vid; int i,j,ilev, icof, n2,n1; int mp1[BLOCK_SIZE]; int qp_per,qp_rem; int qp_per_sp,qp_rem_sp,q_bits_sp; imgpel **mb_pred = currSlice->mb_pred[uv + 1]; int **cof = currSlice->cof[uv + 1]; int **PBlock = new_mem2Dint(MB_BLOCK_SIZE, MB_BLOCK_SIZE); qp_per = p_Vid->qp_per_matrix[ ((currSlice->qp < 0 ? currSlice->qp : QP_SCALE_CR[currSlice->qp]))]; qp_rem = p_Vid->qp_rem_matrix[ ((currSlice->qp < 0 ? currSlice->qp : QP_SCALE_CR[currSlice->qp]))]; qp_per_sp = p_Vid->qp_per_matrix[ ((currSlice->qs < 0 ? currSlice->qs : QP_SCALE_CR[currSlice->qs]))]; qp_rem_sp = p_Vid->qp_rem_matrix[ ((currSlice->qs < 0 ? currSlice->qs : QP_SCALE_CR[currSlice->qs]))]; q_bits_sp = Q_BITS + qp_per_sp; if (currSlice->slice_type == SI_SLICE) { qp_per = qp_per_sp; qp_rem = qp_rem_sp; } for (j=0; j < p_Vid->mb_cr_size_y; ++j) { for (i=0; i < p_Vid->mb_cr_size_x; ++i) { PBlock[j][i] = mb_pred[j][i]; mb_pred[j][i] = 0; } } for (n2=0; n2 < p_Vid->mb_cr_size_y; n2 += BLOCK_SIZE) { for (n1=0; n1 < p_Vid->mb_cr_size_x; n1 += BLOCK_SIZE) { forward4x4(PBlock, PBlock, n2, n1); } } // 2X2 transform of DC coeffs. mp1[0] = (PBlock[0][0] + PBlock[4][0] + PBlock[0][4] + PBlock[4][4]); mp1[1] = (PBlock[0][0] - PBlock[4][0] + PBlock[0][4] - PBlock[4][4]); mp1[2] = (PBlock[0][0] + PBlock[4][0] - PBlock[0][4] - PBlock[4][4]); mp1[3] = (PBlock[0][0] - PBlock[4][0] - PBlock[0][4] + PBlock[4][4]); if (currSlice->sp_switch || currSlice->slice_type == SI_SLICE) { for (n2=0; n2 < 2; ++n2 ) { for (n1=0; n1 < 2; ++n1 ) { //quantization fo predicted block ilev = rshift_rnd_sf(iabs (mp1[n1+n2*2]) * quant_coef[qp_rem_sp][0][0], q_bits_sp + 1); //addition ilev = isignab(ilev, mp1[n1+n2*2]) + cof[n2<<2][n1<<2]; //dequantization mp1[n1+n2*2] =ilev * dequant_coef[qp_rem_sp][0][0] << qp_per_sp; } } for (n2 = 0; n2 < p_Vid->mb_cr_size_y; n2 += BLOCK_SIZE) { for (n1 = 0; n1 < p_Vid->mb_cr_size_x; n1 += BLOCK_SIZE) { for (j = 0; j < BLOCK_SIZE; ++j) { for (i = 0; i < BLOCK_SIZE; ++i) { // recovering coefficient since they are already dequantized earlier cof[n2 + j][n1 + i] = (cof[n2 + j][n1 + i] >> qp_per) / dequant_coef[qp_rem][j][i]; //quantization of the predicted block ilev = rshift_rnd_sf(iabs(PBlock[n2 + j][n1 + i]) * quant_coef[qp_rem_sp][j][i], q_bits_sp); //addition of the residual ilev = isignab(ilev,PBlock[n2 + j][n1 + i]) + cof[n2 + j][n1 + i]; // Inverse quantization cof[n2 + j][n1 + i] = ilev * dequant_coef[qp_rem_sp][j][i] << qp_per_sp; } } } } } else { for (n2=0; n2 < 2; ++n2 ) { for (n1=0; n1 < 2; ++n1 ) { ilev = mp1[n1+n2*2] + (((cof[n2<<2][n1<<2] * dequant_coef[qp_rem][0][0] * A[0][0]) << qp_per) >> 5); ilev = isign(ilev) * rshift_rnd_sf(iabs(ilev) * quant_coef[qp_rem_sp][0][0], q_bits_sp + 1); //ilev = isignab(rshift_rnd_sf(iabs(ilev)* quant_coef[qp_rem_sp][0][0], q_bits_sp + 1), ilev); mp1[n1+n2*2] = ilev * dequant_coef[qp_rem_sp][0][0] << qp_per_sp; } } for (n2 = 0; n2 < p_Vid->mb_cr_size_y; n2 += BLOCK_SIZE) { for (n1 = 0; n1 < p_Vid->mb_cr_size_x; n1 += BLOCK_SIZE) { for (j = 0; j< BLOCK_SIZE; ++j) { for (i = 0; i< BLOCK_SIZE; ++i) { // recovering coefficient since they are already dequantized earlier //icof = ((((cof[n2 + j][n1 + i] << 4) + qp_per/2)>> qp_per) + dequant_coef[qp_rem][j][i]/2) / dequant_coef[qp_rem][j][i]; icof = (cof[n2 + j][n1 + i] >> qp_per) / dequant_coef[qp_rem][j][i]; //dequantization and addition of the predicted block ilev = PBlock[n2 + j][n1 + i] + ((icof * dequant_coef[qp_rem][j][i] * A[j][i] << qp_per) >> 6); //quantization and dequantization ilev = isign(ilev) * rshift_rnd_sf(iabs(ilev) * quant_coef[qp_rem_sp][j][i], q_bits_sp); cof[n2 + j][n1 + i] = ilev * dequant_coef[qp_rem_sp][j][i] << qp_per_sp; //printf( " %d %d %d\n", j, i, quant_coef[qp_rem_sp][j][i]); } } } } } cof[0][0] = (mp1[0] + mp1[1] + mp1[2] + mp1[3]) >> 1; cof[0][4] = (mp1[0] + mp1[1] - mp1[2] - mp1[3]) >> 1; cof[4][0] = (mp1[0] - mp1[1] + mp1[2] - mp1[3]) >> 1; cof[4][4] = (mp1[0] - mp1[1] - mp1[2] + mp1[3]) >> 1; free_mem2Dint(PBlock); } void iMBtrans4x4(Macroblock *currMB, ColorPlane pl, int smb) { Slice *currSlice = currMB->p_Slice; //VideoParameters *p_Vid = currMB->p_Vid; StorablePicture *dec_picture = currMB->p_Slice->dec_picture; int jj, ii; int block8x8; int k; imgpel **curr_img = pl ? dec_picture->imgUV[pl - 1]: dec_picture->imgY; // =============== 4x4 itrans ================ // ------------------------------------------- if (currMB->is_lossless && currMB->mb_type == I16MB) { Inv_Residual_trans_16x16(currMB, pl) ; } else if (smb || currMB->is_lossless == TRUE) { currMB->itrans_4x4 = (smb) ? itrans_sp : ((currMB->is_lossless == FALSE) ? itrans4x4 : Inv_Residual_trans_4x4); for (block8x8=0; block8x8 < MB_BLOCK_SIZE; block8x8 += 4) { for (k = block8x8; k < block8x8 + 4; ++k ) { jj = ((decode_block_scan[k] >> 2) & 3) << BLOCK_SHIFT; ii = (decode_block_scan[k] & 3) << BLOCK_SHIFT; currMB->itrans_4x4(currMB, pl, ii, jj); // use integer transform and make 4x4 block mb_rres from prediction block mb_pred } } } else { int **cof = currSlice->cof[pl]; int **mb_rres = currSlice->mb_rres[pl]; for (jj = 0; jj < MB_BLOCK_SIZE; jj += BLOCK_SIZE) { inverse4x4(cof, mb_rres, jj, 0); inverse4x4(cof, mb_rres, jj, 4); inverse4x4(cof, mb_rres, jj, 8); inverse4x4(cof, mb_rres, jj, 12); } sample_reconstruct (currSlice->mb_rec[pl], currSlice->mb_pred[pl], mb_rres, 0, 0, MB_BLOCK_SIZE, MB_BLOCK_SIZE, currMB->p_Vid->max_pel_value_comp[pl], DQ_BITS); } // construct picture from 4x4 blocks copy_image_data_16x16(&curr_img[currMB->pix_y], currSlice->mb_rec[pl], currMB->pix_x, 0); } void iMBtrans8x8(Macroblock *currMB, ColorPlane pl) { //VideoParameters *p_Vid = currMB->p_Vid; StorablePicture *dec_picture = currMB->p_Slice->dec_picture; imgpel **curr_img = pl ? dec_picture->imgUV[pl - 1]: dec_picture->imgY; // Perform 8x8 idct itrans8x8(currMB, pl, 0, 0); itrans8x8(currMB, pl, 8, 0); itrans8x8(currMB, pl, 0, 8); itrans8x8(currMB, pl, 8, 8); copy_image_data_16x16(&curr_img[currMB->pix_y], currMB->p_Slice->mb_rec[pl], currMB->pix_x, 0); } void iTransform(Macroblock *currMB, ColorPlane pl, int smb) { Slice *currSlice = currMB->p_Slice; VideoParameters *p_Vid = currMB->p_Vid; StorablePicture *dec_picture = currSlice->dec_picture; imgpel **curr_img; int uv = pl-1; if ((currMB->cbp & 15) != 0 || smb) { if(currMB->luma_transform_size_8x8_flag == 0) // 4x4 inverse transform { iMBtrans4x4(currMB, pl, smb); } else // 8x8 inverse transform { iMBtrans8x8(currMB, pl); } } else { curr_img = pl ? dec_picture->imgUV[uv] : dec_picture->imgY; copy_image_data_16x16(&curr_img[currMB->pix_y], currSlice->mb_pred[pl], currMB->pix_x, 0); } if ((dec_picture->chroma_format_idc != YUV400) && (dec_picture->chroma_format_idc != YUV444)) { imgpel **curUV; int b8; int ioff, joff; imgpel **mb_rec; for(uv = PLANE_U; uv <= PLANE_V; ++uv) { // =============== 4x4 itrans ================ // ------------------------------------------- curUV = &dec_picture->imgUV[uv - 1][currMB->pix_c_y]; mb_rec = currSlice->mb_rec[uv]; if (!smb && (currMB->cbp>>4)) { if (currMB->is_lossless == FALSE) { const unsigned char *x_pos, *y_pos; //const unsigned char *xx_pos = subblk_offset_x[1]; //const unsigned char *xy_pos = subblk_offset_y[1]; for (b8 = 0; b8 < (p_Vid->num_uv_blocks); ++b8) { x_pos = subblk_offset_x[1][b8]; y_pos = subblk_offset_y[1][b8]; itrans4x4(currMB, uv, *x_pos++, *y_pos++); itrans4x4(currMB, uv, *x_pos++, *y_pos++); itrans4x4(currMB, uv, *x_pos++, *y_pos++); itrans4x4(currMB, uv, *x_pos , *y_pos ); //itrans4x4(currMB, uv, *(*xx_pos ), *(*xy_pos )); //itrans4x4(currMB, uv, *(*xx_pos + 1), *(*xy_pos + 1)); //itrans4x4(currMB, uv, *(*xx_pos + 2), *(*xy_pos + 2)); //itrans4x4(currMB, uv, *(*xx_pos++ + 3), *(*xy_pos++ + 3)); } sample_reconstruct (mb_rec, currSlice->mb_pred[uv], currSlice->mb_rres[uv], 0, 0, p_Vid->mb_size[1][0], p_Vid->mb_size[1][1], currMB->p_Vid->max_pel_value_comp[uv], DQ_BITS); } else { const unsigned char *x_pos, *y_pos; for (b8 = 0; b8 < (p_Vid->num_uv_blocks); ++b8) { x_pos = subblk_offset_x[1][b8]; y_pos = subblk_offset_y[1][b8]; itrans4x4_ls(currMB, uv, *x_pos++, *y_pos++); itrans4x4_ls(currMB, uv, *x_pos++, *y_pos++); itrans4x4_ls(currMB, uv, *x_pos++, *y_pos++); itrans4x4_ls(currMB, uv, *x_pos , *y_pos ); } } copy_image_data(curUV, mb_rec, currMB->pix_c_x, 0, p_Vid->mb_size[1][0], p_Vid->mb_size[1][1]); } else if (smb) { currMB->itrans_4x4 = (currMB->is_lossless == FALSE) ? itrans4x4 : itrans4x4_ls; itrans_sp_cr(currMB, uv - 1); for (joff = 0; joff < p_Vid->mb_cr_size_y; joff += BLOCK_SIZE) { for(ioff = 0; ioff < p_Vid->mb_cr_size_x ;ioff += BLOCK_SIZE) { currMB->itrans_4x4(currMB, uv, ioff, joff); } } copy_image_data(curUV, mb_rec, currMB->pix_c_x, 0, p_Vid->mb_size[1][0], p_Vid->mb_size[1][1]); } else { copy_image_data(curUV, currSlice->mb_pred[uv], currMB->pix_c_x, 0, p_Vid->mb_size[1][0], p_Vid->mb_size[1][1]); } } } } /*! ************************************************************************************* * \brief * Copy ImgPel Data from one structure to another (16x16) ************************************************************************************* */ void copy_image_data_16x16(imgpel **imgBuf1, imgpel **imgBuf2, int off1, int off2) { int j; for(j = 0; j < MB_BLOCK_SIZE; j += 4) { memcpy((*imgBuf1++ + off1), (*imgBuf2++ + off2), MB_BLOCK_SIZE * sizeof (imgpel)); memcpy((*imgBuf1++ + off1), (*imgBuf2++ + off2), MB_BLOCK_SIZE * sizeof (imgpel)); memcpy((*imgBuf1++ + off1), (*imgBuf2++ + off2), MB_BLOCK_SIZE * sizeof (imgpel)); memcpy((*imgBuf1++ + off1), (*imgBuf2++ + off2), MB_BLOCK_SIZE * sizeof (imgpel)); } } /*! ************************************************************************************* * \brief * Copy ImgPel Data from one structure to another (8x8) ************************************************************************************* */ void copy_image_data_8x8(imgpel **imgBuf1, imgpel **imgBuf2, int off1, int off2) { int j; for(j = 0; j < BLOCK_SIZE_8x8; j+=4) { memcpy((*imgBuf1++ + off1), (*imgBuf2++ + off2), BLOCK_SIZE_8x8 * sizeof (imgpel)); memcpy((*imgBuf1++ + off1), (*imgBuf2++ + off2), BLOCK_SIZE_8x8 * sizeof (imgpel)); memcpy((*imgBuf1++ + off1), (*imgBuf2++ + off2), BLOCK_SIZE_8x8 * sizeof (imgpel)); memcpy((*imgBuf1++ + off1), (*imgBuf2++ + off2), BLOCK_SIZE_8x8 * sizeof (imgpel)); } } /*! ************************************************************************************* * \brief * Copy ImgPel Data from one structure to another (4x4) ************************************************************************************* */ void copy_image_data_4x4(imgpel **imgBuf1, imgpel **imgBuf2, int off1, int off2) { memcpy((*imgBuf1++ + off1), (*imgBuf2++ + off2), BLOCK_SIZE * sizeof (imgpel)); memcpy((*imgBuf1++ + off1), (*imgBuf2++ + off2), BLOCK_SIZE * sizeof (imgpel)); memcpy((*imgBuf1++ + off1), (*imgBuf2++ + off2), BLOCK_SIZE * sizeof (imgpel)); memcpy((*imgBuf1 + off1), (*imgBuf2 + off2), BLOCK_SIZE * sizeof (imgpel)); } int CheckVertMV(Macroblock *currMB, int vec1_y, int block_size_y) { VideoParameters *p_Vid = currMB->p_Vid; StorablePicture *dec_picture = currMB->p_Slice->dec_picture; int y_pos = vec1_y>>2; int maxold_y = (currMB->mb_field) ? (dec_picture->size_y >> 1) - 1 : dec_picture->size_y_m1; if(y_pos < (-p_Vid->iLumaPadY + 2) || y_pos > (maxold_y + p_Vid->iLumaPadY - block_size_y - 2)) return 1; else return 0; } /*! ************************************************************************************* * \brief * Copy ImgPel Data from one structure to another (8x8) ************************************************************************************* */ void copy_image_data(imgpel **imgBuf1, imgpel **imgBuf2, int off1, int off2, int width, int height) { int j; for(j = 0; j < height; ++j) { memcpy((*imgBuf1++ + off1), (*imgBuf2++ + off2), width * sizeof (imgpel)); } }
33.951389
184
0.504057
538cf2ff3070805f370d82f1cf2081469f07711b
708
h
C
async/coroutine/coroutine_notifier.h
smallsunsun1/async_lib
d1e88aa73a1084a9549f884241266c8bdf568411
[ "Apache-2.0", "MIT" ]
null
null
null
async/coroutine/coroutine_notifier.h
smallsunsun1/async_lib
d1e88aa73a1084a9549f884241266c8bdf568411
[ "Apache-2.0", "MIT" ]
null
null
null
async/coroutine/coroutine_notifier.h
smallsunsun1/async_lib
d1e88aa73a1084a9549f884241266c8bdf568411
[ "Apache-2.0", "MIT" ]
null
null
null
#ifndef ASYNC_COROUTINE_COROUTINE_NOTIFIER_ #define ASYNC_COROUTINE_COROUTINE_NOTIFIER_ #include <condition_variable> #include <mutex> class CoroutineNotifier { public: CoroutineNotifier(bool isSet) : mIsSet(isSet) {} CoroutineNotifier() = default; ~CoroutineNotifier() = default; void Set() { std::unique_lock<std::mutex> lock(mMutex); if (!mIsSet) { mIsSet = true; mCv.notify_one(); } } void Wait() { std::unique_lock<std::mutex> lock(mMutex); mCv.wait(lock, [this]() { return mIsSet == true; }); mIsSet = true; } private: bool mIsSet = false; std::mutex mMutex; std::condition_variable mCv; }; #endif /* ASYNC_COROUTINE_COROUTINE_NOTIFIER_ */
22.125
56
0.682203
5b31d3e44cf4d0e62b31e0701e4ddcfc25b8d11b
1,461
h
C
aigmain/aigmain/game_impl.h
sidsahay/aig
b186cad11605469e514e61759af4932dd250fc7a
[ "MIT" ]
null
null
null
aigmain/aigmain/game_impl.h
sidsahay/aig
b186cad11605469e514e61759af4932dd250fc7a
[ "MIT" ]
null
null
null
aigmain/aigmain/game_impl.h
sidsahay/aig
b186cad11605469e514e61759af4932dd250fc7a
[ "MIT" ]
null
null
null
#pragma once #include "game.h" template <typename GameT> void aig::IAgent<GameT>::SetId(int id) { _id = id; } template<typename GameT> inline aig::IAgent<GameT>::~IAgent() { } template <typename GameT> void aig::GameSystem<GameT>::RegisterAgent(IAgent<GameT> * agent) { //TODO use a PRNG here to generate a proper GUID. Or some other form of GUID generation. agent->SetId(_counter); _counter++; _agents.push_back(agent); } template <typename GameT> void aig::GameSystem<GameT>::CreateGameWindow(const char * title, int width, int height) { _graphics = new Graphics(); _graphics->CreateWindow(title, width, height); } template <typename GameT> void aig::GameSystem<GameT>::RunGame() { using namespace std::chrono; high_resolution_clock::time_point previous_time = high_resolution_clock::now(); GameT game(_agents, _graphics); game.Initialize(); //Simple game loop while (!game.HasEnded()) { high_resolution_clock::time_point current_time = high_resolution_clock::now(); duration<double> span = current_time - previous_time; double elapsed_time = span.count(); previous_time = current_time; game.PreProcess(); game.RunAi(elapsed_time); game.UpdateState(elapsed_time); game.Render(); } _graphics->WaitForQuit(); } template<typename GameT> aig::GameSystem<GameT>::~GameSystem() { delete _graphics; }
22.476923
92
0.67488
1286753661ee69ea21f02dfca3b11741ebbd3542
5,115
h
C
src/QmlUtils.h
SammyEnigma/Kaidan
ad8c6a419a13024c71f54fefa820400e21dfc77c
[ "Apache-2.0" ]
81
2016-11-02T20:25:38.000Z
2021-12-19T23:45:03.000Z
src/QmlUtils.h
KDE/kaidan
e6292d8dc8ea4827fef5d0b4dc398446d73c6a6a
[ "Apache-2.0" ]
148
2016-10-31T15:56:35.000Z
2018-06-06T17:35:20.000Z
src/QmlUtils.h
KDE/kaidan
e6292d8dc8ea4827fef5d0b4dc398446d73c6a6a
[ "Apache-2.0" ]
28
2016-10-31T16:15:14.000Z
2020-05-19T20:31:14.000Z
/* * Kaidan - A user-friendly XMPP client for every device! * * Copyright (C) 2016-2021 Kaidan developers and contributors * (see the LICENSE file for a full list of copyright authors) * * Kaidan 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. * * In addition, as a special exception, the author of Kaidan gives * permission to link the code of its release with the OpenSSL * project's "OpenSSL" library (or with modified versions of it that * use the same license as the "OpenSSL" library), and distribute the * linked executables. You must obey the GNU General Public License in * all respects for all of the code used other than "OpenSSL". If you * modify this file, you may extend this exception to your version of * the file, but you are not obligated to do so. If you do not wish to * do so, delete this exception statement from your version. * * Kaidan 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 Kaidan. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <QObject> #include <QUrl> #include <QXmppMessage.h> #include "ClientWorker.h" #include "Globals.h" /** * @brief C++ utitlities to be used in QML * * The methods are not static, because they need to be used from QML and registered in * Qt. */ class QmlUtils : public QObject { Q_OBJECT Q_PROPERTY(QUrl issueTrackingUrl READ issueTrackingUrl CONSTANT) public: static QmlUtils *instance(); QmlUtils(QObject *parent = nullptr); ~QmlUtils(); /** * Returns an error message for a connection error. * * @param error error for which an error message should be returned */ Q_INVOKABLE static QString connectionErrorMessage(ClientWorker::ConnectionError error); /** * Returns a URL to a given resource file name * * This will check various paths which could contain the searched file. * If the file was found, it'll return a `file://` or a `qrc:/` url to * the file. */ Q_INVOKABLE static QString getResourcePath(const QString &resourceName); /** * Returns a string of this build's Kaidan version */ Q_INVOKABLE static QString versionString() { return QStringLiteral(VERSION_STRING); } /** * Returns the name of this application as it should be displayed to the user */ Q_INVOKABLE static QString applicationDisplayName() { return QStringLiteral(APPLICATION_DISPLAY_NAME); } /** * Returns the URL where the source code of this application can be found */ Q_INVOKABLE static QUrl applicationSourceCodeUrl() { return {QStringLiteral(APPLICATION_SOURCE_CODE_URL)}; } /** * Returns the URL to view and report issues. */ static QUrl issueTrackingUrl(); /** * Returns an invitation URL to the given JID */ Q_INVOKABLE static QUrl invitationUrl(const QString &jid) { return {QStringLiteral(INVITATION_URL) + jid}; } /** * Returns a string without new lines, unneeded spaces, etc. * * See QString::simplified for more information. */ Q_INVOKABLE static QString removeNewLinesFromString(const QString &input) { return input.simplified(); } /** * Checks whether a file is an image and could be displayed as such. * @param fileUrl URL to the possible image file */ Q_INVOKABLE static bool isImageFile(const QUrl &fileUrl); /** * Copy text to the clipboard */ Q_INVOKABLE static void copyToClipboard(const QString &text); /** * Returns the file name from a URL */ Q_INVOKABLE static QString fileNameFromUrl(const QUrl &url); /** * Returns the file size from a URL */ Q_INVOKABLE static QString fileSizeFromUrl(const QUrl &url); /** * Styles/formats a message for displaying * * This currently only adds some link highlighting */ Q_INVOKABLE static QString formatMessage(const QString &message); /** * Returns a consistent user color generated from the nickname. */ Q_INVOKABLE static QColor getUserColor(const QString &nickName); /** * Reads an image from the clipboard and returns the url of the saved image. */ Q_INVOKABLE static QUrl pasteImage(); /** * Returns the absolute file path for files to be downloaded. */ static QString downloadPath(const QString &filename); /** * Returns the timestamp in a format for file names. */ static QString timestampForFileName(); static QString timestampForFileName(const QDateTime &dateTime); /** * Returns a human-readable string describing the state of the chat */ Q_INVOKABLE static QString chatStateDescription(const QString &displayName, const QXmppMessage::State state); private: /** * Highlights links in a list of words */ static QString processMsgFormatting(const QStringList &words, bool isFirst = true); };
28.259669
110
0.727273
3e427088e56ba512a4e6483f0639ca7bf592c311
647
h
C
src/prod/src/data/txnreplicator/loggingreplicator/ILogManager.h
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/src/data/txnreplicator/loggingreplicator/ILogManager.h
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/src/data/txnreplicator/loggingreplicator/ILogManager.h
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #pragma once namespace Data { namespace LoggingReplicator { interface ILogManager : public LogRecordLib::ILogManagerReadOnly { K_SHARED_INTERFACE(ILogManager); public: virtual ktl::Awaitable<void> FlushAsync( __in KStringView const & initiator) = 0; }; } }
25.88
98
0.50541
3e45b19d79f9ee7aa7d1455313116027a48e475c
25,762
c
C
net/r_t4_rx/T4_src/ether.c
hirakuni45/RX
3fb91bfc8d5282cde7aa00b8bd37f4aad32582d0
[ "BSD-3-Clause" ]
56
2015-06-04T14:15:38.000Z
2022-03-01T22:58:49.000Z
net/r_t4_rx/T4_src/ether.c
duybang140494/RX
7fed06a9d8295f4504e8a08fa589d4a52792095f
[ "BSD-3-Clause" ]
30
2019-07-27T11:03:14.000Z
2021-12-14T09:59:57.000Z
net/r_t4_rx/T4_src/ether.c
duybang140494/RX
7fed06a9d8295f4504e8a08fa589d4a52792095f
[ "BSD-3-Clause" ]
15
2017-06-24T11:33:39.000Z
2021-12-07T07:26:58.000Z
/*********************************************************************************************************************** * DISCLAIMER * This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No * other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all * applicable laws, including copyright laws. * THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING * THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM * EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES * SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS * SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of * this software. By using this software, you agree to the additional terms and conditions found by accessing the * following link: * http://www.renesas.com/disclaimer * * Copyright (C) 2014-2016 Renesas Electronics Corporation, All Rights Reserved. ***********************************************************************************************************************/ /*********************************************************************************************************************** * File Name : ether.c * Version : 1.01 * Description : Processing for Ether protocol * Website : https://www.renesas.com/mw/t4 ***********************************************************************************************************************/ /*********************************************************************************************************************** * History : DD.MM.YYYY Version Description * : 01.04.2014 1.00 First Release * : 30.11.2016 1.01 add DHCP relation ***********************************************************************************************************************/ /*********************************************************************************************************************** Includes <System Includes> , "Project Includes" ***********************************************************************************************************************/ #include <stdio.h> #include <string.h> #include "r_tcpip_private.h" #include "type.h" #include "r_t4_itcpip.h" #include "ether.h" #include "ip.h" #include "tcp.h" #include "dhcp.h" #include "global.h" #include "r_t4_rx/src/config_tcpudp.h" /*********************************************************************************************************************** Macro definitions ***********************************************************************************************************************/ /*********************************************************************************************************************** Typedef definitions ***********************************************************************************************************************/ /*********************************************************************************************************************** Exported global variables (to be accessed by other files) ***********************************************************************************************************************/ /*********************************************************************************************************************** Private global variables and functions ***********************************************************************************************************************/ /*********************************************************************************************************************** Exported global variables (read from other files) ***********************************************************************************************************************/ /*********************************************************************************************************************** * Function Name: _ether_proc_rcv * Description : * Arguments : * Return Value : ***********************************************************************************************************************/ void _ether_proc_rcv(void) { sint16 len; _EP *pep; /* Return when receive buffer has not released yet */ /* The information has already stored in '_p_rcv_buf' */ if (_ch_info_tbl->_p_rcv_buf.len != 0) { return; } /* Call: driver interface to receive */ void *buf; len = lan_read(_ch_info_tbl->_ch_num, &buf); /* * len > 0 : receive data size * -1 : No data in LAN controller buffer * -2 : LAN controller status is 'STOP' * -5 : LAN controller status is 'ILLEGAL' or need reset. * -6 : CRC error */ if (len < 0) { /* CRC error: buffer release */ if (len == -6) { rcv_buff_release(_ch_info_tbl->_ch_num) ; _ch_info_tbl->_p_rcv_buf.len = 0; } /* LAN Controller reset */ else if (len == -5) { lan_reset(_ch_info_tbl->_ch_num); } /* No data, LAN controller status is 'STOP'. */ return; } /* Illegal len: discard the received data */ else if ((len > 1514) || (len < 60)) { rcv_buff_release(_ch_info_tbl->_ch_num); _ch_info_tbl->_p_rcv_buf.len = 0; report_error(_ch_info_tbl->_ch_num, RE_LEN, (UB*)buf); return; } pep = (_EP *)buf; data_link_buf_ptr = (UB*)buf; /* other(len >= 0): start receive process */ _ch_info_tbl->_p_rcv_buf.len = len - _ETH_LEN; _ch_info_tbl->_p_rcv_buf.pip = &(pep->data[0]); _ch_info_tbl->_p_rcv_buf.ip_rcv = 0; /* Find the packet type */ switch (pep->eh.eh_type) { /* IP Packet Receive */ case hs2net(EPT_IP) : /* IP data received flag ON */ _ch_info_tbl->_p_rcv_buf.ip_rcv = 1; break ; /* ARP Packet Receive */ case hs2net(EPT_ARP) : _ether_rcv_arp() ; break ; default : rcv_buff_release(_ch_info_tbl->_ch_num); _ch_info_tbl->_p_rcv_buf.len = 0; report_error(_ch_info_tbl->_ch_num, RE_NETWORK_LAYER, data_link_buf_ptr); break; /*2670*/ } return; } /*********************************************************************************************************************** * Function Name: _ether_rcv_arp * Description : * Arguments : * Return Value : ***********************************************************************************************************************/ void _ether_rcv_arp(void) { _ARP_ENTRY *ae; _ARP_PKT *rpap; uint16 i; uint32 ul_res; rpap = (_ARP_PKT *)(_ch_info_tbl->_p_rcv_buf.pip); /* Discard: exclude ARP packet addressed to itself */ ul_res = memcmp(rpap->ar_spa, _ch_info_tbl->_myipaddr, IP_ALEN); if ( ul_res == 0) /* colligion ip detect */ { if ((rpap->ar_op) == hs2net(AR_REPLY)) { callback_tcpip(_ch_info_tbl->_ch_num, ETHER_EV_COLLISION_IP, 0); } else { /* nothing to do */ } rcv_buff_release(_ch_info_tbl->_ch_num); _ch_info_tbl->_p_rcv_buf.len = 0; return; } else if (_cmp_ipaddr(&(rpap->ar_tpa), _ch_info_tbl->_myipaddr)) { rcv_buff_release(_ch_info_tbl->_ch_num); _ch_info_tbl->_p_rcv_buf.len = 0; return; } /* Check each field value */ if ((rpap->ar_hwtype != hs2net(AR_HARDWARE)) || (rpap->ar_prtype != hs2net(EPT_IP)) || (rpap->ar_hwlen != EP_ALEN) || (rpap->ar_prlen != IP_ALEN)) { rcv_buff_release(_ch_info_tbl->_ch_num); _ch_info_tbl->_p_rcv_buf.len = 0; report_error(_ch_info_tbl->_ch_num, RE_ARP_HEADER2, data_link_buf_ptr); return; } switch (rpap->ar_op) { /* ARP request: generate ARP response and transmit flag on and renew the ARP table */ case(hs2net(AR_REQUEST)): /* transmit flag on */ _ch_info_tbl->flag |= (_TCBF_NEED_SEND | _TCBF_SND_ARP_REP); /* generate packet process is in transmit process (this timing, only store the data) */ memcpy(_ch_info_tbl->arp_buff, rpap, sizeof(_ARP_PKT)); /* renew the ARP table */ _ether_arp_add(rpap->ar_spa, rpap->ar_sha); break; /* renew the ARP table when unresolved entry is exist */ case(hs2net(AR_REPLY)): /* Is unresolved entry exist? */ ae = _ether_arp_tbl[_ch_info_tbl->_ch_num]; for (i = 0; i < _ip_tblcnt[_ch_info_tbl->_ch_num]; i++, ae++) { if (ae->ae_state == AS_PENDING) { /* If yes, its reply? */ if (_cmp_ipaddr(ae->ae_pra, rpap->ar_spa) == 0) { /* If yes, resolve the entry */ _cpy_eaddr(ae->ae_hwa, rpap->ar_sha); ae->ae_ttl = ARP_TIMEOUT; ae->ae_state = AS_RESOLVED; } } } break; default: break; /*2670*/ } rcv_buff_release(_ch_info_tbl->_ch_num); _ch_info_tbl->_p_rcv_buf.len = 0; return; } #if defined(_ICMP) /*********************************************************************************************************************** * Function Name: _ether_arp_resolve * Description : * Arguments : * Return Value : ***********************************************************************************************************************/ void _ether_arp_resolve(void) { _ETH_HDR *peh; _IP_HDR *piph; piph = (_IP_HDR *)(_ch_info_tbl->_p_rcv_buf.pip); peh = (_ETH_HDR *)(data_link_buf_ptr); _ether_arp_add(piph->ip_src, peh->eh_src); return; } /*********************************************************************************************************************** * Function Name: _ether_proc_rcv * Description : * Arguments : * Return Value : ***********************************************************************************************************************/ sint16 _ether_snd_arp(_ARP_ENTRY *ae) { _ETH_HDR *peh; _ARP_PKT *rpap, *parp; sint16 ret; rpap = (_ARP_PKT *)(_ch_info_tbl->_p_rcv_buf.pip); rpap = (_ARP_PKT *)_ch_info_tbl->arp_buff; peh = &(_tx_hdr.eh); parp = &(_tx_hdr.ihdr.tarp); /* If ARP request, generate ARP packet */ if (_ch_info_tbl->flag & _TCBF_SND_ARP_REQ) { /* generate ARP packet */ parp->ar_hwtype = hs2net(HWT_ETH); parp->ar_prtype = hs2net(EPT_IP); parp->ar_hwlen = EP_ALEN; parp->ar_prlen = IP_ALEN; parp->ar_op = hs2net(AR_REQUEST); memcpy(parp->ar_sha, _myethaddr[_ch_info_tbl->_ch_num], EP_ALEN); _cpy_ipaddr(parp->ar_spa, _ch_info_tbl->_myipaddr); _cpy_eaddr(parp->ar_tha, ae->ae_hwa); _cpy_ipaddr(parp->ar_tpa, ae->ae_pra); _cpy_eaddr(peh->eh_dst, ae->ae_hwa); } /* If ARP response request, generate ARP packet using received ARP packet */ else if (_ch_info_tbl->flag & _TCBF_SND_ARP_REP) { _cpy_eaddr(parp, rpap); parp->ar_op = hs2net(AR_REPLY); memcpy(parp->ar_sha, _myethaddr[_ch_info_tbl->_ch_num], EP_ALEN); memcpy(parp->ar_spa, _ch_info_tbl->_myipaddr, IP_ALEN); memcpy(parp->ar_tha, rpap->ar_sha, EP_ALEN + IP_ALEN); _cpy_eaddr(peh->eh_dst, rpap->ar_sha); } else { return 0; } /*2669*/ _tx_hdr.hlen = _ETH_LEN + ARP_PLEN; ret = _ether_snd(EPT_ARP, NULL, 0); _ch_info_tbl->flag &= ~(_TCBF_SND_ARP_REQ | _TCBF_SND_ARP_REP); return ret; } #endif void ether_snd_gratuitous_arp(void) { _ARP_PKT *parp; const uint8_t bcastadr[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; parp = &(_tx_hdr.ihdr.tarp); parp->ar_hwtype = hs2net(HWT_ETH); parp->ar_prtype = hs2net(EPT_IP); parp->ar_hwlen = EP_ALEN; parp->ar_prlen = IP_ALEN; parp->ar_op = hs2net(AR_REQUEST); memcpy(parp->ar_sha, _myethaddr[_ch_info_tbl->_ch_num], EP_ALEN); /* senderHWaddrs is my ether addr */ _cpy_ipaddr(parp->ar_spa, _ch_info_tbl->_myipaddr); /* senderProtoAddrs is my ip addr */ _cpy_eaddr(parp->ar_tha, bcastadr); /* targetHWaddrs is broad cast addr */ _cpy_ipaddr(parp->ar_tpa, _ch_info_tbl->_myipaddr); /* targetProtoAddrs is my ip addr */ _tx_hdr.hlen = _ETH_LEN + ARP_PLEN; _ether_snd(EPT_ARP, NULL, 0); _ch_info_tbl->flag &= ~(_TCBF_SND_ARP_REQ | _TCBF_SND_ARP_REP); return; } void ether_snd_ip_reply_arp(void) { _ARP_PKT *parp; const uint8_t bcastadr[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; parp = &(_tx_hdr.ihdr.tarp); parp->ar_hwtype = hs2net(HWT_ETH); parp->ar_prtype = hs2net(EPT_IP); parp->ar_hwlen = EP_ALEN; parp->ar_prlen = IP_ALEN; parp->ar_op = hs2net(AR_REPLY); memcpy(parp->ar_sha, _myethaddr[_ch_info_tbl->_ch_num], EP_ALEN); /* senderHWaddrs is my ether addr */ _cpy_ipaddr(parp->ar_spa, _ch_info_tbl->_myipaddr); /* senderProtoAddrs is my ip addr */ _cpy_eaddr(parp->ar_tha, bcastadr); /* targetHWaddrs is b_cast */ _cpy_ipaddr(parp->ar_tpa, _ch_info_tbl->_myipaddr); /* targetProtoAddrs is my ip addr */ _tx_hdr.hlen = _ETH_LEN + ARP_PLEN; _ether_snd(EPT_ARP, NULL, 0); _ch_info_tbl->flag &= ~(_TCBF_SND_ARP_REQ | _TCBF_SND_ARP_REP); return; } /*********************************************************************************************************************** * Function Name: _ether_snd_ip * Description : * Arguments : * Return Value : ***********************************************************************************************************************/ sint16 _ether_snd_ip(uchar *data, uint16 dlen) { sint16 ret = 0; sint16 i; uint32 nexthop; uint32 tmp1; uchar eaddr[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; #if defined(_MULTI) uint32 addr; uint32 subnet_mask; uint32 broad_cast_addr = 0xffffffffu; static const uchar ip_broadcast[] = {0xff, 0xff, 0xff, 0xff}; #endif _ETH_HDR *peh; _ARP_ENTRY *ae; #if defined(_MULTI) net2hl_yn_xn(&addr, _tx_hdr.ihdr.tip.iph.ip_dst); net2hl_yn_xn(&subnet_mask, tcpudp_env[_ch_info_tbl->_ch_num].maskaddr); #endif peh = &(_tx_hdr.eh); /* Judge the destination is multicast or out of LAN (over G/W) */ _cpy_ipaddr(&tmp1, _tx_hdr.ihdr.tip.iph.ip_dst); #if defined(_MULTI) /* EX.XX.XX.XX (multicast) */ if ((*((uchar*)&tmp1) & 0xf0) == 0xe0) { _cpy_ipaddr(&nexthop, &tmp1); _tx_hdr.hlen += _ETH_LEN; ret = _ether_snd(EPT_IP, data, dlen); /* Return when multicast */ return ret; } /* 255.255.255.255 (broadcast) or (directed broadcast) */ else if (!memcmp(_tx_hdr.ihdr.tip.iph.ip_dst, ip_broadcast, 4) || ((addr & ~subnet_mask) == (broad_cast_addr & ~subnet_mask))) { /* Change the destination MAC address to broadcast address */ _tx_hdr.hlen += _ETH_LEN; ret = _ether_snd(EPT_IP, data, dlen); /* Return when broadcast */ return ret; } else { /* Normally sending */ } #endif /* If destination is in same network, nexthop is destination IP address directly */ if ((_ch_info_tbl->_myipaddr[0] & _ch_info_tbl->_mymaskaddr[0]) == (tmp1 & _ch_info_tbl->_mymaskaddr[0])) { _cpy_ipaddr(&nexthop, &tmp1); } /* If destination is out of same network, nexthop is G/W IP address */ else { if (_ch_info_tbl->_mygwaddr[0] != 0) { _cpy_ipaddr(&nexthop, _ch_info_tbl->_mygwaddr); } /*2669*/ else { return 0; } /*2669*/ } /* exist nexthop in ARP table? */ ae = _ether_arp_tbl[_ch_info_tbl->_ch_num]; for (i = 0; i < _ip_tblcnt[_ch_info_tbl->_ch_num]; i++, ae++) { if ((_cmp_ipaddr(&nexthop, ae->ae_pra)) == 0) { break; } /*2669*/ } if (i < _ip_tblcnt[_ch_info_tbl->_ch_num]) { /* If exist */ switch (ae->ae_state) { case AS_RESOLVED: _tx_hdr.hlen += _ETH_LEN; _cpy_eaddr(peh->eh_dst, ae->ae_hwa); ret = _ether_snd(EPT_IP, data, dlen); break; case AS_PENDING: /* Already ARP sent and waiting for resolve, return with no process */ return -1; case AS_TMOUT: /* ARP timeout */ return -2; } } /* If no exist */ else { /* Regist the new entry to the ARP table */ ae = _ether_arp_add((uchar *) & nexthop, eaddr); _ch_info_tbl->flag |= _TCBF_SND_ARP_REQ; _ether_snd_arp(ae); return -1; } return ret; } /*********************************************************************************************************************** * Function Name: _ether_snd * Description : * Arguments : * Return Value : ***********************************************************************************************************************/ sint16 _ether_snd(uint16 type, uchar *data, uint16 dlen) { _ETH_HDR *peh; sint16 plen, ret, i; uchar pad[_EP_PAD_MAX]; /* 0 padding data (max size if 18(_EP_PAD_MAX)) */ #if defined(_MULTI) _IP_HDR *piph; static const uchar eth_multi_addr[3] = {0x01, 0x00, 0x5e}; static const uchar eth_broadcast[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; static const uchar ip_broadcast[] = {0xff, 0xff, 0xff, 0xff}; uint32 addr; uint32 subnet_mask; uint32 broad_cast_addr = 0xffffffffu; #endif peh = &(_tx_hdr.eh); /* Generate Ethernet header */ memcpy(peh->eh_src, _myethaddr[_ch_info_tbl->_ch_num], EP_ALEN); peh->eh_type = hs2net(type); #if defined(_MULTI) if (type == EPT_IP) { /* If destination IP address is multicast, change the destination MAC address to for multicast */ piph = &_tx_hdr.ihdr.tip.iph; /* EX.XX.XX.XX (All Multicast) */ if ((piph->ip_dst[0] & 0xf0) == 0xE0) { /* Set the Internet multicast address (01-00-5e-00-00-00) and lower 23-bit destination IP address */ memcpy(peh->eh_dst, (const void*)eth_multi_addr, sizeof(eth_multi_addr)); memcpy(peh->eh_dst + sizeof(eth_multi_addr), piph->ip_dst + 1, 3); /* clear the bit-24 */ peh->eh_dst[3] &= 0x7f; } /* If destination IP address is broadcast, change the destination MAC address to for broadcast */ /* 255.255.255.255 (broadcast) */ if (!memcmp(piph->ip_dst, ip_broadcast, 4)) { memcpy(peh->eh_dst, eth_broadcast, EP_ALEN); } net2hl_yn_xn(&addr, piph->ip_dst); net2hl_yn_xn(&subnet_mask, tcpudp_env[_ch_info_tbl->_ch_num].maskaddr); /* (directed broadcast) */ if ((addr & ~subnet_mask) == (broad_cast_addr & ~subnet_mask)) { memcpy(peh->eh_dst, eth_broadcast, EP_ALEN); } } #endif /* 0 padding when the packet length is less than 60 byte */ if ((_tx_hdr.hlen + dlen) < _EP_MIN_LEN) { plen = _EP_MIN_LEN - (_tx_hdr.hlen + dlen); /* copy the data to temporarily area for padding */ memcpy(pad, data, dlen); for (i = 0; i < plen; i++) { pad[dlen+i] = 0; } /*2669*/ /* call the transmit function */ ret = lan_write(_ch_info_tbl->_ch_num, (B*) & _tx_hdr, \ (H)_tx_hdr.hlen, (B*)pad, (H)(_EP_MIN_LEN - _tx_hdr.hlen)); } else /* call the transmit function */ ret = lan_write(_ch_info_tbl->_ch_num, (B *) & _tx_hdr, (H)_tx_hdr.hlen, (B*)data, (H)dlen); /* 0: transmit complete */ if (ret == 0) { return 0; } else { return -1; } /*2669*/ } /*********************************************************************************************************************** * Function Name: _ether_arp_add * Description : * Arguments : * Return Value : ***********************************************************************************************************************/ _ARP_ENTRY *_ether_arp_add(uchar *ipaddr, uchar *ethaddr) { sint16 i; uint16 tmp_ttl = ARP_TIMEOUT; uchar bcast[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; _ARP_ENTRY *ae, *ae_tmp, *ae_tmp2; /* Search the existed entry */ ae_tmp = NULL; ae = _ether_arp_tbl[_ch_info_tbl->_ch_num]; for (i = 0; i < _ip_tblcnt[_ch_info_tbl->_ch_num]; i++, ae++) { if ((_cmp_ipaddr(ipaddr, ae->ae_pra)) == 0) { /* If the resolved entry is already exist */ if (ae->ae_state == AS_RESOLVED) { /* renew the TTL */ ae->ae_ttl = ARP_TIMEOUT; } /* If the entry is already exist but not resoleved */ else { memcpy(ae->ae_hwa, ethaddr, EP_ALEN); ae->ae_ttl = ARP_TIMEOUT; ae->ae_state = AS_RESOLVED; } return ae; } else if (ae->ae_state == AS_FREE) { ae_tmp = ae; } /*2669*/ } /* Delete the most old entry if FREE entry is not exist */ if (ae_tmp == NULL) { ae_tmp2 = NULL; /* Select the most smallest TTL */ ae = _ether_arp_tbl[_ch_info_tbl->_ch_num]; for (i = 0; i < _ip_tblcnt[_ch_info_tbl->_ch_num]; i++, ae++) { if (ae->ae_state == AS_RESOLVED) { if (ae->ae_ttl <= tmp_ttl) { tmp_ttl = ae->ae_ttl; ae_tmp = ae; } } else if (ae->ae_state & (AS_PENDING | AS_TMOUT)) { ae_tmp2 = ae; } /*2669*/ } if (ae_tmp != NULL) { ae = ae_tmp; } else { ae = ae_tmp2; } /*2669*/ /* Delete the selected entry */ _ether_arp_del(ae); } /* If FREE entry is exist, use this */ else { ae = ae_tmp; } /*2669*/ memcpy(ae->ae_pra, ipaddr, IP_ALEN); memcpy(ae->ae_hwa, ethaddr, EP_ALEN); ae->ae_ttl = ARP_TIMEOUT; /* If MAC address is all 'f', change the status to PENDING */ if (memcmp(ethaddr, bcast, EP_ALEN) == 0) { ae->ae_state = AS_PENDING; ae->ae_attempts = ARP_MAXRETRY; } else { ae->ae_state = AS_RESOLVED; /* Do not use MAXRETRY when RESOLEVED */ } return ae; } /*********************************************************************************************************************** * Function Name: _ether_arp_del * Description : * Arguments : * Return Value : ***********************************************************************************************************************/ void _ether_arp_del(_ARP_ENTRY *ae) { memset(ae->ae_pra, 0, sizeof(_ARP_ENTRY)); return; } /*********************************************************************************************************************** * Function Name: _ether_arp_init * Description : * Arguments : * Return Value : ***********************************************************************************************************************/ void _ether_arp_init(void) { uint16 counter; _ARP_ENTRY *ae; /* table clear for all channels */ for (counter = 0; counter < _t4_channel_num; counter++) { ae = _ether_arp_tbl[counter]; memset(ae->ae_pra, 0, (sizeof(_ARP_ENTRY) * _ip_tblcnt[counter])); } return; } ER callback_tcpip(UB channel, UW eventid, VP param) { if (eventid == ETHER_EV_LINK_ON) { _ch_info_head[channel].etherlink = 1; } else if (eventid == ETHER_EV_LINK_OFF) { _ch_info_head[channel].etherlink = 0; } /// if (0 != g_fp_user) /// { /// g_fp_user(channel, eventid, param); /// } if (1 == _t4_dhcp_enable) { dhcp_callback_from_ether(channel, eventid, param); } return 0; }
35.387363
121
0.46751
e98acc78f4a0aa461d719ab185fa5b2093518986
8,309
h
C
include/mkl_poisson.h
ziyu123/kaldi_feature
69fe7f1eb19fb954906f469a1abac40ca425fa2f
[ "Apache-2.0" ]
4
2020-03-13T11:24:22.000Z
2020-11-20T11:25:09.000Z
include/mkl_poisson.h
ziyu123/kaldi_feature
69fe7f1eb19fb954906f469a1abac40ca425fa2f
[ "Apache-2.0" ]
3
2020-04-09T12:32:18.000Z
2021-02-20T13:02:06.000Z
include/mkl_poisson.h
ziyu123/kaldi_feature
69fe7f1eb19fb954906f469a1abac40ca425fa2f
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* ! Copyright(C) 2007-2015 Intel Corporation. All Rights Reserved. ! ! The source code, information and material ("Material") contained herein is ! owned by Intel Corporation or its suppliers or licensors, and title to such ! Material remains with Intel Corporation or its suppliers or licensors. The ! Material contains proprietary information of Intel or its suppliers and ! licensors. The Material is protected by worldwide copyright laws and treaty ! provisions. No part of the Material may be used, copied, reproduced, ! modified, published, uploaded, posted, transmitted, distributed or disclosed ! in any way without Intel's prior express written permission. No license ! under any patent, copyright or other intellectual property rights in the ! Material is granted to or conferred upon you, either expressly, by ! implication, inducement, estoppel or otherwise. Any license under such ! intellectual property rights must be express and approved by Intel in ! writing. ! ! *Third Party trademarks are the property of their respective owners. ! ! Unless otherwise agreed by Intel in writing, you may not remove or alter ! this notice or any other notice embedded in Materials by Intel or Intel's ! suppliers or licensors in any way. ! !*******************************************************************************/ #ifndef _MKL_POISSON_H_ #define _MKL_POISSON_H_ /* definitions of MKL types */ #include "mkl_types.h" #include "mkl_dfti.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /** #if defined( _WIN32 ) || ( _WIN64 ) #define d_init_Helmholtz_2D D_INIT_HELMHOLTZ_2D #define d_commit_Helmholtz_2D D_COMMIT_HELMHOLTZ_2D #define d_Helmholtz_2D D_HELMHOLTZ_2D #define free_Helmholtz_2D FREE_HELMHOLTZ_2D #define d_init_Helmholtz_3D D_INIT_HELMHOLTZ_3D #define d_commit_Helmholtz_3D D_COMMIT_HELMHOLTZ_3D #define d_Helmholtz_3D D_HELMHOLTZ_3D #define free_Helmholtz_3D FREE_HELMHOLTZ_3D #define s_init_Helmholtz_2D S_INIT_HELMHOLTZ_2D #define s_commit_Helmholtz_2D S_COMMIT_HELMHOLTZ_2D #define s_Helmholtz_2D S_HELMHOLTZ_2D #define s_init_Helmholtz_3D S_INIT_HELMHOLTZ_3D #define s_commit_Helmholtz_3D S_COMMIT_HELMHOLTZ_3D #define s_Helmholtz_3D S_HELMHOLTZ_3D #define d_init_sph_p D_INIT_SPH_P #define d_commit_sph_p D_COMMIT_SPH_P #define d_sph_p D_SPH_P #define free_sph_p FREE_SPH_P #define d_init_sph_np D_INIT_SPH_NP #define d_commit_sph_np D_COMMIT_SPH_NP #define d_sph_np D_SPH_NP #define free_sph_np FREE_SPH_NP #define s_init_sph_p S_INIT_SPH_P #define s_commit_sph_p S_COMMIT_SPH_P #define s_sph_p S_SPH_P #define s_init_sph_np S_INIT_SPH_NP #define s_commit_sph_np S_COMMIT_SPH_NP #define s_sph_np S_SPH_NP #else #define d_init_Helmholtz_2D d_init_helmholtz_2d_ #define d_commit_Helmholtz_2D d_commit_helmholtz_2d_ #define d_Helmholtz_2D d_helmholtz_2d_ #define free_Helmholtz_2D free_helmholtz_2d_ #define d_init_Helmholtz_3D d_init_helmholtz_3d_ #define d_commit_Helmholtz_3D d_commit_helmholtz_3d_ #define d_Helmholtz_3D d_helmholtz_3d_ #define free_Helmholtz_3D free_helmholtz_3d_ #define s_init_Helmholtz_2D s_init_helmholtz_2d_ #define s_commit_Helmholtz_2D s_commit_helmholtz_2d_ #define s_Helmholtz_2D s_helmholtz_2d_ #define s_init_Helmholtz_3D s_init_helmholtz_3d_ #define s_commit_Helmholtz_3D s_commit_helmholtz_3d_ #define s_Helmholtz_3D s_helmholtz_3d_ #define d_init_sph_p d_init_sph_p_ #define d_commit_sph_p d_commit_sph_p_ #define d_sph_p d_sph_p_ #define free_sph_p free_sph_p_ #define d_init_sph_np d_init_sph_np_ #define d_commit_sph_np d_commit_sph_np_ #define d_sph_np d_sph_np_ #define free_sph_np free_sph_np_ #define s_init_sph_p s_init_sph_p_ #define s_commit_sph_p s_commit_sph_p_ #define s_sph_p s_sph_p_ #define s_init_sph_np s_init_sph_np_ #define s_commit_sph_np s_commit_sph_np_ #define s_sph_np s_sph_np_ #endif **/ /**/ #define d_init_Helmholtz_2D d_init_helmholtz_2d #define d_commit_Helmholtz_2D d_commit_helmholtz_2d #define d_Helmholtz_2D d_helmholtz_2d #define free_Helmholtz_2D free_helmholtz_2d #define d_init_Helmholtz_3D d_init_helmholtz_3d #define d_commit_Helmholtz_3D d_commit_helmholtz_3d #define d_Helmholtz_3D d_helmholtz_3d #define free_Helmholtz_3D free_helmholtz_3d #define s_init_Helmholtz_2D s_init_helmholtz_2d #define s_commit_Helmholtz_2D s_commit_helmholtz_2d #define s_Helmholtz_2D s_helmholtz_2d #define s_init_Helmholtz_3D s_init_helmholtz_3d #define s_commit_Helmholtz_3D s_commit_helmholtz_3d #define s_Helmholtz_3D s_helmholtz_3d /**/ void d_init_Helmholtz_2D(double*,double*,double*,double*,MKL_INT*,MKL_INT*,char*,double*,MKL_INT*,double*,MKL_INT*); void d_commit_Helmholtz_2D(double*,double*,double*,double*,double*,DFTI_DESCRIPTOR_HANDLE *,MKL_INT*,double*,MKL_INT*); void d_Helmholtz_2D(double*,double*,double*,double*,double*,DFTI_DESCRIPTOR_HANDLE *,MKL_INT*,double*,MKL_INT*); void free_Helmholtz_2D(DFTI_DESCRIPTOR_HANDLE*,MKL_INT*,MKL_INT*); void d_init_Helmholtz_3D(double*,double*,double*,double*,double*,double*,MKL_INT*,MKL_INT*,MKL_INT*,char*,double*,MKL_INT*,double*,MKL_INT*); void d_commit_Helmholtz_3D(double*,double*,double*,double*,double*,double*,double*,DFTI_DESCRIPTOR_HANDLE*,DFTI_DESCRIPTOR_HANDLE*,MKL_INT*,double*,MKL_INT*); void d_Helmholtz_3D(double*,double*,double*,double*,double*,double*,double*,DFTI_DESCRIPTOR_HANDLE*,DFTI_DESCRIPTOR_HANDLE*,MKL_INT*,double*,MKL_INT*); void free_Helmholtz_3D(DFTI_DESCRIPTOR_HANDLE*,DFTI_DESCRIPTOR_HANDLE*,MKL_INT*,MKL_INT*); void s_init_Helmholtz_2D(float*,float*,float*,float*,MKL_INT*,MKL_INT*,char*,float*,MKL_INT*,float*,MKL_INT*); void s_commit_Helmholtz_2D(float*,float*,float*,float*,float*,DFTI_DESCRIPTOR_HANDLE *,MKL_INT*,float*,MKL_INT*); void s_Helmholtz_2D(float*,float*,float*,float*,float*,DFTI_DESCRIPTOR_HANDLE *,MKL_INT*,float*,MKL_INT*); void s_init_Helmholtz_3D(float*,float*,float*,float*,float*,float*,MKL_INT*,MKL_INT*,MKL_INT*,char*,float*,MKL_INT*,float*,MKL_INT*); void s_commit_Helmholtz_3D(float*,float*,float*,float*,float*,float*,float*,DFTI_DESCRIPTOR_HANDLE*,DFTI_DESCRIPTOR_HANDLE*,MKL_INT*,float*,MKL_INT*); void s_Helmholtz_3D(float*,float*,float*,float*,float*,float*,float*,DFTI_DESCRIPTOR_HANDLE*,DFTI_DESCRIPTOR_HANDLE*,MKL_INT*,float*,MKL_INT*); void d_init_sph_p(double*,double*,double*,double*,MKL_INT*,MKL_INT*,double*,MKL_INT*,double*,MKL_INT*); void d_commit_sph_p(double*,DFTI_DESCRIPTOR_HANDLE*,DFTI_DESCRIPTOR_HANDLE*,MKL_INT*,double*,MKL_INT*); void d_sph_p(double*,DFTI_DESCRIPTOR_HANDLE*,DFTI_DESCRIPTOR_HANDLE*,MKL_INT*,double*,MKL_INT*); void free_sph_p(DFTI_DESCRIPTOR_HANDLE*,DFTI_DESCRIPTOR_HANDLE*,MKL_INT*,MKL_INT*); void d_init_sph_np(double*,double*,double*,double*,MKL_INT*,MKL_INT*,double*,MKL_INT*,double*,MKL_INT*); void d_commit_sph_np(double*,DFTI_DESCRIPTOR_HANDLE*,MKL_INT*,double*,MKL_INT*); void d_sph_np(double*,DFTI_DESCRIPTOR_HANDLE*,MKL_INT*,double*,MKL_INT*); void free_sph_np(DFTI_DESCRIPTOR_HANDLE*,MKL_INT*,MKL_INT*); void s_init_sph_p(float*,float*,float*,float*,MKL_INT*,MKL_INT*,float*,MKL_INT*,float*,MKL_INT*); void s_commit_sph_p(float*,DFTI_DESCRIPTOR_HANDLE*,DFTI_DESCRIPTOR_HANDLE*,MKL_INT*,float*,MKL_INT*); void s_sph_p(float*,DFTI_DESCRIPTOR_HANDLE*,DFTI_DESCRIPTOR_HANDLE*,MKL_INT*,float*,MKL_INT*); void s_init_sph_np(float*,float*,float*,float*,MKL_INT*,MKL_INT*,float*,MKL_INT*,float*,MKL_INT*); void s_commit_sph_np(float*,DFTI_DESCRIPTOR_HANDLE*,MKL_INT*,float*,MKL_INT*); void s_sph_np(float*,DFTI_DESCRIPTOR_HANDLE*,MKL_INT*,float*,MKL_INT*); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* _MKL_POISSON_H_ */
46.679775
158
0.743892
3a13c91642232f449a1dbda7b9150343e53258e0
410
c
C
pam_bio.c
ccat3z/pam_bio
3f2d105ff25905a212f88600e98106cd4d44c28c
[ "MIT" ]
1
2021-07-07T23:46:43.000Z
2021-07-07T23:46:43.000Z
pam_bio.c
ccat3z/pam_bio
3f2d105ff25905a212f88600e98106cd4d44c28c
[ "MIT" ]
null
null
null
pam_bio.c
ccat3z/pam_bio
3f2d105ff25905a212f88600e98106cd4d44c28c
[ "MIT" ]
null
null
null
#include <security/pam_modules.h> #include <glib.h> extern int do_authenticate (pam_handle_t* pamh, int flags, gint argc, gchar** argv); PAM_EXTERN int pam_sm_authenticate (pam_handle_t* pamh, int flags, int argc, const char** argv) { return do_authenticate(pamh, flags, argc, argv); } PAM_EXTERN int pam_sm_setcred(pam_handle_t *pamh, int flags, int argc, const char **argv) { return PAM_SUCCESS; }
34.166667
97
0.746341
b16f8cc596f0a4b03bc83d69e0ec80691114753b
1,704
h
C
src/os/aix/sigar_os.h
timwr/sigar
b08b66d81604d716a68db1b89b10deb8971532bd
[ "Apache-2.0" ]
4
2017-05-20T00:45:11.000Z
2020-11-24T23:07:00.000Z
src/os/aix/sigar_os.h
timwr/sigar
b08b66d81604d716a68db1b89b10deb8971532bd
[ "Apache-2.0" ]
3
2016-07-20T20:16:58.000Z
2017-02-19T13:41:28.000Z
src/os/aix/sigar_os.h
timwr/sigar
b08b66d81604d716a68db1b89b10deb8971532bd
[ "Apache-2.0" ]
4
2018-03-06T18:55:30.000Z
2020-11-24T23:06:07.000Z
/* * Copyright (c) 2004-2007, 2009 Hyperic, Inc. * Copyright (c) 2009 SpringSource, Inc. * Copyright (c) 2010 VMware, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SIGAR_OS_H #define SIGAR_OS_H #include <fcntl.h> #include <errno.h> #include <dlfcn.h> #include <procinfo.h> #include <sys/resource.h> enum { KOFFSET_LOADAVG, KOFFSET_VAR, KOFFSET_SYSINFO, KOFFSET_IFNET, KOFFSET_VMINFO, KOFFSET_CPUINFO, KOFFSET_TCB, KOFFSET_ARPTABSIZE, KOFFSET_ARPTABP, KOFFSET_MAX }; typedef struct { time_t mtime; int num; char **devs; } swaps_t; typedef int (*proc_fd_func_t) (sigar_t *, sigar_pid_t, sigar_proc_fd_t *); struct sigar_t { SIGAR_T_BASE; int kmem; /* offsets for seeking on kmem */ long koffsets[KOFFSET_MAX]; proc_fd_func_t getprocfd; int pagesize; swaps_t swaps; time_t last_getprocs; sigar_pid_t last_pid; struct procsinfo64 *pinfo; struct cpuinfo *cpuinfo; int cpuinfo_size; int cpu_mhz; char model[128]; int aix_version; int thrusage; sigar_cache_t *diskmap; }; #define SIGAR_EPERM_KMEM (SIGAR_OS_START_ERROR+EACCES) #endif /* SIGAR_OS_H */
23.666667
75
0.703638
38e350a9d19f825ec5de365b41557dabd9b6b4ce
786
h
C
src/naive_kernel_kmeans.h
jutinguely/fast-kmeans
0f0034851653875f8a8627aab76603c8171f9593
[ "MIT" ]
35
2018-05-10T19:50:20.000Z
2022-03-21T06:41:19.000Z
src/naive_kernel_kmeans.h
jutinguely/fast-kmeans
0f0034851653875f8a8627aab76603c8171f9593
[ "MIT" ]
14
2018-05-10T20:19:18.000Z
2019-06-04T16:19:11.000Z
src/naive_kernel_kmeans.h
jutinguely/fast-kmeans
0f0034851653875f8a8627aab76603c8171f9593
[ "MIT" ]
6
2018-11-01T10:52:11.000Z
2021-08-09T20:46:02.000Z
#ifndef NAIVE_KERNEL_KMEANS_H #define NAIVE_KERNEL_KMEANS_H /* Authors: Greg Hamerly and Jonathan Drake * Feedback: hamerly@cs.baylor.edu * See: http://cs.baylor.edu/~hamerly/software/kmeans.php * Copyright 2014 * * NaiveKernelKmeans is a kernelized k-means algorithm that has no acceleration * applied. */ #include "kernel_kmeans.h" class NaiveKernelKmeans : public KernelKmeans { public: NaiveKernelKmeans(Kernel const *k) : KernelKmeans(k) {} virtual ~NaiveKernelKmeans() { free(); } virtual std::string getName() const { std::ostringstream out; out << "naive_kernel(" << kernel.getName() << ")"; return out.str(); } protected: int runThread(int threadId, int maxIterations); }; #endif
25.354839
79
0.660305
cedda4a1c3785c11f28caf76b986391613f992e7
371
c
C
string/strtok.c
msathieu/freestanding-libc
0977c926fb4f6cfdaea6641b2bf5a4d877db2060
[ "Unlicense" ]
1
2021-12-15T02:51:49.000Z
2021-12-15T02:51:49.000Z
string/strtok.c
msathieu/freestanding-libc
0977c926fb4f6cfdaea6641b2bf5a4d877db2060
[ "Unlicense" ]
1
2021-10-06T03:06:28.000Z
2021-12-21T10:53:55.000Z
string/strtok.c
msathieu/freestanding-libc
0977c926fb4f6cfdaea6641b2bf5a4d877db2060
[ "Unlicense" ]
null
null
null
#include <string.h> char* strtok(char* restrict new_str, const char* restrict sep) { static char* str; if (new_str) { str = new_str; } else if (!str) { return 0; } str += strspn(str, sep); if (!str[0]) { return 0; } char* return_value = str; str += strcspn(str, sep); if (str[0]) { str[0] = 0; str++; } return return_value; }
16.863636
64
0.555256
331506215bf61b97ce711449d99f90800d17e870
2,514
h
C
code/wxWidgets/include/wx/motif/control.h
Bloodknight/NeuTorsion
a5890e9ca145a8c1b6bec7b70047a43d9b1c29ea
[ "MIT" ]
38
2016-02-20T02:46:28.000Z
2021-11-17T11:39:57.000Z
code/wxWidgets/include/wx/motif/control.h
Dwarf-King/TorsionEditor
e6887d1661ebaf4ccbf1d09f2690e2bf805fbb50
[ "MIT" ]
17
2016-02-20T02:19:55.000Z
2021-02-08T15:15:17.000Z
code/wxWidgets/include/wx/motif/control.h
Dwarf-King/TorsionEditor
e6887d1661ebaf4ccbf1d09f2690e2bf805fbb50
[ "MIT" ]
46
2016-02-20T02:47:33.000Z
2021-01-31T15:46:05.000Z
///////////////////////////////////////////////////////////////////////////// // Name: control.h // Purpose: wxControl class // Author: Julian Smart // Modified by: // Created: 17/09/98 // RCS-ID: $Id: control.h,v 1.17 2004/05/23 20:51:22 JS Exp $ // Copyright: (c) Julian Smart // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #ifndef _WX_CONTROL_H_ #define _WX_CONTROL_H_ #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA) #pragma interface "control.h" #endif #include "wx/window.h" #include "wx/list.h" #include "wx/validate.h" // General item class class WXDLLEXPORT wxControl: public wxControlBase { DECLARE_ABSTRACT_CLASS(wxControl) public: wxControl(); wxControl( wxWindow *parent, wxWindowID id, const wxPoint &pos = wxDefaultPosition, const wxSize &size = wxDefaultSize, long style = 0, const wxValidator& validator = wxDefaultValidator, const wxString &name = wxControlNameStr ) { Create(parent, id, pos, size, style, validator, name); } bool Create(wxWindow *parent, wxWindowID id, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = 0, const wxValidator& validator = wxDefaultValidator, const wxString& name = wxControlNameStr); // simulates the event, returns true if the event was processed virtual void Command(wxCommandEvent& WXUNUSED(event)) { } // calls the callback and appropriate event handlers, returns true if // event was processed virtual bool ProcessCommand(wxCommandEvent& event); virtual void SetLabel(const wxString& label); virtual wxString GetLabel() const ; bool InSetValue() const { return m_inSetValue; } protected: // calls wxControlBase::CreateControl, also sets foreground, background and // font to parent's values bool CreateControl(wxWindow *parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxValidator& validator, const wxString& name); // native implementation using XtQueryGeometry virtual wxSize DoGetBestSize() const; // Motif: prevent callbacks being called while in SetValue bool m_inSetValue; DECLARE_EVENT_TABLE() }; #endif // _WX_CONTROL_H_
31.037037
79
0.603023
89ace28d71b69d3e39c1abe965e55581fba2ab44
267
c
C
internal/ccall/pathplan.c
edamato/go-graphviz
c6e832de6f05c754b430d996f3493d507ab7061a
[ "MIT" ]
343
2020-01-28T15:13:22.000Z
2022-03-29T08:03:06.000Z
internal/ccall/pathplan.c
edamato/go-graphviz
c6e832de6f05c754b430d996f3493d507ab7061a
[ "MIT" ]
31
2020-02-21T16:09:37.000Z
2022-03-29T12:23:19.000Z
internal/ccall/pathplan.c
edamato/go-graphviz
c6e832de6f05c754b430d996f3493d507ab7061a
[ "MIT" ]
38
2020-02-05T11:09:55.000Z
2022-03-23T19:09:03.000Z
#include "pathplan/cvt.c" #include "pathplan/inpoly.c" #include "pathplan/route.c" #include "pathplan/shortest.c" #include "pathplan/shortestpth.c" #include "pathplan/solvers.c" #include "pathplan/triang.c" #include "pathplan/util.c" #include "pathplan/visibility.c"
26.7
33
0.764045
e4b9ad02409db96b0362788f23bf35b8259d35bc
3,857
h
C
ash/shelf/dimmer_view.h
xzhan96/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2018-02-22T18:06:56.000Z
2021-08-28T12:49:27.000Z
ash/shelf/dimmer_view.h
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
ash/shelf/dimmer_view.h
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2017-08-16T08:15:01.000Z
2018-03-27T00:07:30.000Z
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_SHELF_DIMMER_VIEW_H_ #define ASH_SHELF_DIMMER_VIEW_H_ #include "ash/common/shelf/wm_dimmer_view.h" #include "ash/common/wm/background_animator.h" #include "ash/common/wm_window_observer.h" #include "base/macros.h" #include "ui/events/event_handler.h" #include "ui/views/view.h" #include "ui/views/widget/widget_delegate.h" namespace ash { class WmShelf; // DimmerView slightly dims shelf items when a window is maximized and visible. // TODO(jamescook): Delete this after material design ships, as MD will not // require shelf dimming. http://crbug.com/614453 class DimmerView : public views::View, public views::WidgetDelegate, public BackgroundAnimatorDelegate, public WmDimmerView, public WmWindowObserver { public: // Creates and shows a DimmerView and its Widget. The returned view is owned // by its widget. If |disable_animations_for_test| is set, all changes apply // instantly. static DimmerView* Create(WmShelf* shelf, bool disable_animations_for_test); // Called by |DimmerEventFilter| when the mouse |hovered| state changes. void SetHovered(bool hovered); // views::View overrides: void OnPaintBackground(gfx::Canvas* canvas) override; // views::WidgetDelegate overrides: views::Widget* GetWidget() override; const views::Widget* GetWidget() const override; // BackgroundAnimatorDelegate overrides: void UpdateBackground(BackgroundAnimator* animator, int alpha) override; void BackgroundAnimationEnded(BackgroundAnimator* animator) override; // WmDimmerView: views::Widget* GetDimmerWidget() override; void ForceUndimming(bool force) override; int GetDimmingAlphaForTest() override; // WmWindowObserver overrides: // This will be called when the shelf itself changes its absolute position. // Since the |dimmer_| panel needs to be placed in screen coordinates it needs // to be repositioned. The difference to the OnBoundsChanged call above is // that this gets also triggered when the shelf only moves. void OnWindowBoundsChanged(WmWindow* window, const gfx::Rect& old_bounds, const gfx::Rect& new_bounds) override; private: DimmerView(WmShelf* shelf, bool disable_animations_for_test); ~DimmerView() override; // This class monitors mouse events to see if it is on top of the shelf. class DimmerEventFilter : public ui::EventHandler { public: explicit DimmerEventFilter(DimmerView* owner); ~DimmerEventFilter() override; // Overridden from ui::EventHandler: void OnMouseEvent(ui::MouseEvent* event) override; void OnTouchEvent(ui::TouchEvent* event) override; private: // The owning class. DimmerView* owner_; // True if the mouse is inside the shelf. bool mouse_inside_; // True if a touch event is inside the shelf. bool touch_inside_; DISALLOW_COPY_AND_ASSIGN(DimmerEventFilter); }; // The shelf that uses this dimmer. WmShelf* shelf_; // The alpha to use for covering the shelf. int alpha_; // True if the event filter claims that we should not be dimmed. bool is_hovered_; // True if someone forces us not to be dimmed (e.g. a menu is open). bool force_hovered_; // True if animations should be suppressed for a test. bool disable_animations_for_test_; // The animator for the background transitions. BackgroundAnimator background_animator_; // Notification of entering / exiting of the shelf area by mouse. std::unique_ptr<DimmerEventFilter> event_filter_; DISALLOW_COPY_AND_ASSIGN(DimmerView); }; } // namespace ash #endif // ASH_SHELF_DIMMER_VIEW_H_
33.25
80
0.730101
904c5e439ecaeea84bcc1596564f56755023cf53
7,848
c
C
RRC_Rel14/LTE_CarrierFreqUTRA-TDD-r12.c
brainliubo/openairstudy
8c1f64d00dcf0fbc6efb4e49d30ce2944f512c69
[ "Apache-2.0" ]
1
2020-07-08T03:56:32.000Z
2020-07-08T03:56:32.000Z
RRC_Rel14/LTE_CarrierFreqUTRA-TDD-r12.c
brainliubo/openairstudy
8c1f64d00dcf0fbc6efb4e49d30ce2944f512c69
[ "Apache-2.0" ]
null
null
null
RRC_Rel14/LTE_CarrierFreqUTRA-TDD-r12.c
brainliubo/openairstudy
8c1f64d00dcf0fbc6efb4e49d30ce2944f512c69
[ "Apache-2.0" ]
null
null
null
/* * Generated by asn1c-0.9.29 (http://lionet.info/asn1c) * From ASN.1 module "EUTRA-RRC-Definitions" * found in "/home/guicliu/ue_folder/openair2/RRC/LTE/MESSAGES/asn1c/ASN1_files/lte-rrc-14.7.0.asn1" * `asn1c -pdu=all -fcompound-names -gen-PER -no-gen-OER -no-gen-example -D /home/guicliu/ue_folder/cmake_targets/lte_noS1_build_oai/build/CMakeFiles/RRC_Rel14` */ #include "LTE_CarrierFreqUTRA-TDD-r12.h" /* * This type is implemented using NativeEnumerated, * so here we adjust the DEF accordingly. */ static int memb_LTE_q_RxLevMin_r12_constraint_1(const asn_TYPE_descriptor_t *td, const void *sptr, asn_app_constraint_failed_f *ctfailcb, void *app_key) { long value; if(!sptr) { ASN__CTFAIL(app_key, td, sptr, "%s: value not given (%s:%d)", td->name, __FILE__, __LINE__); return -1; } value = *(const long *)sptr; if((value >= -60 && value <= -13)) { /* Constraint check succeeded */ return 0; } else { ASN__CTFAIL(app_key, td, sptr, "%s: constraint failed (%s:%d)", td->name, __FILE__, __LINE__); return -1; } } static int memb_LTE_p_MaxUTRA_r12_constraint_1(const asn_TYPE_descriptor_t *td, const void *sptr, asn_app_constraint_failed_f *ctfailcb, void *app_key) { long value; if(!sptr) { ASN__CTFAIL(app_key, td, sptr, "%s: value not given (%s:%d)", td->name, __FILE__, __LINE__); return -1; } value = *(const long *)sptr; if((value >= -50 && value <= 33)) { /* Constraint check succeeded */ return 0; } else { ASN__CTFAIL(app_key, td, sptr, "%s: constraint failed (%s:%d)", td->name, __FILE__, __LINE__); return -1; } } static asn_per_constraints_t asn_PER_type_LTE_reducedMeasPerformance_r12_constr_8 CC_NOTUSED = { { APC_CONSTRAINED, 0, 0, 0, 0 } /* (0..0) */, { APC_UNCONSTRAINED, -1, -1, 0, 0 }, 0, 0 /* No PER value map */ }; static asn_per_constraints_t asn_PER_memb_LTE_q_RxLevMin_r12_constr_6 CC_NOTUSED = { { APC_CONSTRAINED, 6, 6, -60, -13 } /* (-60..-13) */, { APC_UNCONSTRAINED, -1, -1, 0, 0 }, 0, 0 /* No PER value map */ }; static asn_per_constraints_t asn_PER_memb_LTE_p_MaxUTRA_r12_constr_7 CC_NOTUSED = { { APC_CONSTRAINED, 7, 7, -50, 33 } /* (-50..33) */, { APC_UNCONSTRAINED, -1, -1, 0, 0 }, 0, 0 /* No PER value map */ }; static const asn_INTEGER_enum_map_t asn_MAP_LTE_reducedMeasPerformance_r12_value2enum_8[] = { { 0, 4, "true" } }; static const unsigned int asn_MAP_LTE_reducedMeasPerformance_r12_enum2value_8[] = { 0 /* true(0) */ }; static const asn_INTEGER_specifics_t asn_SPC_LTE_reducedMeasPerformance_r12_specs_8 = { asn_MAP_LTE_reducedMeasPerformance_r12_value2enum_8, /* "tag" => N; sorted by tag */ asn_MAP_LTE_reducedMeasPerformance_r12_enum2value_8, /* N => "tag"; sorted by N */ 1, /* Number of elements in the maps */ 0, /* Enumeration is not extensible */ 1, /* Strict enumeration */ 0, /* Native long size */ 0 }; static const ber_tlv_tag_t asn_DEF_LTE_reducedMeasPerformance_r12_tags_8[] = { (ASN_TAG_CLASS_CONTEXT | (6 << 2)), (ASN_TAG_CLASS_UNIVERSAL | (10 << 2)) }; static /* Use -fall-defs-global to expose */ asn_TYPE_descriptor_t asn_DEF_LTE_reducedMeasPerformance_r12_8 = { "reducedMeasPerformance-r12", "reducedMeasPerformance-r12", &asn_OP_NativeEnumerated, asn_DEF_LTE_reducedMeasPerformance_r12_tags_8, sizeof(asn_DEF_LTE_reducedMeasPerformance_r12_tags_8) /sizeof(asn_DEF_LTE_reducedMeasPerformance_r12_tags_8[0]) - 1, /* 1 */ asn_DEF_LTE_reducedMeasPerformance_r12_tags_8, /* Same as above */ sizeof(asn_DEF_LTE_reducedMeasPerformance_r12_tags_8) /sizeof(asn_DEF_LTE_reducedMeasPerformance_r12_tags_8[0]), /* 2 */ { 0, &asn_PER_type_LTE_reducedMeasPerformance_r12_constr_8, NativeEnumerated_constraint }, 0, 0, /* Defined elsewhere */ &asn_SPC_LTE_reducedMeasPerformance_r12_specs_8 /* Additional specs */ }; asn_TYPE_member_t asn_MBR_LTE_CarrierFreqUTRA_TDD_r12_1[] = { { ATF_NOFLAGS, 0, offsetof(struct LTE_CarrierFreqUTRA_TDD_r12, carrierFreq_r12), (ASN_TAG_CLASS_CONTEXT | (0 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_LTE_ARFCN_ValueUTRA, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "carrierFreq-r12" }, { ATF_POINTER, 1, offsetof(struct LTE_CarrierFreqUTRA_TDD_r12, cellReselectionPriority_r12), (ASN_TAG_CLASS_CONTEXT | (1 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_LTE_CellReselectionPriority, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "cellReselectionPriority-r12" }, { ATF_NOFLAGS, 0, offsetof(struct LTE_CarrierFreqUTRA_TDD_r12, threshX_High_r12), (ASN_TAG_CLASS_CONTEXT | (2 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_LTE_ReselectionThreshold, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "threshX-High-r12" }, { ATF_NOFLAGS, 0, offsetof(struct LTE_CarrierFreqUTRA_TDD_r12, threshX_Low_r12), (ASN_TAG_CLASS_CONTEXT | (3 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_LTE_ReselectionThreshold, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "threshX-Low-r12" }, { ATF_NOFLAGS, 0, offsetof(struct LTE_CarrierFreqUTRA_TDD_r12, q_RxLevMin_r12), (ASN_TAG_CLASS_CONTEXT | (4 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_NativeInteger, 0, { 0, &asn_PER_memb_LTE_q_RxLevMin_r12_constr_6, memb_LTE_q_RxLevMin_r12_constraint_1 }, 0, 0, /* No default value */ "q-RxLevMin-r12" }, { ATF_NOFLAGS, 0, offsetof(struct LTE_CarrierFreqUTRA_TDD_r12, p_MaxUTRA_r12), (ASN_TAG_CLASS_CONTEXT | (5 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_NativeInteger, 0, { 0, &asn_PER_memb_LTE_p_MaxUTRA_r12_constr_7, memb_LTE_p_MaxUTRA_r12_constraint_1 }, 0, 0, /* No default value */ "p-MaxUTRA-r12" }, { ATF_POINTER, 1, offsetof(struct LTE_CarrierFreqUTRA_TDD_r12, reducedMeasPerformance_r12), (ASN_TAG_CLASS_CONTEXT | (6 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_LTE_reducedMeasPerformance_r12_8, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "reducedMeasPerformance-r12" }, }; static const int asn_MAP_LTE_CarrierFreqUTRA_TDD_r12_oms_1[] = { 1, 6 }; static const ber_tlv_tag_t asn_DEF_LTE_CarrierFreqUTRA_TDD_r12_tags_1[] = { (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)) }; static const asn_TYPE_tag2member_t asn_MAP_LTE_CarrierFreqUTRA_TDD_r12_tag2el_1[] = { { (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 }, /* carrierFreq-r12 */ { (ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0 }, /* cellReselectionPriority-r12 */ { (ASN_TAG_CLASS_CONTEXT | (2 << 2)), 2, 0, 0 }, /* threshX-High-r12 */ { (ASN_TAG_CLASS_CONTEXT | (3 << 2)), 3, 0, 0 }, /* threshX-Low-r12 */ { (ASN_TAG_CLASS_CONTEXT | (4 << 2)), 4, 0, 0 }, /* q-RxLevMin-r12 */ { (ASN_TAG_CLASS_CONTEXT | (5 << 2)), 5, 0, 0 }, /* p-MaxUTRA-r12 */ { (ASN_TAG_CLASS_CONTEXT | (6 << 2)), 6, 0, 0 } /* reducedMeasPerformance-r12 */ }; asn_SEQUENCE_specifics_t asn_SPC_LTE_CarrierFreqUTRA_TDD_r12_specs_1 = { sizeof(struct LTE_CarrierFreqUTRA_TDD_r12), offsetof(struct LTE_CarrierFreqUTRA_TDD_r12, _asn_ctx), asn_MAP_LTE_CarrierFreqUTRA_TDD_r12_tag2el_1, 7, /* Count of tags in the map */ asn_MAP_LTE_CarrierFreqUTRA_TDD_r12_oms_1, /* Optional members */ 2, 0, /* Root/Additions */ 7, /* First extension addition */ }; asn_TYPE_descriptor_t asn_DEF_LTE_CarrierFreqUTRA_TDD_r12 = { "CarrierFreqUTRA-TDD-r12", "CarrierFreqUTRA-TDD-r12", &asn_OP_SEQUENCE, asn_DEF_LTE_CarrierFreqUTRA_TDD_r12_tags_1, sizeof(asn_DEF_LTE_CarrierFreqUTRA_TDD_r12_tags_1) /sizeof(asn_DEF_LTE_CarrierFreqUTRA_TDD_r12_tags_1[0]), /* 1 */ asn_DEF_LTE_CarrierFreqUTRA_TDD_r12_tags_1, /* Same as above */ sizeof(asn_DEF_LTE_CarrierFreqUTRA_TDD_r12_tags_1) /sizeof(asn_DEF_LTE_CarrierFreqUTRA_TDD_r12_tags_1[0]), /* 1 */ { 0, 0, SEQUENCE_constraint }, asn_MBR_LTE_CarrierFreqUTRA_TDD_r12_1, 7, /* Elements count */ &asn_SPC_LTE_CarrierFreqUTRA_TDD_r12_specs_1 /* Additional specs */ };
36.165899
161
0.71445
117e8695a633e216bda542304f811ceb9091290f
3,141
h
C
xapian/xapian-core-1.2.13/common/io_utils.h
pgs7179/xapian_modified
0229c9efb9eca19be4c9f463cd4b793672f24198
[ "MIT" ]
2
2021-01-13T21:17:42.000Z
2021-01-13T21:17:42.000Z
xapian/xapian-core-1.2.13/common/io_utils.h
Loslove55/tailbench
fbbf3f31e3f0af1bb7db7f07c2e7193b84abb1eb
[ "MIT" ]
null
null
null
xapian/xapian-core-1.2.13/common/io_utils.h
Loslove55/tailbench
fbbf3f31e3f0af1bb7db7f07c2e7193b84abb1eb
[ "MIT" ]
null
null
null
/** @file io_utils.h * @brief Wrappers for low-level POSIX I/O routines. */ /* Copyright (C) 2006,2007,2008,2009,2011 Olly Betts * Copyright (C) 2010 Richard Boulton * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef XAPIAN_INCLUDED_IO_UTILS_H #define XAPIAN_INCLUDED_IO_UTILS_H #include <sys/types.h> #include "safefcntl.h" #include "safeunistd.h" #include <string> /** Ensure all data previously written to file descriptor fd has been written to * disk. * * Returns false if this could not be done. */ inline bool io_sync(int fd) { #ifdef F_FULLFSYNC /* Only supported on Mac OS X (at the time of writing at least). * * This call ensures that data has actually been written to disk, not just * to the drive's write cache, so it provides better protection from power * failures, etc. It does take longer though. * * According to the sqlite sources, this shouldn't fail on a local FS so * a failure means that the file system doesn't support this operation and * therefore it's best to fallback to fdatasync()/fsync(). */ if (fcntl(fd, F_FULLFSYNC, 0) == 0) return true; #endif #if defined HAVE_FDATASYNC // If we have it, prefer fdatasync() over fsync() as the former avoids // updating the access time so is probably a little more efficient. return fdatasync(fd) == 0; #elif defined HAVE_FSYNC return fsync(fd) == 0; #elif defined __WIN32__ return _commit(fd) == 0; #else # error Cannot implement io_sync() without fdatasync(), fsync(), or _commit() #endif } /** Read n bytes (or until EOF) into block pointed to by p from file descriptor * fd. * * If less than min bytes are read, throw an exception. * * Returns the number of bytes actually read. */ size_t io_read(int fd, char * p, size_t n, size_t min); /** Write n bytes from block pointed to by p to file descriptor fd. */ void io_write(int fd, const char * p, size_t n); /** Delete a file. * * @param filename The file to delete. * * @exception Xapian::DatabaseError is thrown if @a filename existed but * couldn't be unlinked. * @return true if @a filename was successfully removed; false if it * didn't exist. If the file is on NFS, false may be returned * even if the file was removed (if the server fails after * removing the file but before telling the client, and the * client then retries). */ bool io_unlink(const std::string & filename); #endif // XAPIAN_INCLUDED_IO_UTILS_H
34.141304
80
0.711875
119065d94cc15686a846aa95fb2b5794298ef570
1,998
c
C
compiler/stm_tests.c
tajmone/alan
b76a03eed8b567a130352bea4781203bcf693286
[ "Artistic-2.0" ]
12
2019-07-30T23:25:12.000Z
2021-09-07T08:06:10.000Z
compiler/stm_tests.c
tajmone/alan
b76a03eed8b567a130352bea4781203bcf693286
[ "Artistic-2.0" ]
40
2019-08-01T09:12:47.000Z
2022-01-09T18:09:51.000Z
compiler/stm_tests.c
tajmone/alan
b76a03eed8b567a130352bea4781203bcf693286
[ "Artistic-2.0" ]
2
2021-04-21T13:23:10.000Z
2022-02-21T19:27:45.000Z
#include <cgreen/cgreen.h> #include "stm_x.h" #include "lmList.mock" #include "lmlog.mock" #include "context.mock" #include "exp.mock" #include "emit.mock" #include "sym.mock" #include "adv.mock" #include "wht.mock" #include "whr.mock" #include "srcp.mock" #include "id.mock" #include "encode.mock" #include "set.mock" #include "atr.mock" #include "resource.mock" #include "lst_x.h" /* Global data */ FILE *txtfil; int totalScore; Describe(Statement); BeforeEach(Statement) {} AfterEach(Statement) {} Ensure(Statement, analyzeIf_creates_restricting_context_for_Id_Isa_expression) { What *what = newWhatId(nulsrcp, newId(nulsrcp, "id")); Expression *what_expression = newWhatExpression(nulsrcp, what); Expression *isa = newIsaExpression(nulsrcp, what_expression, false, NULL); Statement *statement = newStatement(&nulsrcp, IF_STATEMENT); isa->type = BOOLEAN_TYPE; statement->fields.iff.exp = isa; statement->fields.iff.thn = NULL; statement->fields.iff.els = NULL; expect(analyzeExpression); expect(pushContext); expect(addRestrictionInContext); analyzeStatements(newList(statement, STATEMENT_LIST), NULL); } Ensure(Statement, analyzeIf_does_not_create_restricting_context_for_Isa_expression_with_anything_but_Id) { What *what = newWhatId(nulsrcp, newId(nulsrcp, "id")); Expression *what_expression = newWhatExpression(nulsrcp, what); Expression *attribute_expression = newAttributeExpression(nulsrcp, newId(nulsrcp, "attribute"), false, what_expression); Expression *isa = newIsaExpression(nulsrcp, attribute_expression, false, NULL); Statement *statement = newStatement(&nulsrcp, IF_STATEMENT); isa->type = BOOLEAN_TYPE; statement->fields.iff.exp = isa; statement->fields.iff.thn = NULL; statement->fields.iff.els = NULL; expect(analyzeExpression); never_expect(pushContext); never_expect(addRestrictionInContext); analyzeStatements(newList(statement, STATEMENT_LIST), NULL); }
27.369863
124
0.73974
61fa1b3c7b0db8311667d125dc3666226a429920
2,162
h
C
molecular/util/TextStream.h
petrarce/molecular-gfx
fdf95c28a5693a2e1f9abaedda9521f8521b1f84
[ "MIT" ]
null
null
null
molecular/util/TextStream.h
petrarce/molecular-gfx
fdf95c28a5693a2e1f9abaedda9521f8521b1f84
[ "MIT" ]
1
2019-10-23T14:33:25.000Z
2019-10-23T14:33:25.000Z
molecular/util/TextStream.h
petrarce/molecular-gfx
fdf95c28a5693a2e1f9abaedda9521f8521b1f84
[ "MIT" ]
2
2020-09-24T13:33:39.000Z
2022-03-29T13:17:47.000Z
/* TextStream.h MIT License Copyright (c) 2019 Fabian Herb Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef MOLECULAR_TEXTSTREAM_H #define MOLECULAR_TEXTSTREAM_H #include <stdexcept> #include <stdint.h> namespace molecular { namespace util { class TextReadStreamBase { public: virtual ~TextReadStreamBase() = default; virtual char* GetNextLine() = 0; }; template<class Storage> class TextReadStream : public TextReadStreamBase { public: TextReadStream(Storage& storage) : mStorage(storage) { mLine[0] = 0; } /// Reads a line and returns it /** @returns Pointer to an internal storage of the line, which is only valid until the next call to GetNextLine(). Returns nullptr if the storage is at its end. */ char* GetNextLine() override { if(mStorage.EndOfData()) return nullptr; char c; int i; for(i = 0; i < kMaxLineLength; ++i) { if(mStorage.EndOfData() || mStorage.Read(&c, 1) != 1 || c == '\n') { mLine[i] = 0; return mLine; } else mLine[i] = c; } throw std::range_error("Line too long"); } private: static const int kMaxLineLength = 1024; char mLine[kMaxLineLength]; Storage& mStorage; }; } } #endif
24.850575
78
0.73913
500e8c3b75d8ee37bf2265c56acd07825ec24030
1,379
h
C
src/apps/testbedservice/virtual_links/virtual_link_transmission_model_factory.h
itm/shawn
49cb715d0044a20a01a19bc4d7b62f9f209df83c
[ "BSD-3-Clause" ]
15
2015-07-07T15:48:30.000Z
2019-10-27T18:49:49.000Z
src/apps/testbedservice/virtual_links/virtual_link_transmission_model_factory.h
itm/shawn
49cb715d0044a20a01a19bc4d7b62f9f209df83c
[ "BSD-3-Clause" ]
null
null
null
src/apps/testbedservice/virtual_links/virtual_link_transmission_model_factory.h
itm/shawn
49cb715d0044a20a01a19bc4d7b62f9f209df83c
[ "BSD-3-Clause" ]
4
2016-11-23T05:50:01.000Z
2019-09-18T12:44:36.000Z
/************************************************************************ ** This file is part of the network simulator Shawn. ** ** Copyright (C) 2004-2007 by the SwarmNet (www.swarmnet.de) project ** ** Shawn is free software; you can redistribute it and/or modify it ** ** under the terms of the BSD License. Refer to the shawn-licence.txt ** ** file in the root of the Shawn source tree for further details. ** ************************************************************************/ #ifndef __SHAWN_APPS_TESTBEDSERVICE_VIRTUAL_LINK_TRANSMISSION_MODEL_FACTORY_H_ #define __SHAWN_APPS_TESTBEDSERVICE_VIRTUAL_LINK_TRANSMISSION_MODEL_FACTORY_H_ #include "../buildfiles/_apps_enable_cmake.h" #ifdef ENABLE_TESTBEDSERVICE #include <string> #include "sys/transm_models/transmission_model_factory.h" namespace testbedservice { ///Creates instances of VirtualLinkTransmissionModelFactory class VirtualLinkTransmissionModelFactory : public shawn::TransmissionModelFactory { public: VirtualLinkTransmissionModelFactory(); virtual ~VirtualLinkTransmissionModelFactory(); virtual std::string name( void ) const throw(); virtual std::string description( void ) const throw(); virtual shawn::TransmissionModel* create( const shawn::SimulationController& ) throw(); }; } #endif #endif
38.305556
95
0.661349
fb8b1ee2bc3d4beef4eac65e91b8051bd737a221
4,096
c
C
tests/test_litl_pause.c
sthibaul/LiTL
3c9d0baaa0611b1cdc481c085cee766455491a6c
[ "BSD-2-Clause" ]
6
2020-12-18T12:24:28.000Z
2022-03-08T15:58:18.000Z
tests/test_litl_pause.c
sthibaul/LiTL
3c9d0baaa0611b1cdc481c085cee766455491a6c
[ "BSD-2-Clause" ]
null
null
null
tests/test_litl_pause.c
sthibaul/LiTL
3c9d0baaa0611b1cdc481c085cee766455491a6c
[ "BSD-2-Clause" ]
1
2021-02-14T23:46:55.000Z
2021-02-14T23:46:55.000Z
/* -*- c-file-style: "GNU" -*- */ /* * Copyright © Télécom SudParis. * See COPYING in top-level directory. */ /* * This test simulates the situation when the event recoding is paused. */ #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include "litl_types.h" #include "litl_tools.h" #include "litl_write.h" #include "litl_read.h" void write_trace(char* filename, int nb_iter, int skipped_iter) { int i; litl_write_trace_t* trace; const uint32_t buffer_size = 512 * 1024; // 512KB trace = litl_write_init_trace(buffer_size); litl_write_set_filename(trace, filename); #ifdef LITL_TESTBUFFER_FLUSH litl_write_buffer_flush_on(trace); #else litl_write_buffer_flush_off(trace); #endif litl_data_t val[] = "Well, that's Philosophy I've read, And Law and Medicine, and I fear Theology, too, from A to Z; Hard studies all, that have cost me dear. And so I sit, poor silly man No wiser now than when I began."; for (i = 0; i < nb_iter; i++) { if (i == skipped_iter - 1) { printf("Loop %d: stop recording\n", i); litl_write_pause_recording(trace); } litl_write_probe_reg_0(trace, 0x100 * (i + 1) + 1); usleep(100); litl_write_probe_reg_1(trace, 0x100 * (i + 1) + 2, 1); usleep(100); litl_write_probe_reg_2(trace, 0x100 * (i + 1) + 3, 1, 3); usleep(100); litl_write_probe_reg_3(trace, 0x100 * (i + 1) + 4, 1, 3, 5); usleep(100); litl_write_probe_reg_4(trace, 0x100 * (i + 1) + 5, 1, 3, 5, 7); usleep(100); litl_write_probe_reg_5(trace, 0x100 * (i + 1) + 6, 1, 3, 5, 7, 11); usleep(100); litl_write_probe_reg_6(trace, 0x100 * (i + 1) + 7, 1, 3, 5, 7, 11, 13); usleep(100); litl_write_probe_reg_7(trace, 0x100 * (i + 1) + 8, 1, 3, 5, 7, 11, 13, 17); usleep(100); litl_write_probe_reg_8(trace, 0x100 * (i + 1) + 9, 1, 3, 5, 7, 11, 13, 17, 19); usleep(100); litl_write_probe_reg_9(trace, 0x100 * (i + 1) + 10, 1, 3, 5, 7, 11, 13, 17, 19, 23); usleep(100); litl_write_probe_reg_10(trace, 0x100 * (i + 1) + 11, 1, 3, 5, 7, 11, 13, 17, 19, 23, 29); usleep(100); litl_write_probe_raw(trace, 0x100 * (i + 1) + 12, sizeof(val) - 1, val); usleep(100); if (i == skipped_iter - 1) { printf("Loop %d: resume recording\n", i); litl_write_resume_recording(trace); } } printf("\nEvents with code between %x and %x were not recorded\n", 0x100 * skipped_iter + 1, 0x100 * skipped_iter + 12); litl_write_finalize_trace(trace); } void read_trace(char* filename, uint32_t left_bound, uint32_t right_bound) { int nbevents = 0; litl_read_event_t* event; litl_read_trace_t *trace; trace = litl_read_open_trace(filename); litl_read_init_processes(trace); while (1) { event = litl_read_next_event(trace); if (event == NULL ) break; // check whether some events were skipped if ((left_bound < LITL_READ_GET_CODE(event))&& (LITL_READ_GET_CODE(event) < right_bound)){ nbevents++; break; } } // litl_read_finalize_trace(trace); if (nbevents > 0) { fprintf(stderr, "Some events were recorded when they supposed to be skipped"); exit(EXIT_FAILURE); } } int main(int argc, char **argv) { int nb_iter; int skipped_iter; char* filename = "trace"; nb_iter = 10; skipped_iter = nb_iter / 2; if ((argc == 3) && (strcmp(argv[1], "-f") == 0)) filename = argv[2]; else #ifdef LITL_TESTBUFFER_FLUSH filename = "/tmp/test_litl_pause_flush.trace"; #else filename = "/tmp/test_litl_pause.trace"; #endif printf("Recording events with various number of arguments\n\n"); write_trace(filename, nb_iter, skipped_iter); printf("Events are recorded and written in the %s file\n", filename); printf("\nChecking whether the recording of events was paused\n"); read_trace(filename, 0x100 * skipped_iter + 1, 0x100 * skipped_iter + 12); printf("Yes, the recording of events was paused\n"); return EXIT_SUCCESS; }
27.863946
205
0.638428
f72bd1c6def0c0e9fd4b9da896d52035f4bccc8b
880
c
C
src/mem.c
pi-pi3/funky-kernel
e6938c0e75e5aabf49cc94f6720250f21bf94900
[ "Zlib" ]
null
null
null
src/mem.c
pi-pi3/funky-kernel
e6938c0e75e5aabf49cc94f6720250f21bf94900
[ "Zlib" ]
null
null
null
src/mem.c
pi-pi3/funky-kernel
e6938c0e75e5aabf49cc94f6720250f21bf94900
[ "Zlib" ]
null
null
null
#include "alloc.h" #include "holes.h" #include "mem.h" extern heap_t heap; // TODO: frames int init_mem(frame_t frame_start, frame_t frame_end, size_t heap_start, size_t heap_end) { init_frames(frame_start, frame_end); page_t page_start = page_with_addr(heap_start); page_t page_end = page_with_addr(heap_end); for (page_t page = page_start; page < page_end; page++) { map_page(next_frame_create(), page); } heap_init(&heap, heap_start, heap_end); return 0; } void map_page(frame_t frame, page_t page) { /* TODO */ } size_t page_with_addr(size_t addr) { return addr >> 12; } size_t addr_at_page(size_t page) { return page << 12; } size_t align_down(const size_t n, const size_t align) { return n & ~(align - 1); } size_t align_up(const size_t n, const size_t align) { return align_down(n + align - 1, align); }
20
90
0.679545
ddc6dd0ea335a6635baebf865a5d3b1cd0bfbd20
8,910
c
C
mpid/ch_p4/p4/lib/p4_fc.c
RWTH-OS/MP-MPICH
f2ae296477bb9d812fda587221b3419c09f85b4a
[ "mpich2" ]
null
null
null
mpid/ch_p4/p4/lib/p4_fc.c
RWTH-OS/MP-MPICH
f2ae296477bb9d812fda587221b3419c09f85b4a
[ "mpich2" ]
null
null
null
mpid/ch_p4/p4/lib/p4_fc.c
RWTH-OS/MP-MPICH
f2ae296477bb9d812fda587221b3419c09f85b4a
[ "mpich2" ]
1
2021-01-23T11:01:01.000Z
2021-01-23T11:01:01.000Z
/* this file contains the direct fiber channel interface: p4_initfc p4_sendfc p4_recvfc */ #include "p4.h" #include "p4_sys.h" #include <sys/uio.h> #include <sys/file.h> #include <sys/comio.h> /* #include <fcntl.h> */ #include <sys/devinfo.h> #include <stdlib.h> /* #include <netdb.h> */ #include "sfcdchi.h" int y, fds[64]; struct sfc_open *fcopen; struct sfc_bind *fcbind; struct sfc_connect *fcconnect; struct sfc_listen *fclisten; struct sfc_accept *fcaccept; struct sfc_read *fcread; struct sfc_write *fcwrite; struct sfc_close *fcclose; p4_initfc() { unsigned char *buf; int fd; int i; int j; int k; char * device; char * localip = NULL; char destip[100]; struct hostent * hp; int remotefd; int myid, numnodes, rc; device = "/dev/sfc0"; fcopen = calloc(1,sizeof(struct sfc_open)); fcbind = calloc(1,sizeof(struct sfc_bind)); fcbind->name = calloc(1,sizeof(struct sfcaddr_in)); fcconnect = calloc(1,sizeof(struct sfc_connect)); fcconnect->name = calloc(1,sizeof(struct sfcaddr_in)); fcaccept = calloc(1,sizeof(struct sfc_accept)); fcaccept->address = calloc(1,sizeof(struct sfcaddr_in)); fclisten = calloc(1,sizeof(struct sfc_listen)); fcread = calloc(1,sizeof(struct sfc_read)); fcwrite = calloc(1,sizeof(struct sfc_write)); fcclose= calloc(1,sizeof(struct sfc_close)); if ((y=open(device,O_RDWR,0)) < 0) { fprintf(stderr, "p4_initfc: Unable to open device '%s': %s\n", device, strerror(errno)); exit(1); } p4_dprintfl(30,"opening. . .\n"); if ((i = ioctl(y,SFC_OPEN,fcopen)) != 0) { p4_error("p4_initfc: open error: ",errno); } fd = fcopen->dcd; p4_dprintfl(30,"opened fd %d. . .\n",fd); p4_dprintfl(30,"binding port 211 to descriptor fd %d. . .\n",fd); fcbind->dcd=fd; fcbind->name->port = 211; fcbind->name->type = IP_ADDR; if (localip == NULL) fcbind->name->inet_addr = gethostid(); else { hp = gethostbyname(localip); if (hp == NULL) { fprintf(stderr, "p4_initfc: %s: unknown host\n", localip); exit(1); } bcopy(hp->h_addr,&fcconnect->name->inet_addr,hp->h_length); } if ((i = ioctl(y,SFC_BIND,fcbind)) != 0) { p4_error("p4_initfc: bind error: ",errno); } p4_dprintfl(30,"listening for connection requests. . .\n"); fclisten->dcd = fd; fclisten->backlog = 3; if ((i = ioctl(y,SFC_LISTEN,fclisten)) != 0) { p4_error("p4_initfc: listen error: ",errno); } /* establish all the connections */ numnodes = p4_num_total_ids(); myid = p4_get_my_id(); for (i = 0; i < numnodes; i++) { if (myid < i) { int otherid; p4_dprintfl(30,"accepting first connection. . .\n"); fcaccept->dcd = fd; fcaccept->timeout = DCMAXTIMEOUT; fcaccept->blockflag = BLOCKING; do { errno = 0; if ((rc = ioctl(y,SFC_ACCEPT,fcaccept)) != 0 && errno != ETIMEOUT) { p4_error("p4_initfc: accept error: ",errno); } } while (errno == ETIMEOUT); if (rc==NOERROR) remotefd = fcaccept->newdcd; p4_dprintfl(30,"doing initial blocked read\n"); fcread->dcd = fcaccept->newdcd; fcread->buff = (char *) &otherid; fcread->nbytes = sizeof(int); fcread->timeout = 10; /* 10 sec */ fcread->blockflag = BLOCKING; rc = ioctl(y,SFC_READ,fcread); if (rc != 0) p4_dprintf("err %d\n",errno); else { if (fcread->nbytes != sizeof(int)) p4_error("initial message wrong size:", fcread->nbytes); else { p4_dprintfl(30,"read from %d\n",otherid); fds[otherid] = remotefd; } } } if (myid > i) { p4_dprintfl(30,"opening. . .\n"); if ((rc = ioctl(y,SFC_OPEN,fcopen)) != 0) { p4_error("p4_initfc: open error: ",errno); } fd = fcopen->dcd; p4_dprintfl(30,"opened fd %d. . .\n",fd); translate_name(p4_global->proctable[i].host_name,destip); p4_dprintfl(30,"swname = %s, destip = %s\n", p4_global->proctable[i].host_name,destip); hp = gethostbyname(destip); if (hp == 0) { fprintf(stderr, "p4_initfc: %s: unknown host\n",destip); exit(2); } p4_dprintfl(30,"connecting. . .\n"); do /*try to connect repeatedly until accept on other side occurs */ { fcconnect->dcd = fd; fcconnect->timeout = 10; fcconnect->name->port = 211; fcconnect->name->type = IP_ADDR; bcopy(hp->h_addr, &fcconnect->name->inet_addr, hp->h_length); if ((rc = ioctl(y,SFC_CONNECT,fcconnect)) != NOERROR) { p4_dprintf("error connecting %d\n", errno); } } while (rc != NOERROR); fds[i] = fd; p4_dprintfl(30,"connected. . .\n"); p4_dprintfl(30,"%d writing id\n",myid); fcwrite->dcd = fd; fcwrite->nbytes = sizeof(int); fcwrite->buff = (char *) &myid; fcwrite->type = BLOCKING; if ((rc = ioctl(y,SFC_WRITE,fcwrite)) != NOERROR) { if (rc < 0 ) p4_dprintf("error on initial write was %d \n ",errno); } } } } translate_name(fromname,toname) char *fromname, *toname; { /* this routine is a temporary hack to derive fiber-channel names from the hostnames in the procgroup file that are used to set up the original p4 configuration for use by p4_send and p4_recv. The fiber channel names will be used by the direct fiber-channel interface, p4_sendfc and p4_recvfc. */ if (strncmp(fromname,"spnode",6) == 0) /* ANL SP-1 nodes */ { /* chg swnodexxx to fcnodexxx */ strcpy(toname,fromname); toname[0] = 'f'; toname[1] = 'c'; } else if ((strncmp(fromname,"hamlet",6) == 0) || (strncmp(fromname,"timon",5) == 0) || (strncmp(fromname,"titus",5) == 0) || (strncmp(fromname,"ibm1",4) == 0)) /* ANL CTD and HEP */ { /* append "-fc to machine names */ strcpy(toname,fromname); strcat(toname,"-fc"); } else if ((strncmp(fromname,"mercury",7) == 0) || (strncmp(fromname,"venus",5) == 0) || (strncmp(fromname,"earth",5) == 0) || (strncmp(fromname,"mars",4) == 0) || (strncmp(fromname,"jupiter",7) == 0) || (strncmp(fromname,"saturn",6) == 0) || (strncmp(fromname,"neptune",7) == 0) || (strncmp(fromname,"uranus",7) == 0) || (strncmp(fromname,"pluto",5) == 0)) /* ANL SP-1 planets */ { /* append "f1" to planet names */ strcpy(toname,fromname); strcat(toname,"f1"); } else if (strncmp(fromname,"ibms",4) == 0) /* FSU nodes */ { /* append "f" to FSU ibmsxx names */ strcpy(toname,fromname); strcat(toname,"f"); } else p4_error("p4_initfc: couldn't translate name", 0); } p4_sendfc(type,to,msg,len) int type,to,len; char *msg; { int rc, wrtlen; struct p4_net_msg_hdr header; header.msg_type = type; header.to = to; header.from = p4_get_my_id(); header.ack_req = 0; header.msg_len = len; p4_dprintfl(30,"writing header to %d\n",to); fcwrite->dcd = fds[to]; fcwrite->nbytes = sizeof(struct p4_net_msg_hdr); fcwrite->buff = (char *) &header; fcwrite->type = BLOCKING; if ((rc = ioctl(y,SFC_WRITE,fcwrite)) != NOERROR) { if (rc < 0 ) p4_error("p4_sendfc error on header write was ",errno); } while (len > 0) { if (len > 65500) { len -= 65500; wrtlen = 65500; } else { wrtlen = len; len = 0; } p4_dprintfl(30,"writing %d bytes of data to %d\n",to); fcwrite->dcd = fds[to]; fcwrite->nbytes = wrtlen; fcwrite->buff = msg; fcwrite->type = BLOCKING; if ((rc = ioctl(y,SFC_WRITE,fcwrite)) != NOERROR) { if (rc < 0 ) p4_error("error on data write was ",errno); } } p4_dprintfl(30,"exiting p4_sendfc\n"); } p4_recvfc(type,from,msg,len) int *type, *from, *len; char **msg; { int rc; struct p4_net_msg_hdr header; if (*msg == NULL) p4_error("p4_recvfc: pre-allocated buffers required for fiber channel",0); if (*from == -1) p4_error("p4_recvfc: wild-card receive not allowed for fiber channel",0); p4_dprintfl(30,"doing blocked read for header\n"); fcread->dcd = fds[*from]; fcread->buff = (char *) &header; fcread->nbytes = sizeof(struct p4_net_msg_hdr); fcread->timeout = 10; /* 10 sec */ fcread->blockflag = BLOCKING; rc = ioctl(y,SFC_READ,fcread); if (rc != 0) p4_error("p4_recvfc: read for header failed",rc); p4_dprintfl(30,"length from received header is %d\n",header.msg_len); if (header.msg_len != 0) { p4_dprintfl(30,"doing blocked read for data\n"); fcread->dcd = fds[*from]; fcread->buff = *msg; fcread->nbytes = header.msg_len; fcread->timeout = 10; /* 10 sec */ fcread->blockflag = BLOCKING; rc = ioctl(y,SFC_READ,fcread); if (rc != 0) p4_error("p4_recvfc: read for data failed",rc); } *type = header.msg_type; *from = header.from; *len = header.msg_len; }
25.457143
77
0.600786
de20cc0afb0d6be277d90b3d8379c125ca835a73
1,547
c
C
masscan_redis/queue.c
luantao/masscan_redis
30b0330134fe4222a182e053c0a9e7d3fbecc7cf
[ "Apache-2.0" ]
1
2017-06-13T07:45:55.000Z
2017-06-13T07:45:55.000Z
masscan_redis/queue.c
luantao/masscan_redis
30b0330134fe4222a182e053c0a9e7d3fbecc7cf
[ "Apache-2.0" ]
null
null
null
masscan_redis/queue.c
luantao/masscan_redis
30b0330134fe4222a182e053c0a9e7d3fbecc7cf
[ "Apache-2.0" ]
2
2017-03-08T00:19:42.000Z
2019-06-19T01:19:41.000Z
#include <stdio.h> #include <stdlib.h> #include "queue.h" void initQueue(queue_t * queue_eg) { queue_eg->head = NULL; //队头标志位 queue_eg->tail = NULL; //队尾标志位 } /*2.向链队的<span style="background-color: rgb(255, 102, 102);">队尾插入</span>一个元素x*/ void enQueue(queue_t *hq, elemType x) { node_t * new_p; new_p = (node_t *) malloc(sizeof (queue_t)); if (new_p == NULL) { printf("分配空间出错!"); exit(1); } new_p->data = x; new_p->next = NULL; if (hq->head == NULL) { hq->head = new_p; hq->tail = new_p; } else { //hq->tail->data = x; hq->tail->next = new_p; hq->tail = new_p; } return; } /*3. 从列队中队首删除一个元素*/ elemType outQueue(queue_t * hq) { node_t * p; elemType temp; if (hq->head == NULL) { printf("队列为空,不能删除!"); exit(1); } temp = hq->head->data; p = hq->head; hq->head = hq->head->next; if (hq->head == NULL) { hq->tail = NULL; } free(p); return temp; } /*4. 读取队首元素 */ elemType peekQueue(queue_t * hq) { if (hq->head == NULL) { printf("队列为空。"); exit(1); } return hq->head->data; } /*5. 检查队列是否为空,若是空返回1,若不为空返回0 。*/ int is_emptyQueue(queue_t * hq) { if (hq->head == NULL) { return 1; } else { return 0; } } /*6. 清除链队中的所有元素*/ void clearQueue(queue_t * hq) { node_t * p = hq->head; while (p != NULL) { hq->head = hq->head->next; free(p); p = hq->head; } hq->tail = NULL; return; }
19.582278
78
0.505495
f51df200c4ffdec87b65616e70de5343529f179e
25,392
c
C
montage-tech/src/kware/demux_mp/mplayer/ffmpeg/libavformat/ff_hds.c
kuikuitage/NewCool-UC-3.1.0-priv
16198d4eae1dd1a1bf4f4ba4b54652688078c018
[ "Apache-2.0" ]
null
null
null
montage-tech/src/kware/demux_mp/mplayer/ffmpeg/libavformat/ff_hds.c
kuikuitage/NewCool-UC-3.1.0-priv
16198d4eae1dd1a1bf4f4ba4b54652688078c018
[ "Apache-2.0" ]
null
null
null
montage-tech/src/kware/demux_mp/mplayer/ffmpeg/libavformat/ff_hds.c
kuikuitage/NewCool-UC-3.1.0-priv
16198d4eae1dd1a1bf4f4ba4b54652688078c018
[ "Apache-2.0" ]
3
2016-05-03T05:57:19.000Z
2021-11-10T21:34:00.000Z
/* * Adobe HTTP Dynamic Streaming (HDS) demuxer * Copyright (c) 2013 Cory McCarthy * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * @brief Adobe HTTP Dynamic Streaming (HDS) demuxer * @author Cory McCarthy * @see http://www.adobe.com/devnet/hds.html * @see http://wwwimages.adobe.com/www.adobe.com/content/dam/Adobe/en/devnet/hds/pdfs/adobe-hds-specification.pdf * @see http://wwwimages.adobe.com/www.adobe.com/content/dam/Adobe/en/devnet/hds/pdfs/adobe-media-manifest-specification.pdf * @see http://download.macromedia.com/f4v/video_file_format_spec_v10_1.pdf * * @note Link for a HDS test player below: * @see http://mediapm.edgesuite.net/edgeflash/public/zeri/debug/Main.html * * @note Test streams are below: * @test http://multiplatform-f.akamaihd.net/z/multi/april11/hdworld/hdworld_,512x288_450_b,640x360_700_b,768x432_1000_b,1024x576_1400_m,1280x720_1900_m,1280x720_2500_m,1280x720_3500_m,.mp4.csmil/manifest.f4m?hdcore * @test http://multiplatform-f.akamaihd.net/z/multi/april11/cctv/cctv_,512x288_450_b,640x360_700_b,768x432_1000_b,1024x576_1400_m,1280x720_1900_m,1280x720_2500_m,1280x720_3500_m,.mp4.csmil/manifest.f4m?hdcore * @test http://multiplatform-f.akamaihd.net/z/multi/april11/sintel/sintel-hd_,512x288_450_b,640x360_700_b,768x432_1000_b,1024x576_1400_m,1280x720_1900_m,1280x720_2500_m,1280x720_3500_m,.mp4.csmil/manifest.f4m?hdcore * @test http://multiplatform-f.akamaihd.net/z/multi/akamai10year/Akamai_10_Year_,200,300,600,800,1000,1500,2500,4000,k.mp4.csmil/manifest.f4m?hdcore * @test http://zerihdndemo-f.akamaihd.net/z/h264/seeker/LegendofSeeker_16x9_24fps_H264_,400K,650K,1Mbps,1.4Mbps,1.8Mbps,2.5Mbps,.mp4.csmil/manifest.f4m?hdcore * @test http://multiplatform-f.akamaihd.net/z/multi/will/bunny/big_buck_bunny_,640x360_400,640x360_700,640x360_1000,950x540_1500,1280x720_2000,1280x720_3000,.f4v.csmil/manifest.f4m?hdcore * @test http://multiplatform-f.akamaihd.net/z/multi/companion/nba_game/nba_game.mov_,300,600,800,1000,2500,4000,9000,k.mp4.csmil/manifest.f4m?hdcore * @test http://multiplatform-f.akamaihd.net/z/multi/companion/big_bang_theory/big_bang_theory.mov_,300,600,800,1000,2500,4000,9000,k.mp4.csmil/manifest.f4m?hdcore * @test http://multiplatform-f.akamaihd.net/z/multi/shuttle/shuttle_,300,600,800,1000,k.mp4.csmil/manifest.f4m?hdcore * @test http://multiplatform-f.akamaihd.net/z/multi/up_trailer/up_trailer_720p_,300,600,800,1000,k.mp4.csmil/manifest.f4m?hdcore * @test http://multiformatlive-f.akamaihd.net/z/demostream_1@2131/manifest.f4m?hdcore * @test http://zerihdndemo-f.akamaihd.net/z/h264/darkknight/darkknight.smil/manifest.f4m?hdcore * @test http://zerihdndemo-f.akamaihd.net/z/h264/amours/amours.smil/manifest.f4m?hdcore * @test http://zerihdndemo-f.akamaihd.net/z/h264/robinhood/robinhood.smil/manifest.f4m?hdcore * @test http://zerihdndemo-f.akamaihd.net/z/h264/wallstreet/wallstreet.smil/manifest.f4m?hdcore * @test http://zerihdndemo-f.akamaihd.net/z/h264/rockandroll/rockandroll.smil/manifest.f4m?hdcore * @test http://184.72.239.149/vod/smil:bigbuckbunny.smil/manifest.f4m */ #include "avformat.h" #include "internal.h" #include "url.h" #include "avio_internal.h" #include "libavutil/avstring.h" #include "libavutil/parseutils.h" #include "libavutil/time.h" #include "amfmetadata.h" #include "f4mmanifest.h" #include "f4fbox.h" #include "flvtag.h" #ifndef __LINUX__ #include "mp_func_trans.h" #endif #define MAX_NB_SAMPLES 1024 static int open_url_fail = 0;//maybe index error, update bootstrap_info immediately typedef struct HDSBootstrapInfo { char id[MAX_URL_SIZE]; char url[MAX_URL_SIZE]; char profile[MAX_URL_SIZE]; int last_fragment; F4FBox box; } HDSBootstrapInfo; typedef struct HDSMedia { int bitrate; char url[MAX_URL_SIZE]; char bootstrap_info_id[MAX_URL_SIZE]; AVStream *audio_stream; AVStream *video_stream; int nb_samples; FLVMediaSample *samples[MAX_NB_SAMPLES]; int sample_index; int nb_fragments_read; } HDSMedia; typedef struct HDSContext { char id[MAX_URL_SIZE]; int is_live; char base_url[MAX_URL_SIZE]; int nb_bootstraps; HDSBootstrapInfo *bootstrap_info[MAX_NB_BOOTSTRAPS]; int nb_media; HDSMedia *media[MAX_NB_MEDIA]; } HDSContext; static void construct_bootstrap_url(const char *base_url, const char *bootstrap_url, const char *suffix, char *url_out, size_t url_size) { char *p; p = url_out; p += av_strlcat(p, base_url, url_size); p += av_strlcat(p, bootstrap_url, url_size); p += av_strlcat(p, suffix, url_size); } static int download_bootstrap(AVFormatContext *s, HDSBootstrapInfo *bootstrap, uint8_t **buffer_out, int *buffer_size_out) { HDSContext *c = s->priv_data; URLContext *puc; char url[MAX_URL_SIZE]; uint8_t *buffer; int buffer_size; int ret; memset(url, 0x00, sizeof(url)); if(!av_stristr(bootstrap->url, "?") && av_stristr(s->filename, "?")) { construct_bootstrap_url(c->base_url, bootstrap->url, av_stristr(s->filename, "?"), url, MAX_URL_SIZE); } else { construct_bootstrap_url(c->base_url, bootstrap->url, "", url, MAX_URL_SIZE); } av_log(NULL, AV_LOG_DEBUG, "download_bootstrap url:%s\n", url); if((ret = ffurl_open(&puc, url, AVIO_FLAG_READ, &s->interrupt_callback, NULL)) < 0) { av_log(NULL, AV_LOG_ERROR, "hds Failed to start downloading bootstrap, ret: %d \n", ret); return ret; } buffer_size = ffurl_size(puc); buffer = av_mallocz(buffer_size+FF_INPUT_BUFFER_PADDING_SIZE); if(!buffer) return AVERROR(ENOMEM); if((ret = ffurl_read_complete(puc, buffer, buffer_size)) < 0) { av_log(NULL, AV_LOG_ERROR, "hds Failed to downloaded bootstrap, ret: %d \n", ret); av_free(buffer); return ret; } if((ret = ffurl_close(puc)) < 0) { av_log(NULL, AV_LOG_ERROR, "hds Failed to finish downloading bootstrap, ret: %d \n", ret); av_free(buffer); return ret; } if(buffer_out) *buffer_out = buffer; if(buffer_size_out) *buffer_size_out = buffer_size; return 0; } static int create_bootstrap_info(AVFormatContext *s, F4MBootstrapInfo *f4m_bootstrap_info) { HDSContext *c = s->priv_data; HDSBootstrapInfo *bootstrap_info; uint8_t *buffer; int buffer_size, ret; bootstrap_info = av_mallocz(sizeof(HDSBootstrapInfo)); if(!bootstrap_info) return AVERROR(ENOMEM); c->bootstrap_info[c->nb_bootstraps++] = bootstrap_info; memcpy(bootstrap_info->id, f4m_bootstrap_info->id, sizeof(bootstrap_info->id)); memcpy(bootstrap_info->url, f4m_bootstrap_info->url, sizeof(bootstrap_info->url)); memcpy(bootstrap_info->profile, f4m_bootstrap_info->profile, sizeof(bootstrap_info->profile)); if(f4m_bootstrap_info->metadata_size > 0) { av_log(NULL, AV_LOG_DEBUG, "enter f4m_bootstrap_info->metadata_size > 0 !!!!!!\n"); buffer = f4m_bootstrap_info->metadata; buffer_size = f4m_bootstrap_info->metadata_size; if((ret = ff_parse_f4f_box(buffer, buffer_size, &(bootstrap_info->box))) < 0) { av_log(NULL, AV_LOG_ERROR, "hds Failed to parse metadata bootstrap box, ret: %d \n", ret); return ret; } } else { if((ret = download_bootstrap(s, bootstrap_info, &buffer, &buffer_size)) < 0) { av_log(NULL, AV_LOG_ERROR, "hds Failed to download bootstrap, ret: %d \n", ret); return ret; } if((ret = ff_parse_f4f_box(buffer, buffer_size, &(bootstrap_info->box))) < 0) { av_log(NULL, AV_LOG_ERROR, "hds Failed to parse downloaded bootstrap box, ret: %d \n", ret); av_free(buffer); return ret; } av_free(buffer); } return 0; } static int create_streams(AVFormatContext *s, HDSMedia *media, AMFMetadata *metadata) { AVStream *st; st = avformat_new_stream(s, NULL); if(!st) return AVERROR(ENOMEM); media->video_stream = st; st->id = 0; avpriv_set_pts_info(st, 32, 1, 1000); st->codec->codec_type = AVMEDIA_TYPE_VIDEO; st->codec->codec_id = metadata->video_codec_id; st->codec->width = metadata->width; st->codec->height = metadata->height; st->codec->bit_rate = metadata->video_data_rate * 1000; st = avformat_new_stream(s, NULL); if(!st) return AVERROR(ENOMEM); media->audio_stream = st; st->id = 0; avpriv_set_pts_info(st, 32, 1, 1000); st->codec->codec_type = AVMEDIA_TYPE_AUDIO; st->codec->codec_id = metadata->audio_codec_id; st->codec->channels = metadata->nb_audio_channels; st->codec->sample_rate = metadata->audio_sample_rate; st->codec->sample_fmt = AV_SAMPLE_FMT_S16; st->codec->bit_rate = metadata->audio_data_rate * 1000; return 0; } static int create_media(AVFormatContext *s, F4MMedia *f4m_media) { HDSContext *c = s->priv_data; HDSMedia *media; AMFMetadata metadata; int ret; media = av_mallocz(sizeof(HDSMedia)); if(!media) return AVERROR(ENOMEM); c->media[c->nb_media++] = media; media->bitrate = f4m_media->bitrate; memcpy(media->url, f4m_media->url, sizeof(media->url)); av_log(NULL, AV_LOG_DEBUG, "create_media media->url: %s \n", media->url); memcpy(media->bootstrap_info_id, f4m_media->bootstrap_info_id, sizeof(media->bootstrap_info_id)); memset(&metadata, 0x00, sizeof(AMFMetadata)); if((ret = ff_parse_amf_metadata(f4m_media->metadata, f4m_media->metadata_size, &metadata)) < 0) { av_log(NULL, AV_LOG_ERROR, "hds Failed to parse metadata, ret: %d \n", ret); return ret; } if((ret = create_streams(s, media, &metadata)) < 0) return ret; return 0; } static int create_pmt(AVFormatContext *s) { HDSContext *c = s->priv_data; HDSMedia *media; AVProgram *p; int i, j; j = 0; for(i = 0; i < c->nb_media; i++) { media = c->media[i]; p = av_new_program(s, j++); if(!p) return AVERROR(ENOMEM); av_dict_set(&p->metadata,"name", av_asprintf("Bandwidth: %dKbps", media->bitrate), 0); ff_program_add_stream_index(s, p->id, media->video_stream->index); ff_program_add_stream_index(s, p->id, media->audio_stream->index); } return 0; } static int initialize_context(AVFormatContext *s, F4MManifest *manifest) { HDSContext *c = s->priv_data; F4MBootstrapInfo *f4m_bootstrap_info; F4MMedia *f4m_media; int i, ret; int prefer_size = -1; for(i = 0; i < manifest->nb_media; i++) { f4m_media = manifest->media[i]; if(f4m_media->width > 0) { av_log(NULL, AV_LOG_DEBUG, "hds i[%d] f4m_media->width:%d \n", i, f4m_media->width); if(f4m_media->width> 500 && f4m_media->width< 800)//d1 { prefer_size = i; break; } } } if(prefer_size == -1) { for(i = 0; i < manifest->nb_media; i++) { f4m_media = manifest->media[i]; if(f4m_media->width > 0) { if(f4m_media->width> 300 && f4m_media->width< 500)//cif { prefer_size = i; break; } } } } if(prefer_size == -1 && manifest->nb_media > 1) { prefer_size = 1; } else if(prefer_size == -1) { prefer_size = 0; } av_log(NULL, AV_LOG_DEBUG, "hds choosed index[%d] \n", prefer_size); f4m_bootstrap_info = manifest->bootstraps[prefer_size]; if((ret = create_bootstrap_info(s, f4m_bootstrap_info)) < 0) { av_log(NULL, AV_LOG_ERROR, "hds Failed to create bootstrap_info, ret: %d \n", ret); return ret; } for(i = 0; i < manifest->nb_media; i++) { f4m_media = manifest->media[i]; if(strcmp(f4m_media->bootstrap_info_id, f4m_bootstrap_info->id) == 0) { if((ret = create_media(s, f4m_media)) < 0) { av_log(NULL, AV_LOG_ERROR, "hds Failed to create media, ret: %d \n", ret); return ret; } } } if((ret = create_pmt(s)) < 0) { av_log(NULL, AV_LOG_ERROR, "hds Failed to create PMT, ret: %d \n", ret); return ret; } if(!av_strcasecmp(manifest->stream_type, "live")) c->is_live = 1; return 0; } static int hds_read_header(AVFormatContext *s) { HDSContext *c = s->priv_data; AVIOContext *in = s->pb; F4MManifest manifest; int64_t filesize; uint8_t *buf; char *p; int ret; p = av_stristr(s->filename, "manifest.f4m"); if(!p) { p = av_stristr(s->filename, "live.f4m"); if(!p) { p = av_stristr(s->filename, "live_src.f4m"); if(!p) { av_log(NULL, AV_LOG_ERROR, "hds Failed to build base url, url: %s \n", s->filename); return -1; } } } av_strlcpy(c->base_url, s->filename, p - s->filename + 1); filesize = avio_size(in); if(filesize <= 0) return -1; buf = av_mallocz(filesize*sizeof(uint8_t)); if(!buf) return AVERROR(ENOMEM); int len = avio_read(in, buf, filesize); memset(&manifest, 0x00, sizeof(F4MManifest)); if((ret = ff_parse_f4m_manifest(buf, len, &manifest)) < 0) { av_free(buf); ff_free_manifest(&manifest); return ret; } av_free(buf); ret = initialize_context(s, &manifest); ff_free_manifest(&manifest); return ret; } static void construct_fragment_url(const char *base_url, const char *media_url, int segment, int fragment, const char *suffix, char *url_out, size_t url_size) { char *p; char *fragment_str; p = url_out; p += av_strlcat(p, base_url, url_size); p += av_strlcat(p, media_url, url_size); fragment_str = av_asprintf("Seg%d-Frag%d", segment, fragment); p += av_strlcat(p, fragment_str, url_size); av_free(fragment_str); p += av_strlcat(p, suffix, url_size); av_log(NULL, AV_LOG_DEBUG, "construct_fragment_url url: %s \n", url_out); } static int get_segment_fragment(AVFormatContext *s, int is_live, HDSBootstrapInfo *bootstrap_info, HDSMedia *media, int *segment_out, int *fragment_out) { F4FBootstrapInfoBox *abst = &(bootstrap_info->box.abst); F4FSegmentRunTableBox *asrt; F4FFragmentRunTableBox *afrt; F4FSegmentRunEntry *segment_entry; F4FFragmentRunEntry *fragment_entry; int segment, fragment; int i, j; if(open_url_fail) { open_url_fail = 0; ff_free_f4f_box(&bootstrap_info->box); int buffer_size, ret; uint8_t *buffer; av_log(NULL, AV_LOG_DEBUG, "last open url failed! update bootstrap!\n"); if((ret = download_bootstrap(s, bootstrap_info, &buffer, &buffer_size)) < 0) { av_log(NULL, AV_LOG_ERROR, "hds Failed to download bootstrap, ret: %d \n", ret); return ret; } if((ret = ff_parse_f4f_box(buffer, buffer_size, &(bootstrap_info->box))) < 0) { av_log(NULL, AV_LOG_ERROR, "hds Failed to parse downloaded bootstrap box, ret: %d \n", ret); av_free(buffer); return ret; } afrt = abst->fragment_run_table_boxes[abst->nb_fragment_run_table_boxes-1]; fragment_entry = afrt->fragment_run_entries[0]; bootstrap_info->last_fragment = fragment_entry->first_fragment; } for(i = 0; i < abst->nb_segment_run_table_boxes; i++) { asrt = abst->segment_run_table_boxes[i]; if(asrt) { for(j = 0; j < asrt->nb_segment_run_entries; j++) { segment_entry = asrt->segment_run_entries[j]; segment = segment_entry->first_segment; } } } if(!segment_entry) { av_log(NULL, AV_LOG_ERROR, "hds segment entry not found"); return -1; } av_log(NULL, AV_LOG_DEBUG, "get_segment_fragment nb_segment_run_table_boxes[%d] nb_fragment_run_table_boxes[%d]\n", abst->nb_segment_run_table_boxes, abst->nb_fragment_run_table_boxes); afrt = abst->fragment_run_table_boxes[abst->nb_fragment_run_table_boxes-1]; fragment_entry = afrt->fragment_run_entries[0]; if(bootstrap_info->last_fragment == 0) { bootstrap_info->last_fragment = fragment_entry->first_fragment;//start } else { bootstrap_info->last_fragment++; } fragment = bootstrap_info->last_fragment; if(!fragment_entry) { av_log(NULL, AV_LOG_ERROR, "hds fragment entry not found\n"); return -1; } int request_fragment_dis_num = segment_entry->fragments_per_segment/2 - 3; if((fragment + request_fragment_dis_num) == (fragment_entry->first_fragment + segment_entry->fragments_per_segment)) { if(abst->nb_segment_run_table_boxes == (MAX_NB_SEGMENT_RUN_TABLE_BOXES-2) || abst->nb_fragment_run_table_boxes == (MAX_NB_FRAGMENT_RUN_TABLE_BOXES-2)) { av_log(NULL, AV_LOG_DEBUG, "update bootstrap ff_free_f4f_box\n"); ff_free_f4f_box(&bootstrap_info->box); } int buffer_size, ret; uint8_t *buffer; av_log(NULL, AV_LOG_DEBUG, "update bootstrap\n"); if((ret = download_bootstrap(s, bootstrap_info, &buffer, &buffer_size)) < 0) { av_log(NULL, AV_LOG_ERROR, "hds Failed to download bootstrap, ret: %d \n", ret); return ret; } if((ret = ff_parse_f4f_box(buffer, buffer_size, &(bootstrap_info->box))) < 0) { av_log(NULL, AV_LOG_ERROR, "hds Failed to parse downloaded bootstrap box, ret: %d \n", ret); av_free(buffer); return ret; } } if(segment_out) //*segment_out = 1; *segment_out = segment; if(fragment_out) *fragment_out = fragment; return 0; } static int download_fragment(AVFormatContext *s, HDSBootstrapInfo *bootstrap_info, HDSMedia *media, uint8_t **buffer_out, int *buffer_size_out) { HDSContext *c = s->priv_data; URLContext *puc; char url[MAX_URL_SIZE]; uint8_t *buffer; int buffer_size; int segment, fragment; int ret; if((ret = get_segment_fragment(s, c->is_live, bootstrap_info, media, &segment, &fragment)) < 0) { av_log(NULL, AV_LOG_ERROR, "error, ret[%d] download_fragment segment:%d, fragment:%d \n", ret, segment, fragment); return ret; } av_log(NULL, AV_LOG_ERROR, "download_fragment segment:%d, fragment:%d \n", segment, fragment); memset(url, 0x00, sizeof(url)); if(!av_stristr(media->url, "?") && av_stristr(s->filename, "?")) { construct_fragment_url(c->base_url, media->url, segment, fragment, av_stristr(s->filename, "?"), url, MAX_URL_SIZE); } else { construct_fragment_url(c->base_url, media->url, segment, fragment, "", url, MAX_URL_SIZE); } if((ret = ffurl_open(&puc, url, AVIO_FLAG_READ, &s->interrupt_callback, NULL)) < 0) { if(ret != AVERROR(EIO)) av_log(NULL, AV_LOG_ERROR, "hds Failed to start downloading fragment, url:%s, ret:%d \n", url, ret); open_url_fail = 1; return ret; } buffer_size = ffurl_size(puc); buffer = av_mallocz(buffer_size+FF_INPUT_BUFFER_PADDING_SIZE); if(!buffer) return AVERROR(ENOMEM); if((ret = ffurl_read_complete(puc, buffer, buffer_size)) < 0) { av_log(NULL, AV_LOG_ERROR, "hds Failed to downloaded fragment, ret: %d \n", ret); av_free(buffer); return ret; } av_log(NULL, AV_LOG_DEBUG, "download_fragment url[%s] buffer_size[%d] media->nb_fragments_read[%d]\n", url, buffer_size, media->nb_fragments_read); if((ret = ffurl_close(puc)) < 0) { av_log(NULL, AV_LOG_ERROR, "hds Failed to finish downloading fragment, ret: %d \n", ret); av_free(buffer); return ret; } media->nb_fragments_read++; if(buffer_out) *buffer_out = buffer; if(buffer_size_out) *buffer_size_out = buffer_size; return 0; } static int get_next_fragment(AVFormatContext *s, HDSBootstrapInfo *bootstrap_info, HDSMedia *media) { F4FBox box; uint8_t *buffer; int buffer_size, ret; if((ret = download_fragment(s, bootstrap_info, media, &buffer, &buffer_size)) < 0) { return ret; } memset(&box, 0x00, sizeof(F4FBox)); if((ret = ff_parse_f4f_box(buffer, buffer_size, &box)) < 0) { av_log(NULL, AV_LOG_ERROR, "hds Failed to parse bootstrap box, ret: %d \n", ret); av_free(buffer); ff_free_f4f_box(&box); return ret; } av_free(buffer); if((ret = ff_decode_flv_body(box.mdat.data, box.mdat.size, media->samples, &media->nb_samples)) < 0) { av_log(NULL, AV_LOG_ERROR, "hds Failed to decode FLV body, ret: %d \n", ret); ff_free_f4f_box(&box); return ret; } ff_free_f4f_box(&box); return 0; } static void read_next_sample(HDSMedia *media, AVPacket *pkt) { FLVMediaSample *sample; sample = media->samples[media->sample_index]; media->sample_index++; av_new_packet(pkt, sample->data_size); memcpy(pkt->data, sample->data, sample->data_size); pkt->dts = sample->timestamp; if(sample->type == AVMEDIA_TYPE_VIDEO && media->video_stream) { pkt->stream_index = media->video_stream->index; } else if(sample->type == AVMEDIA_TYPE_AUDIO && media->audio_stream) { pkt->stream_index = media->audio_stream->index; } } static void clear_samples(HDSMedia *media) { FLVMediaSample *sample; int i; for(i = 0; i < media->nb_samples; i++) { sample = media->samples[i]; av_freep(&sample->data); av_freep(&sample); media->samples[i] = NULL; } media->nb_samples = 0; media->sample_index = 0; } static int get_next_packet(AVFormatContext *s, HDSBootstrapInfo *bootstrap_info, HDSMedia *media, AVPacket *pkt) { int ret; if(media->nb_samples == 0) { if((ret = get_next_fragment(s, bootstrap_info, media)) < 0) { return ret; } } if(media->nb_samples > 0) { read_next_sample(media, pkt); } if(media->sample_index >= media->nb_samples) { clear_samples(media); } return 0; } static int hds_read_packet(AVFormatContext *s, AVPacket *pkt) { HDSContext *c = s->priv_data; HDSBootstrapInfo *bootstrap_info = NULL; HDSMedia *media = NULL; int i, j, ret; for(i = 0; i < c->nb_media; i++) { media = c->media[i]; bootstrap_info = NULL; if(media->video_stream->discard == AVDISCARD_ALL && media->audio_stream->discard == AVDISCARD_ALL) { av_log(NULL, AV_LOG_ERROR, "media->video_stream audio_stream is set to AVDISCARD_ALL\n"); continue; } for(j = 0; j < c->nb_bootstraps; j++) { if(av_strcasecmp(media->bootstrap_info_id, c->bootstrap_info[j]->id)) continue; bootstrap_info = c->bootstrap_info[j]; break; } if(!bootstrap_info) continue; break; } if(i == c->nb_media) return -1; if(!bootstrap_info) return 0; if(!media) return 0; if((ret = get_next_packet(s, bootstrap_info, media, pkt)) < 0) { if(ret == AVERROR(EIO)) return 0; if(ret == AVERROR_EOF) return ret; av_log(NULL, AV_LOG_ERROR, "hds Failed to get next packet, ret: %d \n", ret); return ret; } return 0; } static int hds_close(AVFormatContext *s) { HDSContext *c = s->priv_data; HDSBootstrapInfo *bootstrap_info; HDSMedia *media; int i; for(i = 0; i < c->nb_bootstraps; i++) { bootstrap_info = c->bootstrap_info[i]; ff_free_f4f_box(&bootstrap_info->box); av_freep(&bootstrap_info); } for(i = 0; i < c->nb_media; i++) { media = c->media[i]; clear_samples(media); av_freep(&media); } memset(c, 0x00, sizeof(HDSContext)); return 0; } static int hds_probe(AVProbeData *p) { if(p->filename && av_stristr(p->filename, ".f4m")) return AVPROBE_SCORE_MAX; return 0; } AVInputFormat ff_hds_demuxer = { .name = "hds", .long_name = "Adobe HTTP Dynamic Streaming Demuxer", .priv_data_size = sizeof(HDSContext), .read_probe = hds_probe, .read_header = hds_read_header, .read_packet = hds_read_packet, .read_close = hds_close, };
31.700375
216
0.645124
67211653c67a9948477563381df029f495f789e8
10,345
h
C
PhysX-3.2.4_PC_SDK_Core/Source/Common/src/CmNvToolsExtProfiler.h
JayStilla/AIEPhysics
d3e45c1bbe44987a96ed12781ef9781fba06bcfa
[ "MIT" ]
null
null
null
PhysX-3.2.4_PC_SDK_Core/Source/Common/src/CmNvToolsExtProfiler.h
JayStilla/AIEPhysics
d3e45c1bbe44987a96ed12781ef9781fba06bcfa
[ "MIT" ]
null
null
null
PhysX-3.2.4_PC_SDK_Core/Source/Common/src/CmNvToolsExtProfiler.h
JayStilla/AIEPhysics
d3e45c1bbe44987a96ed12781ef9781fba06bcfa
[ "MIT" ]
null
null
null
// This code contains NVIDIA Confidential Information and is disclosed to you // under a form of NVIDIA software license agreement provided separately to you. // // Notice // NVIDIA Corporation and its licensors retain all intellectual property and // proprietary rights in and to this software and related documentation and // any modifications thereto. Any use, reproduction, disclosure, or // distribution of this software and related documentation without an express // license agreement from NVIDIA Corporation is strictly prohibited. // // ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES // NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO // THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, // MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. // // Information and code furnished is believed to be accurate and reliable. // However, NVIDIA Corporation assumes no responsibility for the consequences of use of such // information or for any infringement of patents or other rights of third parties that may // result from its use. No license is granted by implication or otherwise under any patent // or patent rights of NVIDIA Corporation. Details are subject to change without notice. // This code supersedes and replaces all information previously supplied. // NVIDIA Corporation products are not authorized for use as critical // components in life support devices or systems without express written approval of // NVIDIA Corporation. // // Copyright (c) 2008-2014 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PX_PHYSICS_COMMON_NV_TOOLS_EXT_PROFILER_H #define PX_PHYSICS_COMMON_NV_TOOLS_EXT_PROFILER_H #if PX_NVTX #include "nvToolsExt.h" #include "PsThread.h" #include "PsHash.h" #include "PsHashMap.h" // C++ function templates to enable NvToolsExt functions namespace nvtx { class Attributes { public: inline Attributes() { clear(); } inline Attributes& category(uint32_t category) { m_event.category = category; return *this; } inline Attributes& color(uint32_t argb) { m_event.colorType = NVTX_COLOR_ARGB; m_event.color = argb; return *this; } inline Attributes& payload(uint64_t value) { m_event.payloadType = NVTX_PAYLOAD_TYPE_UNSIGNED_INT64; m_event.payload.ullValue = value; return *this; } inline Attributes& payload(int64_t value) { m_event.payloadType = NVTX_PAYLOAD_TYPE_INT64; m_event.payload.llValue = value; return *this; } inline Attributes& payload(double value) { m_event.payloadType = NVTX_PAYLOAD_TYPE_DOUBLE; m_event.payload.dValue = value; return *this; } inline Attributes& message(const char* message) { m_event.messageType = NVTX_MESSAGE_TYPE_ASCII; m_event.message.ascii = message; return *this; } inline Attributes& message(const wchar_t* message) { m_event.messageType = NVTX_MESSAGE_TYPE_UNICODE; m_event.message.unicode = message; return *this; } inline Attributes& clear() { memset(&m_event, 0, NVTX_EVENT_ATTRIB_STRUCT_SIZE); m_event.version = NVTX_VERSION; m_event.size = NVTX_EVENT_ATTRIB_STRUCT_SIZE; return *this; } inline const nvtxEventAttributes_t* out() const { return &m_event; } private: nvtxEventAttributes_t m_event; }; class ScopedRange { public: inline ScopedRange(const char* message) { nvtxRangePushA(message); } inline ScopedRange(const wchar_t* message) { nvtxRangePushW(message); } inline ScopedRange(const nvtxEventAttributes_t* attributes) { nvtxRangePushEx(attributes); } inline ScopedRange(const nvtx::Attributes& attributes) { nvtxRangePushEx(attributes.out()); } inline ~ScopedRange() { nvtxRangePop(); } }; inline void Mark(const nvtx::Attributes& attrib) { nvtxMarkEx(attrib.out()); } inline void Mark(const nvtxEventAttributes_t* eventAttrib) { nvtxMarkEx(eventAttrib); } inline void Mark(const char* message) { nvtxMarkA(message); } inline void Mark(const wchar_t* message) { nvtxMarkW(message); } inline nvtxRangeId_t RangeStart(const nvtx::Attributes& attrib) { return nvtxRangeStartEx(attrib.out()); } inline nvtxRangeId_t RangeStart(const nvtxEventAttributes_t* eventAttrib) { return nvtxRangeStartEx(eventAttrib); } inline nvtxRangeId_t RangeStart(const char* message) { return nvtxRangeStartA(message); } inline nvtxRangeId_t RangeStart(const wchar_t* message) { return nvtxRangeStartW(message); } inline void RangeEnd(nvtxRangeId_t id) { nvtxRangeEnd(id); } inline int RangePush(const nvtx::Attributes& attrib) { return nvtxRangePushEx(attrib.out()); } inline int RangePush(const nvtxEventAttributes_t* eventAttrib) { return nvtxRangePushEx(eventAttrib); } inline int RangePush(const char* message) { return nvtxRangePushA(message); } inline int RangePush(const wchar_t* message) { return nvtxRangePushW(message); } inline void RangePop() { nvtxRangePop(); } inline void NameCategory(uint32_t category, const char* name) { nvtxNameCategoryA(category, name); } inline void NameCategory(uint32_t category, const wchar_t* name) { nvtxNameCategoryW(category, name); } inline void NameOsThread(uint32_t threadId, const char* name) { nvtxNameOsThreadA(threadId, name); } inline void NameOsThread(uint32_t threadId, const wchar_t* name) { nvtxNameOsThreadW(threadId, name); } inline void NameCurrentThread(const char* name) { nvtxNameOsThreadA( uint32_t(physx::shdfnd::Thread::getId()), name); } inline void NameCurrentThread(const wchar_t* name) { nvtxNameOsThreadW( uint32_t(physx::shdfnd::Thread::getId()), name); } template <bool TEnabled> class TemplateEnabledRange: public ScopedRange { public: TemplateEnabledRange(const char* message): ScopedRange(message) {} TemplateEnabledRange(const wchar_t* message): ScopedRange(message) {} TemplateEnabledRange(const nvtxEventAttributes_t* attributes): ScopedRange(attributes) {} TemplateEnabledRange(const Attributes& attributes): ScopedRange(attributes) {} ~TemplateEnabledRange() {} }; template <> class TemplateEnabledRange<false> { public: TemplateEnabledRange(const char* message) { (void)message; } TemplateEnabledRange(const wchar_t* message) { (void)message; } TemplateEnabledRange(const nvtxEventAttributes_t* attributes) { (void)attributes; } TemplateEnabledRange(const Attributes& attributes) { (void)attributes; } ~TemplateEnabledRange() {} }; class RuntimeEnabledScope { bool mEnabled; public: inline RuntimeEnabledScope(const char* message, bool enabled): mEnabled(enabled) { if(enabled) nvtxRangePushA(message); } inline RuntimeEnabledScope(const wchar_t* message, bool enabled): mEnabled(enabled) { if(enabled) nvtxRangePushW(message); } inline RuntimeEnabledScope(const nvtxEventAttributes_t* attributes, bool enabled): mEnabled(enabled) { if(enabled) nvtxRangePushEx(attributes); } inline RuntimeEnabledScope(const nvtx::Attributes& attributes, bool enabled): mEnabled(enabled) { if(enabled) nvtxRangePushEx(attributes.out()); } inline ~RuntimeEnabledScope() { if(mEnabled) nvtxRangePop(); } }; struct EventIdContextPair { EventIdContextPair(): context(physx::PxU64(-1)), id(physx::PxU16(-1)) {} EventIdContextPair(physx::PxU64 c, physx::PxU16 i): context(c), id(i) {} PX_FORCE_INLINE bool operator==(const EventIdContextPair& p) const { return (context==p.context) && (id==p.id); } physx::PxU64 context; physx::PxU16 id; }; template<class Key> struct Hash { }; // hash object for hash map template parameter template <> struct Hash<EventIdContextPair> { physx::PxU32 operator()(const EventIdContextPair& k) const { return physx::shdfnd::hash((physx::PxU64(k.id)<<32) | (k.context&0xffffffff)); } bool operator()(const EventIdContextPair& k0, const EventIdContextPair& k1) const { return k0 == k1; } }; typedef Hash<EventIdContextPair> EventHash; typedef physx::shdfnd::HashMap<nvtx::EventIdContextPair, nvtxRangeId_t, nvtx::EventHash> EventHashMap; #define NV_TEXT_COL(_c) (((((_c)*7)&255)<<8)+0xff8300de) #define NV_TEXT_PROFILE_START( _p, _id) nvtx::Attributes a; physx::PxU32 c = physx::PxU32((_p).getEventContext()); nvtx::RangePush(a.color(NV_TEXT_COL(c)).message(_p.getStringFromId(_id.mEventId))); #define NV_TEXT_PROFILE_STOP( _p, _id) nvtx::RangePop(); #define NV_TEXT_PROFILE_ZONE( _p, _id) nvtx::Attributes a; physx::PxU32 c = physx::PxU32((_p).getEventContext()); nvtx::RuntimeEnabledScope __nvtxZone(a.color(NV_TEXT_COL(c)).message(_p.getStringFromId(_id.mEventId)).category(c), _id.mCompileTimeEnabled); #define NV_TEXT_PROFILE_ZONE_WITH_SUBSYSTEM( _p, subsystem, eventId ) nvtx::Attributes a; physx::PxU32 c = physx::PxU32((_p).getEventProfiler().getEventContext()); nvtx::TemplateEnabledRange<PX_PROFILE_EVENT_FILTER_VALUE(subsystem,eventId)> __nvtxZone(a.color(NV_TEXT_COL(c)).message(#subsystem "." #eventId).category(c)); #define NV_TEXT_PROFILE_VALUE( _p, subsystem, eventId, value ) if(PX_PROFILE_EVENT_FILTER_VALUE(subsystem,eventId)){nvtx::Attributes attr; physx::PxU32 c = physx::PxU32((_p).getEventProfiler().getEventContext()); nvtx::Mark(attr.color(NV_TEXT_COL(c)).category(c).payload(value).message(#subsystem "." #eventId)); } #define NV_TEXT_PROFILE_START_CROSSTHREAD( _p, _id) \ if (_id.mCompileTimeEnabled) { nvtx::Attributes a ;physx::PxU32 c = physx::PxU32((_p).getEventContext()); _p.storeCrossEvent(_id.mEventId, _p.getEventContext(), nvtx::RangeStart(a.color(NV_TEXT_COL(c)).message(_p.getStringFromId(_id.mEventId)).category(c))); } #define NV_TEXT_PROFILE_STOP_CROSSTHREAD( _p, _id) \ if (_id.mCompileTimeEnabled) { nvtx::RangeEnd(_p.getCrossEvent(_id.mEventId, _p.getEventContext())); } } // namespace nvtx #else #define NV_TEXT_COL(_p) #define NV_TEXT_PROFILE_START( _p, _id) #define NV_TEXT_PROFILE_STOP( _p, _id) #define NV_TEXT_PROFILE_ZONE( _p, _id) #define NV_TEXT_PROFILE_ZONE_WITH_SUBSYSTEM( _p, subsystem, eventId ) #define NV_TEXT_PROFILE_VALUE( _p, subsystem, eventId, value ) #define NV_TEXT_PROFILE_START_CROSSTHREAD( _p, _id) #define NV_TEXT_PROFILE_STOP_CROSSTHREAD( _p, _id) #endif // defined PX_NVTX #endif
36.426056
323
0.754471
e5829f1b13bc8427412ffbf7cf2ac99f4bd22b0c
2,300
h
C
DXLiveDevelopProject/DXLiveDevelopProject/Live/gensee_3_6_4/RtSDK.framework/Headers/GSBroadcastDocumentDelegate.h
sandradd/DXLive
035cac86a3c4231a51881245a6ebe549fd50dd28
[ "MIT" ]
1
2020-05-11T07:11:54.000Z
2020-05-11T07:11:54.000Z
DXLiveDevelopProject/DXLiveDevelopProject/Live/gensee_3_6_4/RtSDK.framework/Headers/GSBroadcastDocumentDelegate.h
sandradd/DXLive
035cac86a3c4231a51881245a6ebe549fd50dd28
[ "MIT" ]
null
null
null
DXLiveDevelopProject/DXLiveDevelopProject/Live/gensee_3_6_4/RtSDK.framework/Headers/GSBroadcastDocumentDelegate.h
sandradd/DXLive
035cac86a3c4231a51881245a6ebe549fd50dd28
[ "MIT" ]
null
null
null
// // GSBroadcastDocumentDelegate.h // RtSDK // // Created by Gaojin Hsu on 6/29/16. // Copyright © 2016 Geensee. All rights reserved. // #import <Foundation/Foundation.h> /** * 直播文档代理,接收直播文档信息回调 */ @protocol GSBroadcastDocumentDelegate <NSObject> @required /** * 文档模块初始化反馈代理 * * @param manager 触发此代理的GSBroadcastManager对象 * @param result 布尔值表示初始化是否成功,YES表示成功 * @see GSBroadcastManager */ - (void)broadcastManager:(GSBroadcastManager*)manager didReceiveDocModuleInitResult:(BOOL)result; @optional /** * 文档打开代理 * * @param manager 触发此代理的GSBroadcastManager对象 * @see GSBroadcastManager */ - (void)broadcastManager:(GSBroadcastManager *)manager didOpenDocument:(GSDocument*)doc; /** * 文档关闭代理 * * @param manager 触发此代理的GSBroadcastManager对象 * @see GSBroadcastManager */ - (void)broadcastManager:(GSBroadcastManager *)manager didCloseDocument:(unsigned)docID; /** * 文档切换代理 * * @param manager 触发此代理的GSBroadcastManager对象 * @see GSBroadcastManager */ - (void)broadcastManager:(GSBroadcastManager*)manager didSlideToPage:(unsigned)pageID ofDoc:(unsigned)docID step:(int)step; /** * 文档收到标注代理 * * @param manager 触发此代理的GSBroadcastManager对象 * @param anno 标注对象 * @param pageID 标注所属Page的pageID * @param docID 标注所属的Doc的docID */ - (void)broadcastManager:(GSBroadcastManager*)manager didReceiveAnno:(GSAnnoBase*)anno onPage:(unsigned int)pageID ofDoc:(unsigned int)docID ; /** * 文档删除标注代理 * * @param manager 触发此代理的GSBroadcastManager对象 * @param annoID 删除标注的ID * @param pageID 删除标注所属的Page的pageID * @param docID 删除标注所属的Doc的docID */ - (void)broadcastManager:(GSBroadcastManager*)manager didRemoveAnno:(long long)annoID onPage:(unsigned int)pageID ofDoc:(unsigned int)docID; /** * 文档页加载完成代理 * * @param manager 触发此代理的GSBroadcastManager对象 * @param page 加载完的文档页对象 * @param docID 文档页所属的Doc的docID */ - (void)broadcastManager:(GSBroadcastManager*)manager didFinishLoadingPage:(GSDocPage*)page ofDoc:(unsigned int)docID; /** * 文档是否保存到服务器代理 * * @param manager 触发此代理的GSBroadcastManager对象 * @param docID 文档的docID * @param bSaved 是否保存到服务器 * @param isBySelf 是否是自己保存的,YES表示是 */ - (void)broadcastManager:(GSBroadcastManager*)manager doc:(unsigned int)docID savedOnServer:(BOOL)bSaved bySelf:(BOOL)isBySelf; @end
22.772277
142
0.737826
8cbff571355a45ef931edb9b58b2e37b595d5484
8,217
c
C
external/prowiz/r/FuzzacPacker.c
demozoo/open_depacker
3d5b41cd159d5d3288de133c69c7ee7fb9605b6c
[ "Apache-2.0" ]
3
2018-01-04T13:13:56.000Z
2019-05-04T11:54:25.000Z
external/prowiz/r/FuzzacPacker.c
emoon/OpenDepacker
3d5b41cd159d5d3288de133c69c7ee7fb9605b6c
[ "Apache-2.0" ]
6
2016-01-12T15:20:50.000Z
2016-01-13T13:43:07.000Z
external/prowiz/r/FuzzacPacker.c
emoon/OpenDepacker
3d5b41cd159d5d3288de133c69c7ee7fb9605b6c
[ "Apache-2.0" ]
null
null
null
/* testFUZZAC() */ /* Rip_Fuzzac() */ /* Depack_Fuzzac() */ #include "globals.h" #include "extern.h" int16_t testFUZZAC ( void ) { PW_Start_Address = PW_i; /* test finetune */ for ( PW_k=0 ; PW_k<31 ; PW_k++ ) { if ( in_data[PW_Start_Address+72+PW_k*68] > 0x0F ) { return BAD; } } /* test volumes */ for ( PW_k=0 ; PW_k<31 ; PW_k++ ) { if ( in_data[PW_Start_Address+73+PW_k*68] > 0x40 ) { return BAD; } } /* test sample sizes */ PW_WholeSampleSize = 0; for ( PW_k=0 ; PW_k<31 ; PW_k++ ) { PW_j = (in_data[PW_Start_Address+66+PW_k*68]*256)+in_data[PW_Start_Address+67+PW_k*68]; if ( PW_j > 0x8000 ) { return BAD; } PW_WholeSampleSize += (PW_j * 2); } /* test size of pattern list */ if ( in_data[PW_Start_Address+2114] == 0x00 ) { return BAD; } return GOOD; } void Rip_Fuzzac ( void ) { /* PW_WholeSampleSize IS still the whole sample size */ PW_j = in_data[PW_Start_Address+2114]; PW_k = in_data[PW_Start_Address+2115]; OutputSize = PW_WholeSampleSize + (PW_j*16) + (PW_k*256) + 2118 + 4; CONVERT = GOOD; Save_Rip ( "Fuzzac packer module", Fuzzac ); if ( Save_Status == GOOD ) PW_i += (OutputSize - 2); /* -1 should do but call it "just to be sure" :) */ } /* * fuzzac.c 1997 (c) Asle / ReDoX * * Converts Fuzzac packed MODs back to PTK MODs * thanks to Gryzor and his ProWizard tool ! ... without it, this prog * would not exist !!! * * Note: A most worked-up prog ... took some time to finish this !. * there's what lot of my other depacker are missing : the correct * pattern order (most of the time the list is generated badly ..). * Dont know why I did it for this depacker because I've but one * exemple file ! :). * * Last update: 30/11/99 * - removed open() (and other fread()s and the like) * - general Speed & Size Optmizings * - memory leak bug corrected (thx to Thomas Neumann) * - SEnd ID bypassed REALLY now :) (Thomas Neumann again !) */ #define ON 1 #define OFF 2 void Depack_Fuzzac ( void ) { uint8_t c5; uint8_t PatPos; uint8_t *Whatever; uint8_t NbrTracks; uint8_t Track_Numbers[128][16]; uint8_t Track_Numbers_Real[128][4]; uint8_t Track_Datas[4][256]; uint8_t Status=ON; int32_t WholeSampleSize=0; int32_t i,j,k,l; int32_t Where = PW_Start_Address; FILE *out; if ( Save_Status == BAD ) return; BZERO ( Track_Numbers , 128*16 ); BZERO ( Track_Numbers_Real , 128*4 ); sprintf ( Depacked_OutName , "%d.mod" , Cpt_Filename-1 ); out = PW_fopen ( Depacked_OutName , "w+b" ); /* bypass ID */ /* bypass 2 unknown bytes */ Where += 6; /* write title */ Whatever = (uint8_t *) malloc (1024); BZERO ( Whatever , 1024 ); fwrite ( Whatever , 20 , 1 , out ); /*printf ( "Converting header ... " );*/ /*fflush ( stdout );*/ for ( i=0 ; i<31 ; i++ ) { /*sample name*/ fwrite ( &in_data[Where] , 22 , 1 , out ); WholeSampleSize += (((in_data[Where+60]*256)+in_data[Where+61])*2); fwrite ( &in_data[Where+60] , 2 , 1 , out ); fwrite ( &in_data[Where+66] , 2 , 1 , out ); fwrite ( &in_data[Where+62] , 2 , 1 , out ); Whatever[0] = in_data[Where+65]; if ( (in_data[Where+64]==0x00) && (in_data[Where+65]==0x00) ) Whatever[0] = 0x01; fwrite ( &in_data[Where+64] , 1 , 1 , out ); fwrite ( Whatever , 1 , 1 , out ); Where += 68; } /*printf ( "ok\n" );*/ /*printf ( " - Whole sample size : %ld\n" , WholeSampleSize );*/ /* read & write size of pattern list */ PatPos = in_data[Where++]; fwrite ( &PatPos , 1 , 1 , out ); /*printf ( " - size of pattern list : %d\n" , PatPos );*/ /* read the number of tracks */ NbrTracks = in_data[Where++]; /* write noisetracker byte */ Whatever[0] = 0x7f; fwrite ( Whatever , 1 , 1 , out ); /* place file pointer at track number list address */ Where = PW_Start_Address + 2118; /* read tracks numbers */ for ( i=0 ; i<4 ; i++ ) { for ( j=0 ; j<PatPos ; j++ ) { Track_Numbers[j][i*4] = in_data[Where++]; Track_Numbers[j][i*4+1] = in_data[Where++]; Track_Numbers[j][i*4+2] = in_data[Where++]; Track_Numbers[j][i*4+3] = in_data[Where++]; } } /* sort tracks numbers */ c5 = 0x00; for ( i=0 ; i<PatPos ; i++ ) { if ( i == 0 ) { Whatever[0] = c5; c5 += 0x01; continue; } for ( j=0 ; j<i ; j++ ) { Status = ON; for ( k=0 ; k<4 ; k++ ) { if ( Track_Numbers[j][k*4] != Track_Numbers[i][k*4] ) { Status=OFF; break; } } if ( Status == ON ) { Whatever[i] = Whatever[j]; break; } } if ( Status == OFF ) { Whatever[i] = c5; c5 += 0x01; } Status = ON; } /* c5 is the Max pattern number */ /* create a real list of tracks numbers for the really existing patterns */ Whatever[129] = 0x00; for ( i=0 ; i<PatPos ; i++ ) { if ( i==0 ) { Track_Numbers_Real[Whatever[129]][0] = Track_Numbers[i][0]; Track_Numbers_Real[Whatever[129]][1] = Track_Numbers[i][4]; Track_Numbers_Real[Whatever[129]][2] = Track_Numbers[i][8]; Track_Numbers_Real[Whatever[129]][3] = Track_Numbers[i][12]; Whatever[129] += 0x01; continue; } for ( j=0 ; j<i ; j++ ) { Status = ON; if ( Whatever[i] == Whatever[j] ) { Status = OFF; break; } } if ( Status == OFF ) continue; Track_Numbers_Real[Whatever[129]][0] = Track_Numbers[i][0]; Track_Numbers_Real[Whatever[129]][1] = Track_Numbers[i][4]; Track_Numbers_Real[Whatever[129]][2] = Track_Numbers[i][8]; Track_Numbers_Real[Whatever[129]][3] = Track_Numbers[i][12]; Whatever[129] += 0x01; Status = ON; } /* write pattern list */ fwrite ( Whatever , 128 , 1 , out ); /* write ID */ Whatever[0] = 'M'; Whatever[1] = '.'; Whatever[2] = 'K'; Whatever[3] = '.'; fwrite ( Whatever , 4 , 1 , out ); /* pattern data */ /*printf ( "Processing the pattern datas ... " );*/ /*fflush ( stdout );*/ l = PW_Start_Address + 2118 + (PatPos * 16); for ( i=0 ; i<c5 ; i++ ) { BZERO ( Whatever , 1024 ); BZERO ( Track_Datas , 4*256 ); Where = l + (Track_Numbers_Real[i][0]*256); for ( j=0 ; j<256 ; j++ ) Track_Datas[0][j] = in_data[Where+j]; Where = l + (Track_Numbers_Real[i][1]*256); for ( j=0 ; j<256 ; j++ ) Track_Datas[1][j] = in_data[Where+j]; Where = l + (Track_Numbers_Real[i][2]*256); for ( j=0 ; j<256 ; j++ ) Track_Datas[2][j] = in_data[Where+j]; Where = l + (Track_Numbers_Real[i][3]*256); for ( j=0 ; j<256 ; j++ ) Track_Datas[3][j] = in_data[Where+j]; for ( j=0 ; j<64 ; j++ ) { Whatever[j*16] = Track_Datas[0][j*4]; Whatever[j*16+1] = Track_Datas[0][j*4+1]; Whatever[j*16+2] = Track_Datas[0][j*4+2]; Whatever[j*16+3] = Track_Datas[0][j*4+3]; Whatever[j*16+4] = Track_Datas[1][j*4]; Whatever[j*16+5] = Track_Datas[1][j*4+1]; Whatever[j*16+6] = Track_Datas[1][j*4+2]; Whatever[j*16+7] = Track_Datas[1][j*4+3]; Whatever[j*16+8] = Track_Datas[2][j*4]; Whatever[j*16+9] = Track_Datas[2][j*4+1]; Whatever[j*16+10] = Track_Datas[2][j*4+2]; Whatever[j*16+11] = Track_Datas[2][j*4+3]; Whatever[j*16+12] = Track_Datas[3][j*4]; Whatever[j*16+13] = Track_Datas[3][j*4+1]; Whatever[j*16+14] = Track_Datas[3][j*4+2]; Whatever[j*16+15] = Track_Datas[3][j*4+3]; } fwrite ( Whatever , 1024 , 1 , out ); /*printf ( "+" );*/ /*fflush ( stdout );*/ } free ( Whatever ); /*printf ( "ok\n" );*/ /* sample data */ /*printf ( "Saving sample data ... " );*/ /*fflush ( stdout );*/ Where = l + 4 + NbrTracks*256; /* l : 2118 + NumberOfPattern*16+PW_Start_Address */ /* 4 : to bypass the "SEnd" unidentified ID */ fwrite ( &in_data[Where] , WholeSampleSize , 1 , out ); /*printf ( "ok\n" );*/ /* crap ... */ Crap ( " FUZZAC Packer " , BAD , BAD , out ); fflush ( out ); fclose ( out ); printf ( "done\n" ); return; /* useless ... but */ }
25.678125
91
0.555312
f42ae0076100a87c723fe8903c1bc60df66f7a53
21,769
c
C
sdk-6.5.20/src/soc/dpp/ARAD/arad_api_ingress_packet_queuing.c
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
sdk-6.5.20/src/soc/dpp/ARAD/arad_api_ingress_packet_queuing.c
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
sdk-6.5.20/src/soc/dpp/ARAD/arad_api_ingress_packet_queuing.c
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
#include <soc/mcm/memregs.h> #if defined(BCM_88650_A0) /* * 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. */ #ifdef _ERR_MSG_MODULE_NAME #error "_ERR_MSG_MODULE_NAME redefined" #endif #define _ERR_MSG_MODULE_NAME BSL_SOC_INGRESS #include <shared/bsl.h> #include <soc/dcmn/error.h> #include <soc/dpp/cosq.h> #include <soc/dpp/SAND/Utils/sand_header.h> #include <soc/dpp/ARAD/arad_ingress_packet_queuing.h> #include <soc/dpp/ARAD/arad_api_general.h> #include <soc/dpp/SAND/Management/sand_general_macros.h> #include <soc/dpp/ARAD/arad_sw_db.h> #include <soc/dpp/ARAD/arad_general.h> int arad_ipq_explicit_mapping_mode_info_set( SOC_SAND_IN int unit, SOC_SAND_IN ARAD_IPQ_EXPLICIT_MAPPING_MODE_INFO *info ) { uint32 res; SOCDNX_INIT_FUNC_DEFS; res = arad_ipq_explicit_mapping_mode_info_verify(unit, info); SOCDNX_SAND_IF_ERR_EXIT(res); res = arad_ipq_explicit_mapping_mode_info_set_unsafe(unit, info); SOCDNX_SAND_IF_ERR_EXIT(res); exit: SOCDNX_FUNC_RETURN; } int arad_ipq_explicit_mapping_mode_info_get( SOC_SAND_IN int unit, SOC_SAND_OUT ARAD_IPQ_EXPLICIT_MAPPING_MODE_INFO *info ) { uint32 res; SOCDNX_INIT_FUNC_DEFS; res = arad_ipq_explicit_mapping_mode_info_get_unsafe(unit, info); SOCDNX_SAND_IF_ERR_EXIT(res); exit: SOCDNX_FUNC_RETURN; } uint32 arad_ipq_traffic_class_map_set( SOC_SAND_IN int unit, SOC_SAND_IN ARAD_IPQ_TR_CLS tr_cls_ndx, SOC_SAND_IN ARAD_IPQ_TR_CLS new_class ) { uint32 res; SOC_SAND_INIT_ERROR_DEFINITIONS(ARAD_IPQ_TRAFFIC_CLASS_MAP_SET); SOC_SAND_CHECK_DRIVER_AND_DEVICE; res = arad_ipq_traffic_class_map_verify( unit, tr_cls_ndx, new_class ); SOC_SAND_CHECK_FUNC_RESULT(res, 10, exit); SOC_SAND_TAKE_DEVICE_SEMAPHORE; res = arad_ipq_traffic_class_map_set_unsafe( unit, tr_cls_ndx, new_class ); SOC_SAND_CHECK_FUNC_RESULT(res, 100, exit_semaphore); exit_semaphore: SOC_SAND_GIVE_DEVICE_SEMAPHORE; exit: SOC_SAND_EXIT_AND_SEND_ERROR( "error in arad_ipq_traffic_class_map_set()",0,0); } uint32 arad_ipq_traffic_class_map_get( SOC_SAND_IN int unit, SOC_SAND_IN ARAD_IPQ_TR_CLS tr_cls_ndx, SOC_SAND_OUT ARAD_IPQ_TR_CLS *new_class ) { uint32 res; SOC_SAND_INIT_ERROR_DEFINITIONS(ARAD_IPQ_TRAFFIC_CLASS_MAP_GET); SOC_SAND_CHECK_DRIVER_AND_DEVICE; SOC_SAND_CHECK_NULL_INPUT(new_class); SOC_SAND_TAKE_DEVICE_SEMAPHORE; res = arad_ipq_traffic_class_map_get_unsafe( unit, tr_cls_ndx, new_class ); SOC_SAND_CHECK_FUNC_RESULT(res, 100, exit_semaphore); exit_semaphore: SOC_SAND_GIVE_DEVICE_SEMAPHORE; exit: SOC_SAND_EXIT_AND_SEND_ERROR( "error in arad_ipq_traffic_class_map_get()",0,0); } int arad_ipq_traffic_class_multicast_priority_map_set( SOC_SAND_IN int unit, SOC_SAND_IN uint32 traffic_class, SOC_SAND_IN uint8 enable ) { uint32 res; SOCDNX_INIT_FUNC_DEFS; res = arad_ipq_traffic_class_multicast_priority_map_set_verify( unit, traffic_class, enable ); SOCDNX_SAND_IF_ERR_EXIT(res); res = arad_ipq_traffic_class_multicast_priority_map_set_unsafe( unit, traffic_class, enable ); SOCDNX_SAND_IF_ERR_EXIT(res); exit: SOCDNX_FUNC_RETURN; } int arad_ipq_traffic_class_multicast_priority_map_get( SOC_SAND_IN int unit, SOC_SAND_IN uint32 traffic_class, SOC_SAND_OUT uint8 *enable ) { uint32 res; SOCDNX_INIT_FUNC_DEFS; SOCDNX_NULL_CHECK(enable); res = arad_ipq_traffic_class_multicast_priority_map_get_verify( unit, traffic_class, enable ); SOCDNX_SAND_IF_ERR_EXIT(res); res = arad_ipq_traffic_class_multicast_priority_map_get_unsafe( unit, traffic_class, enable ); SOCDNX_SAND_IF_ERR_EXIT(res); exit: SOCDNX_FUNC_RETURN; } uint32 arad_ipq_destination_id_packets_base_queue_id_set( SOC_SAND_IN int unit, SOC_SAND_IN int core, SOC_SAND_IN uint32 dest_ndx, SOC_SAND_IN uint8 valid, SOC_SAND_IN uint8 sw_only, SOC_SAND_IN uint32 base_queue ) { uint32 res; SOC_SAND_INIT_ERROR_DEFINITIONS(ARAD_IPQ_DESTINATION_ID_PACKETS_BASE_QUEUE_ID_SET); SOC_SAND_CHECK_DRIVER_AND_DEVICE; res = arad_ipq_destination_id_packets_base_queue_id_verify( unit, core, dest_ndx, valid, sw_only, base_queue ); SOC_SAND_CHECK_FUNC_RESULT(res, 10, exit); SOC_SAND_TAKE_DEVICE_SEMAPHORE; res = arad_ipq_destination_id_packets_base_queue_id_set_unsafe( unit, core, dest_ndx, valid, sw_only, base_queue ); SOC_SAND_CHECK_FUNC_RESULT(res, 100, exit_semaphore); exit_semaphore: SOC_SAND_GIVE_DEVICE_SEMAPHORE; exit: SOC_SAND_EXIT_AND_SEND_ERROR( "error in arad_ipq_destination_id_packets_base_queue_id_set()",0,0); } uint32 arad_ipq_destination_id_packets_base_queue_id_get( SOC_SAND_IN int unit, SOC_SAND_IN int core, SOC_SAND_IN uint32 dest_ndx, SOC_SAND_OUT uint8 *valid, SOC_SAND_OUT uint8 *sw_only, SOC_SAND_OUT uint32 *base_queue ) { uint32 res; SOC_SAND_INIT_ERROR_DEFINITIONS(ARAD_IPQ_DESTINATION_ID_PACKETS_BASE_QUEUE_ID_GET); SOC_SAND_CHECK_DRIVER_AND_DEVICE; SOC_SAND_CHECK_NULL_INPUT(valid); SOC_SAND_CHECK_NULL_INPUT(base_queue); SOC_SAND_TAKE_DEVICE_SEMAPHORE; res = arad_ipq_destination_id_packets_base_queue_id_get_unsafe( unit, core, dest_ndx, valid, sw_only, base_queue ); SOC_SAND_CHECK_FUNC_RESULT(res, 100, exit_semaphore); exit_semaphore: SOC_SAND_GIVE_DEVICE_SEMAPHORE; exit: SOC_SAND_EXIT_AND_SEND_ERROR( "error in arad_ipq_destination_id_packets_base_queue_id_get()",0,0); } uint32 arad_ipq_stack_lag_packets_base_queue_id_set( SOC_SAND_IN int unit, SOC_SAND_IN uint32 tmd, SOC_SAND_IN uint32 entry, SOC_SAND_IN uint32 base_queue ) { uint32 res; SOC_SAND_INIT_ERROR_DEFINITIONS(0); SOC_SAND_CHECK_DRIVER_AND_DEVICE; res = arad_ipq_stack_lag_packets_base_queue_id_verify(unit, tmd, entry, base_queue); SOC_SAND_CHECK_FUNC_RESULT(res, 10, exit); SOC_SAND_TAKE_DEVICE_SEMAPHORE; res = arad_ipq_stack_lag_packets_base_queue_id_set_unsafe(unit, tmd, entry,base_queue); SOC_SAND_CHECK_FUNC_RESULT(res, 100, exit_semaphore); exit_semaphore: SOC_SAND_GIVE_DEVICE_SEMAPHORE; exit: SOC_SAND_EXIT_AND_SEND_ERROR( "error in arad_ipq_stack_lag_packets_base_queue_id_set()",0,0); } uint32 arad_ipq_stack_lag_packets_base_queue_id_get( SOC_SAND_IN int unit, SOC_SAND_IN uint32 tmd, SOC_SAND_IN uint32 entry, SOC_SAND_OUT uint32 *base_queue ) { uint32 res; SOC_SAND_INIT_ERROR_DEFINITIONS(0); SOC_SAND_CHECK_DRIVER_AND_DEVICE; SOC_SAND_CHECK_NULL_INPUT(base_queue); SOC_SAND_TAKE_DEVICE_SEMAPHORE; res = arad_ipq_stack_lag_packets_base_queue_id_get_unsafe(unit, tmd, entry, base_queue); SOC_SAND_CHECK_FUNC_RESULT(res, 100, exit_semaphore); exit_semaphore: SOC_SAND_GIVE_DEVICE_SEMAPHORE; exit: SOC_SAND_EXIT_AND_SEND_ERROR( "error in arad_ipq_stack_lag_packets_base_queue_id_get()",0,0); } uint32 arad_ipq_stack_fec_map_stack_lag_set( SOC_SAND_IN int unit, SOC_SAND_IN uint32 tmd, SOC_SAND_IN uint32 entry, SOC_SAND_IN uint32 stack_lag ) { uint32 res; SOC_SAND_INIT_ERROR_DEFINITIONS(0); SOC_SAND_CHECK_DRIVER_AND_DEVICE; res = arad_ipq_stack_fec_map_stack_lag_verify(unit, tmd, entry, stack_lag); SOC_SAND_CHECK_FUNC_RESULT(res, 10, exit); SOC_SAND_TAKE_DEVICE_SEMAPHORE; res = arad_ipq_stack_fec_map_stack_lag_set_unsafe(unit, tmd, entry,stack_lag); SOC_SAND_CHECK_FUNC_RESULT(res, 100, exit_semaphore); exit_semaphore: SOC_SAND_GIVE_DEVICE_SEMAPHORE; exit: SOC_SAND_EXIT_AND_SEND_ERROR( "error in arad_ipq_stack_fec_map_stack_lag_set()",0,0); } uint32 arad_ipq_stack_fec_map_stack_lag_get( SOC_SAND_IN int unit, SOC_SAND_IN uint32 tmd, SOC_SAND_IN uint32 entry, SOC_SAND_OUT uint32* stack_lag ) { uint32 res; SOC_SAND_INIT_ERROR_DEFINITIONS(0); SOC_SAND_CHECK_DRIVER_AND_DEVICE; SOC_SAND_CHECK_NULL_INPUT(stack_lag); res = arad_ipq_stack_fec_map_stack_lag_verify(unit, tmd, entry, 0); SOC_SAND_CHECK_FUNC_RESULT(res, 10, exit); SOC_SAND_TAKE_DEVICE_SEMAPHORE; res = arad_ipq_stack_fec_map_stack_lag_get_unsafe(unit, tmd, entry, stack_lag); SOC_SAND_CHECK_FUNC_RESULT(res, 100, exit_semaphore); exit_semaphore: SOC_SAND_GIVE_DEVICE_SEMAPHORE; exit: SOC_SAND_EXIT_AND_SEND_ERROR( "error in arad_ipq_stack_fec_map_stack_lag_get()",0,0); } uint32 arad_ipq_queue_interdigitated_mode_set( SOC_SAND_IN int unit, SOC_SAND_IN int core, SOC_SAND_IN uint32 k_queue_ndx, SOC_SAND_IN uint8 is_interdigitated ) { uint32 res; SOC_SAND_INIT_ERROR_DEFINITIONS(ARAD_IPQ_QUEUE_INTERDIGITATED_MODE_SET); SOC_SAND_CHECK_DRIVER_AND_DEVICE; res = arad_ipq_queue_interdigitated_mode_verify( unit, core, k_queue_ndx, is_interdigitated ); SOC_SAND_CHECK_FUNC_RESULT(res, 10, exit); SOC_SAND_TAKE_DEVICE_SEMAPHORE; res = arad_ipq_queue_interdigitated_mode_set_unsafe( unit, core, k_queue_ndx, is_interdigitated ); SOC_SAND_CHECK_FUNC_RESULT(res, 100, exit_semaphore); exit_semaphore: SOC_SAND_GIVE_DEVICE_SEMAPHORE; exit: SOC_SAND_EXIT_AND_SEND_ERROR( "error in arad_ipq_queue_interdigitated_mode_set()",0,0); } uint32 arad_ipq_queue_interdigitated_mode_get( SOC_SAND_IN int unit, SOC_SAND_IN int core, SOC_SAND_IN uint32 k_queue_ndx, SOC_SAND_OUT uint8 *is_interdigitated ) { uint32 res; SOC_SAND_INIT_ERROR_DEFINITIONS(ARAD_IPQ_QUEUE_INTERDIGITATED_MODE_GET); SOC_SAND_CHECK_DRIVER_AND_DEVICE; SOC_SAND_CHECK_NULL_INPUT(is_interdigitated); SOC_SAND_TAKE_DEVICE_SEMAPHORE; res = arad_ipq_queue_interdigitated_mode_get_unsafe( unit, core, k_queue_ndx, is_interdigitated ); SOC_SAND_CHECK_FUNC_RESULT(res, 100, exit_semaphore); exit_semaphore: SOC_SAND_GIVE_DEVICE_SEMAPHORE; exit: SOC_SAND_EXIT_AND_SEND_ERROR( "error in arad_ipq_queue_interdigitated_mode_get()",0,0); } uint32 arad_ipq_queue_to_flow_mapping_set( SOC_SAND_IN int unit, SOC_SAND_IN int core, SOC_SAND_IN uint32 queue_quartet_ndx, SOC_SAND_IN ARAD_IPQ_QUARTET_MAP_INFO *info ) { uint32 res; SOC_SAND_INIT_ERROR_DEFINITIONS(ARAD_IPQ_QUEUE_TO_FLOW_MAPPING_SET); SOC_SAND_CHECK_DRIVER_AND_DEVICE; SOC_SAND_CHECK_NULL_INPUT(info); SOC_SAND_TAKE_DEVICE_SEMAPHORE; res = arad_ipq_queue_to_flow_mapping_verify( unit, core, queue_quartet_ndx, info ); SOC_SAND_CHECK_FUNC_RESULT(res, 10, exit_semaphore); res = arad_ipq_queue_to_flow_mapping_set_unsafe( unit, core, queue_quartet_ndx, info ); SOC_SAND_CHECK_FUNC_RESULT(res, 100, exit_semaphore); exit_semaphore: SOC_SAND_GIVE_DEVICE_SEMAPHORE; exit: SOC_SAND_EXIT_AND_SEND_ERROR( "error in arad_ipq_queue_to_flow_mapping_set()",0,0); } uint32 arad_ipq_queue_to_flow_mapping_get( SOC_SAND_IN int unit, SOC_SAND_IN int core, SOC_SAND_IN uint32 queue_quartet_ndx, SOC_SAND_OUT ARAD_IPQ_QUARTET_MAP_INFO *info ) { uint32 res; SOC_SAND_INIT_ERROR_DEFINITIONS(ARAD_IPQ_QUEUE_TO_FLOW_MAPPING_GET); SOC_SAND_CHECK_DRIVER_AND_DEVICE; SOC_SAND_CHECK_NULL_INPUT(info); SOC_SAND_TAKE_DEVICE_SEMAPHORE; res = arad_ipq_queue_to_flow_mapping_get_unsafe( unit, core, queue_quartet_ndx, info ); SOC_SAND_CHECK_FUNC_RESULT(res, 100, exit_semaphore); exit_semaphore: SOC_SAND_GIVE_DEVICE_SEMAPHORE; exit: SOC_SAND_EXIT_AND_SEND_ERROR( "error in arad_ipq_queue_to_flow_mapping_get()",0,0); } uint32 arad_ipq_queue_qrtt_unmap( SOC_SAND_IN int unit, SOC_SAND_IN int core, SOC_SAND_IN uint32 queue_quartet_ndx ) { uint32 res = SOC_SAND_OK; SOC_SAND_INIT_ERROR_DEFINITIONS(ARAD_IPQ_QUEUE_QRTT_UNMAP); SOC_SAND_CHECK_DRIVER_AND_DEVICE; SOC_SAND_TAKE_DEVICE_SEMAPHORE; res = arad_ipq_queue_qrtt_unmap_unsafe( unit, core, queue_quartet_ndx ); SOC_SAND_CHECK_FUNC_RESULT(res, 10, exit_semaphore); exit_semaphore: SOC_SAND_GIVE_DEVICE_SEMAPHORE; exit: SOC_SAND_EXIT_AND_SEND_ERROR( "error in arad_ipq_queue_qrtt_unmap()",queue_quartet_ndx,0); } uint32 arad_ipq_quartet_reset( SOC_SAND_IN int unit, SOC_SAND_IN int core, SOC_SAND_IN uint32 queue_quartet_ndx ) { uint32 res; SOC_SAND_INIT_ERROR_DEFINITIONS(ARAD_IPQ_QUARTET_RESET); SOC_SAND_CHECK_DRIVER_AND_DEVICE; SOC_SAND_TAKE_DEVICE_SEMAPHORE; res = arad_ipq_quartet_reset_unsafe( unit, core, queue_quartet_ndx ); SOC_SAND_CHECK_FUNC_RESULT(res, 100, exit_semaphore); exit_semaphore: SOC_SAND_GIVE_DEVICE_SEMAPHORE; exit: SOC_SAND_EXIT_AND_SEND_ERROR( "error in arad_ipq_quartet_reset()",0,0); } uint32 arad_ipq_k_quartet_reset( SOC_SAND_IN int unit, SOC_SAND_IN int core, SOC_SAND_IN uint32 queue_k_quartet_ndx, SOC_SAND_IN uint32 region_size ) { uint32 res; SOC_SAND_INIT_ERROR_DEFINITIONS(ARAD_IPQ_K_QUARTET_RESET); SOC_SAND_CHECK_DRIVER_AND_DEVICE; SOC_SAND_TAKE_DEVICE_SEMAPHORE; res = arad_ipq_k_quartet_reset_unsafe( unit, core, queue_k_quartet_ndx, region_size ); SOC_SAND_CHECK_FUNC_RESULT(res, 100, exit_semaphore); exit_semaphore: SOC_SAND_GIVE_DEVICE_SEMAPHORE; exit: SOC_SAND_EXIT_AND_SEND_ERROR( "error in arad_ipq_k_quartet_reset()",0,0); } void arad_ARAD_IPQ_EXPLICIT_MAPPING_MODE_INFO_clear( SOC_SAND_OUT ARAD_IPQ_EXPLICIT_MAPPING_MODE_INFO *info ) { SOC_SAND_INIT_ERROR_DEFINITIONS_NO_DEVID(0); SOC_SAND_CHECK_NULL_INPUT(info); SOC_TMC_IPQ_EXPLICIT_MAPPING_MODE_INFO_clear(info); exit: SOC_SAND_VOID_EXIT_AND_SEND_ERROR(0, 0, 0); } void arad_ARAD_IPQ_BASEQ_MAP_INFO_clear( SOC_SAND_OUT ARAD_IPQ_BASEQ_MAP_INFO *info ) { SOC_SAND_INIT_ERROR_DEFINITIONS_NO_DEVID(0); SOC_SAND_CHECK_NULL_INPUT(info); SOC_TMC_IPQ_BASEQ_MAP_INFO_clear(info); exit: SOC_SAND_VOID_EXIT_AND_SEND_ERROR(0, 0, 0); } void arad_ARAD_IPQ_QUARTET_MAP_INFO_clear( SOC_SAND_OUT ARAD_IPQ_QUARTET_MAP_INFO *info ) { SOC_SAND_INIT_ERROR_DEFINITIONS_NO_DEVID(0); SOC_SAND_CHECK_NULL_INPUT(info); SOC_TMC_IPQ_QUARTET_MAP_INFO_clear(info); exit: SOC_SAND_VOID_EXIT_AND_SEND_ERROR(0, 0, 0); } uint32 arad_ipq_attached_flow_port_get( SOC_SAND_IN int unit, SOC_SAND_IN int core, SOC_SAND_IN uint32 queue_ndx, SOC_SAND_OUT uint32 *flow_id, SOC_SAND_OUT uint32 *sys_port ) { uint32 res = SOC_SAND_OK; SOC_SAND_INIT_ERROR_DEFINITIONS(ARAD_IPQ_ATTACHED_FLOW_PORT_GET); SOC_SAND_CHECK_DRIVER_AND_DEVICE; SOC_SAND_CHECK_NULL_INPUT(flow_id); SOC_SAND_CHECK_NULL_INPUT(sys_port); SOC_SAND_TAKE_DEVICE_SEMAPHORE; res = arad_ipq_attached_flow_port_get_unsafe( unit, core, queue_ndx, flow_id, sys_port ); SOC_SAND_CHECK_FUNC_RESULT(res, 100, exit_semaphore); exit_semaphore: SOC_SAND_GIVE_DEVICE_SEMAPHORE; exit: SOC_SAND_EXIT_AND_SEND_ERROR( "error in arad_ipq_attached_flow_port_get()",0,0); } #if ARAD_DEBUG_IS_LVL1 uint32 arad_ips_non_empty_queues_info_get( SOC_SAND_IN int unit, SOC_SAND_IN int core, SOC_SAND_IN uint32 first_queue, SOC_SAND_IN uint32 max_array_size, SOC_SAND_OUT soc_ips_queue_info_t* queues, SOC_SAND_OUT uint32* nof_queues_filled, SOC_SAND_OUT uint32* next_queue, SOC_SAND_OUT uint32* reached_end ) { uint32 res = SOC_SAND_OK; SOC_SAND_INIT_ERROR_DEFINITIONS(0); SOC_SAND_CHECK_DRIVER_AND_DEVICE; SOC_SAND_TAKE_DEVICE_SEMAPHORE; res = arad_ips_non_empty_queues_info_get_unsafe( unit, core, first_queue, max_array_size, queues, nof_queues_filled, next_queue, reached_end ); SOC_SAND_CHECK_FUNC_RESULT(res, 10, exit_semaphore); exit_semaphore: SOC_SAND_GIVE_DEVICE_SEMAPHORE; exit: SOC_SAND_EXIT_AND_SEND_ERROR( "error in arad_ips_non_empty_queues_print()",0,0); } #endif uint32 arad_ipq_tc_profile_set( SOC_SAND_IN int unit, SOC_SAND_IN int core, SOC_SAND_IN uint8 is_flow_ndx, SOC_SAND_IN uint32 dest_ndx, SOC_SAND_IN uint32 tc_profile ) { uint32 res = SOC_SAND_OK; SOC_SAND_INIT_ERROR_DEFINITIONS(ARAD_IPQ_TC_PROFILE_SET); SOC_SAND_CHECK_DRIVER_AND_DEVICE; SOC_SAND_TAKE_DEVICE_SEMAPHORE; res = arad_ipq_tc_profile_verify( unit, is_flow_ndx, dest_ndx, tc_profile ); SOC_SAND_CHECK_FUNC_RESULT(res,10,exit_semaphore); res = arad_ipq_tc_profile_set_unsafe( unit, core, is_flow_ndx, dest_ndx, tc_profile ); SOC_SAND_CHECK_FUNC_RESULT(res,20,exit_semaphore); exit_semaphore: SOC_SAND_GIVE_DEVICE_SEMAPHORE; exit: SOC_SAND_EXIT_AND_SEND_ERROR( "error in arad_ipq_tc_profile_set()",0,0); } uint32 arad_ipq_tc_profile_get( SOC_SAND_IN int unit, SOC_SAND_IN int core, SOC_SAND_IN uint8 is_flow_ndx, SOC_SAND_IN uint32 dest_ndx, SOC_SAND_OUT uint32 *tc_profile ) { uint32 res = SOC_SAND_OK; SOC_SAND_INIT_ERROR_DEFINITIONS(ARAD_IPQ_TC_PROFILE_SET); SOC_SAND_CHECK_DRIVER_AND_DEVICE; SOC_SAND_TAKE_DEVICE_SEMAPHORE; res = arad_ipq_tc_profile_verify( unit, is_flow_ndx, dest_ndx, 0 ); SOC_SAND_CHECK_FUNC_RESULT(res,10,exit_semaphore); res = arad_ipq_tc_profile_get_unsafe( unit, core, is_flow_ndx, dest_ndx, tc_profile ); SOC_SAND_CHECK_FUNC_RESULT(res,20,exit_semaphore); exit_semaphore: SOC_SAND_GIVE_DEVICE_SEMAPHORE; exit: SOC_SAND_EXIT_AND_SEND_ERROR( "error in arad_ipq_tc_profile_get()",0,0); } uint32 arad_ipq_tc_profile_map_set( SOC_SAND_IN int unit, SOC_SAND_IN int core_id, SOC_SAND_IN ARAD_IPQ_TR_CLS_PROFILE profile_ndx, SOC_SAND_IN uint8 is_flow_profile, SOC_SAND_IN ARAD_IPQ_TR_CLS tr_cls_ndx, SOC_SAND_IN ARAD_IPQ_TR_CLS new_class ) { uint32 res = SOC_SAND_OK; SOC_SAND_INIT_ERROR_DEFINITIONS(ARAD_IPQ_TRAFFIC_CLASS_PROFILE_MAP_SET); SOC_SAND_CHECK_DRIVER_AND_DEVICE; SOC_SAND_TAKE_DEVICE_SEMAPHORE; res = arad_ipq_traffic_class_profile_map_verify( unit, core_id, profile_ndx, is_flow_profile, tr_cls_ndx, 0 ); SOC_SAND_CHECK_FUNC_RESULT(res,20,exit_semaphore); res = arad_ipq_traffic_class_profile_map_set_unsafe( unit, core_id, profile_ndx, is_flow_profile, FALSE, tr_cls_ndx, new_class ); SOC_SAND_CHECK_FUNC_RESULT(res,20,exit_semaphore); exit_semaphore: SOC_SAND_GIVE_DEVICE_SEMAPHORE; exit: SOC_SAND_EXIT_AND_SEND_ERROR( "error in arad_ipq_traffic_class_profile_map_set()",0,0); } uint32 arad_ipq_tc_profile_map_get( SOC_SAND_IN int unit, SOC_SAND_IN int core_id, SOC_SAND_IN ARAD_IPQ_TR_CLS_PROFILE profile_ndx, SOC_SAND_IN uint8 is_flow_profile, SOC_SAND_IN ARAD_IPQ_TR_CLS tr_cls_ndx, SOC_SAND_OUT ARAD_IPQ_TR_CLS *new_class ) { uint32 res = SOC_SAND_OK; SOC_SAND_INIT_ERROR_DEFINITIONS(ARAD_IPQ_TRAFFIC_CLASS_PROFILE_MAP_GET); SOC_SAND_CHECK_DRIVER_AND_DEVICE; SOC_SAND_TAKE_DEVICE_SEMAPHORE; res = arad_ipq_traffic_class_profile_map_verify( unit, core_id, profile_ndx, is_flow_profile, tr_cls_ndx, 0 ); SOC_SAND_CHECK_FUNC_RESULT(res,20,exit_semaphore); res = arad_ipq_traffic_class_profile_map_get_unsafe( unit, core_id, profile_ndx, is_flow_profile, FALSE, tr_cls_ndx, new_class ); SOC_SAND_CHECK_FUNC_RESULT(res,20,exit_semaphore); exit_semaphore: SOC_SAND_GIVE_DEVICE_SEMAPHORE; exit: SOC_SAND_EXIT_AND_SEND_ERROR( "error in arad_ipq_traffic_class_profile_map_set()",0,0); } #include <soc/dpp/SAND/Utils/sand_footer.h> #endif
23.332262
134
0.706831
a7167ee84eb35ad183a2332ac5f14360b9339436
381
h
C
src/windows/usr.include/unistd.h
philrz/zeek
22da41abf71ea64988d138fe07d092fbb4ef9be6
[ "Apache-2.0" ]
2
2020-09-14T03:12:13.000Z
2020-12-11T20:19:44.000Z
src/windows/usr.include/unistd.h
philrz/zeek
22da41abf71ea64988d138fe07d092fbb4ef9be6
[ "Apache-2.0" ]
27
2020-02-28T22:29:21.000Z
2020-12-24T18:03:24.000Z
src/windows/usr.include/unistd.h
philrz/zeek
22da41abf71ea64988d138fe07d092fbb4ef9be6
[ "Apache-2.0" ]
3
2020-05-25T20:14:38.000Z
2020-11-10T22:58:08.000Z
#pragma once #include <../include/unistd.h> #ifdef __cplusplus extern "C" { #endif unsigned alarm(unsigned seconds); int fork(); int fsync(int fildes); pid_t getppid(void); int link(const char *path1, const char * path2); int pipe(int fildes[2]); ssize_t pwrite(int fildes, const void *buf, size_t nbyte, off64_t offset); int setpgid(pid_t, pid_t); #ifdef __cplusplus } #endif
18.142857
74
0.729659
4cc8e91727dcabd04ce242f9b90598622741af18
303
c
C
src/PJ/gfx/rebclip0.c
AnimatorPro/Animator-Pro
6d0b68cd94bb5cfde2cdd05e9a7c8ee1e1cb3cbb
[ "BSD-3-Clause" ]
119
2015-01-10T15:13:50.000Z
2022-01-24T04:54:34.000Z
src/PJ/gfx/rebclip0.c
AnimatorPro/Animator-Pro
6d0b68cd94bb5cfde2cdd05e9a7c8ee1e1cb3cbb
[ "BSD-3-Clause" ]
6
2015-10-22T20:14:59.000Z
2021-07-10T03:25:21.000Z
src/PJ/gfx/rebclip0.c
AnimatorPro/Animator-Pro
6d0b68cd94bb5cfde2cdd05e9a7c8ee1e1cb3cbb
[ "BSD-3-Clause" ]
27
2015-04-24T22:55:30.000Z
2022-01-21T13:54:00.000Z
#include "rectang.h" void bclip0xy_rect(Rectangle *r, /* rectangle to clip */ Rectangle *port) /* boundary rectangle */ /* does a bclip but substitutes x and y with 0 */ { Rectangle b; b.x = b.y = 0; b.width = port->width; b.height = port->height; bclip_rect(r,&b); }
21.642857
58
0.594059
5db1c1ed5523aef9d23723f565861f9e421406da
7,598
h
C
include/tmx/MapObject.h
DevelopersGuild/C-RPG
92d33bf5ab14d8c41478d75aa7068f83890a5ea0
[ "MIT" ]
4
2018-04-15T06:01:06.000Z
2022-02-26T02:08:59.000Z
include/tmx/MapObject.h
DevelopersGuild/C-RPG
92d33bf5ab14d8c41478d75aa7068f83890a5ea0
[ "MIT" ]
6
2016-02-02T07:46:03.000Z
2016-06-10T18:41:15.000Z
include/tmx/MapObject.h
DevelopersGuild/C-RPG
92d33bf5ab14d8c41478d75aa7068f83890a5ea0
[ "MIT" ]
5
2016-03-15T01:12:26.000Z
2019-02-28T18:51:14.000Z
/********************************************************************* Matt Marchant 2013 - 2015 SFML Tiled Map Loader - https://github.com/bjorn/tiled/wiki/TMX-Map-Format http://trederia.blogspot.com/2013/05/tiled-map-loader-for-sfml.html The zlib license has been used to make this software fully compatible with SFML. See http://www.sfml-dev.org/license.php This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. *********************************************************************/ #ifndef MAP_OBJECT_H #define MAP_OBJECT_H #include <string> #include <vector> #include <map> #include <iostream> #include <memory> #include <SFML/Graphics/Color.hpp> #include <SFML/Graphics/Drawable.hpp> #include <SFML/Graphics/Font.hpp> #include <SFML/Graphics/Image.hpp> #include <SFML/Graphics/VertexArray.hpp> #include <SFML/Graphics/RectangleShape.hpp> #include <SFML/Graphics/RenderStates.hpp> #include <SFML/Graphics/RenderTarget.hpp> #include <SFML/Graphics/Sprite.hpp> #include <SFML/Graphics/Text.hpp> #include <SFML/System/NonCopyable.hpp> #include <tmx/Helpers.h> #include <tmx/DebugShape.h> namespace tmx { class TileQuad; enum MapObjectShape { Rectangle, Ellipse, Circle, Polygon, Polyline, Tile }; //map object class. class MapObject final { private: struct Segment { Segment(const sf::Vector2f& start, const sf::Vector2f& end) : Start (start) , End(end){} bool Intersects(const Segment& segment); sf::Vector2f Start; sf::Vector2f End; }; public: MapObject(); //**accessors**// //returns empty string if property not found std::string GetPropertyString(const std::string& name); //returns top left corner of bounding rectangle sf::Vector2f GetPosition() const {return m_position;} //returns precomputed centre of mass, or zero for polylines sf::Vector2f GetCentre() const {return m_centrePoint;}; //returns the type of shape of the object MapObjectShape GetShapeType() const {return m_shape;}; //returns and object's name std::string GetName() const {return m_name;}; //returns the object's type std::string GetType() const {return m_type;}; //returns the name of the object's parent layer std::string GetParent() const {return m_parent;}; //returns the objects AABB in world coordinates sf::FloatRect GetAABB() const {return m_AABB;}; //returns visibility bool Visible() const {return m_visible;} //sets a property value, or adds it if property doesn't exist void SetProperty(const std::string& name, const std::string& value); //sets the object position in world coords void SetPosition(float x, float y); void SetPosition(const sf::Vector2f& position); //moves the object by given amount void Move(float x, float y); void Move(const sf::Vector2f& distance); //sets the width and height of the object void SetSize(const sf::Vector2f& size){m_size = size;}; //sets the object's name void SetName(const std::string& name){m_name = name;} //sets the object's type void SetType(const std::string& type){m_type = type;}; //sets the name of the object's parent layer void SetParent(const std::string& parent){m_parent = parent;}; //sets the shape type void SetShapeType(MapObjectShape shape){m_shape = shape;}; //sets visibility void SetVisible(bool visible){m_visible = visible;}; //adds a point to the list of polygonal points. If calling this manually //call CreateDebugShape() afterwards to rebuild debug output void AddPoint(const sf::Vector2f& point){m_polypoints.push_back(point);}; //checks if an object contains given point in world coords. //Always returns false for polylines. bool Contains(sf::Vector2f point) const; //checks if two objects intersect, including polylines bool Intersects(const MapObject& object) const; //creates a shape used for debug drawing - points are in world space void CreateDebugShape(const sf::Color& colour); //draws debug shape to given target void DrawDebugShape(sf::RenderTarget& rt) const; //returns the first point of poly point member (if any) sf::Vector2f FirstPoint() const; //returns the last point of poly point member (if any) sf::Vector2f LastPoint() const; //returns a unit vector normal to the polyline segment if intersected //takes the start and end point of a trajectory sf::Vector2f CollisionNormal(const sf::Vector2f& start, const sf::Vector2f& end) const; //creates a vector of segments making up the poly shape void CreateSegments(); //returns if an objects poly shape is convex or not bool Convex() const; //returns a reference to the array of points making up the object const std::vector<sf::Vector2f>& PolyPoints() const; //reversing winding of object points void ReverseWinding(); //sets the quad used to draw the tile for tile objects void SetQuad(TileQuad* quad); private: //object properties, reflects those which are part of the tmx format std::string m_name, m_type, m_parent; //parent is name of layer to which object belongs //sf::FloatRect m_rect; //width / height property of object plus position in world space sf::Vector2f m_position, m_size; std::map <std::string, std::string> m_properties;//map of custom name/value properties bool m_visible; std::vector<sf::Vector2f> m_polypoints; //list of points defining any polygonal shape MapObjectShape m_shape; DebugShape m_debugShape; sf::Vector2f m_centrePoint; std::vector<Segment> m_polySegs; //segments which make up shape, if any TileQuad* m_tileQuad; float m_furthestPoint; //furthest distance from centre of object to vertex - used for intersection testing //AABB created from polygonal shapes, used for adding MapObjects to a QuadTreeNode. //Note that the position of this box many not necessarily match the MapObject's position, as polygonal //points may have negative values relative to the object's world position. sf::FloatRect m_AABB; //returns centre of poly shape if available, else centre of //bounding rectangle in world space sf::Vector2f CalcCentre() const; //precomputes centre point and furthest point to be used in intersection testing void CalcTestValues(); //creates an AABB around the object based on its polygonal points, in world space void CreateAABB(); }; typedef std::vector<MapObject> MapObjects; //represents a single tile on a layer struct MapTile final { //returns the base centre point of sprite / tile sf::Vector2f GetBase() const { return sf::Vector2f(sprite.getPosition().x + (sprite.getLocalBounds().width / 2.f), sprite.getPosition().y + sprite.getLocalBounds().height); } sf::Sprite sprite; sf::Vector2i gridCoord; sf::RenderStates renderStates; //used to perform any rendering with custom shaders or blend mode }; typedef std::vector<MapTile> MapTiles; }; #endif //MAP_OBJECT_H
37.245098
108
0.731113
56ba0310432843015469fec3ae0f112b4559b7af
324
h
C
MVVMReactiveCocoa/View/BaseClass/MRCWebViewController.h
redanula/MVVMReactiveCocoa
902508c584ec80667246ab51d6a0302686ed452a
[ "MIT" ]
5
2015-09-22T02:35:57.000Z
2020-03-26T18:49:18.000Z
MVVMReactiveCocoa/View/BaseClass/MRCWebViewController.h
mftechs/MVVMReactiveCocoa
902508c584ec80667246ab51d6a0302686ed452a
[ "MIT" ]
null
null
null
MVVMReactiveCocoa/View/BaseClass/MRCWebViewController.h
mftechs/MVVMReactiveCocoa
902508c584ec80667246ab51d6a0302686ed452a
[ "MIT" ]
null
null
null
// // MRCWebViewController.h // MVVMReactiveCocoa // // Created by leichunfeng on 15/1/24. // Copyright (c) 2015年 leichunfeng. All rights reserved. // #import "MRCViewController.h" @interface MRCWebViewController : MRCViewController <UIWebViewDelegate> @property (weak, nonatomic, readonly) UIWebView *webView; @end
20.25
71
0.75
ab091bd93dd634021bb0d0140660a751499c4dcd
631
c
C
gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/i386/pr71647.c
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
7
2020-05-02T17:34:05.000Z
2021-10-17T10:15:18.000Z
gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/i386/pr71647.c
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
null
null
null
gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/i386/pr71647.c
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
2
2020-07-27T00:22:36.000Z
2021-04-01T09:41:02.000Z
/* PR tree-optimization/71647 */ /* { dg-do compile } */ /* { dg-options "-O3 -fopenmp-simd -mavx -mno-avx512f -fdump-tree-vect-details" } */ void foo (double *a, double *b) { int i; #pragma omp simd aligned(a,b:4*sizeof(double)) for (i = 0; i < 32768; i++) a[i] += b[i]; } void bar (double *a, double *b) { int i; #pragma omp simd aligned(a,b:32) for (i = 0; i < 32768; i++) a[i] += b[i]; } void baz (double *a, double *b) { int i; #pragma omp simd aligned(a,b:32L) for (i = 0; i < 32768; i++) a[i] += b[i]; } /* { dg-final { scan-tree-dump-not "Alignment of access forced using peeling" "vect" } } */
19.121212
91
0.567353
ab43c0059e3ca2dc02dcb4942b14facad04ca938
286
h
C
Pod/Core/CNNumberParser.h
Draveness/CNNumber
10a398a6d5c32d6f23a6ccdf9522c8c96d61e641
[ "MIT" ]
5
2015-04-15T13:43:37.000Z
2017-03-22T02:15:50.000Z
Pod/Core/CNNumberParser.h
draven-archive/CNNumber
10a398a6d5c32d6f23a6ccdf9522c8c96d61e641
[ "MIT" ]
1
2016-02-25T11:13:18.000Z
2016-02-25T11:13:18.000Z
Pod/Core/CNNumberParser.h
draven-archive/CNNumber
10a398a6d5c32d6f23a6ccdf9522c8c96d61e641
[ "MIT" ]
2
2015-09-07T06:27:41.000Z
2017-02-06T06:16:05.000Z
// // CNNumber.h // CNNumber // // Created by apple on 4/17/15. // Copyright (c) 2015 DeltaX. All rights reserved. // #import <Foundation/Foundation.h> //#import "CNNumberHelper.h" @interface CNNumberParser : NSObject + (NSString *)cn_numberWithInteger:(NSInteger)integer; @end
16.823529
54
0.702797
ab4aae5ebbc85a9bdc27be2281a471ff38b60dff
10,077
c
C
test/test_list.c
pmkenned/c
e54d32b257655c51745ee926f2587890ebb6d8e5
[ "MIT" ]
null
null
null
test/test_list.c
pmkenned/c
e54d32b257655c51745ee926f2587890ebb6d8e5
[ "MIT" ]
null
null
null
test/test_list.c
pmkenned/c
e54d32b257655c51745ee926f2587890ebb6d8e5
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "../src/list.h" #include "minunit.h" #if 0 char * test_empty_list(); char * test_list_length_1(); char * test_list_length_n(); char * test_list_insert(); char * test_list_remove(); char * test_list_set(); char * test_list_dup(); char * test_list_insert_invalid(); char * test_list_remove_invalid(); char * test_list_get_set_invalid(); char * test_list_to_str(); #endif /* NOTE: could use %zu with C99 for size_t format specifier; not supported by C89 */ node_data_t dummy; char * test_empty_list() { list_t new_list = list_create(); list_t * new_list_ptr = &new_list; size_t ll = list_length(new_list_ptr); mu_assert(ll == 0, "empty list should have length of 0, not %lu", (unsigned long) ll); return 0; } char * test_list_length_1() { size_t ll; list_t new_list = list_create(); list_t * new_list_ptr = &new_list; dummy.i = 1; list_append(new_list_ptr, dummy); mu_assert(list_get(new_list_ptr, 0).i == 1, "should be %d", 1); ll = list_length(new_list_ptr); mu_assert(ll == 1, "should be 1, is %lu", (unsigned long) ll); list_destroy(new_list_ptr); ll = list_length(new_list_ptr); mu_assert(ll == 0, "should be 0, is %lu", (unsigned long) ll); return 0; } /* TODO: can this be parameterized? */ char * test_list_length_n() { int i; int n = 5; size_t ll; list_t new_list = list_create(); list_t * new_list_ptr = &new_list; for(i=0; i<n; i++) { int data; dummy.i = i; list_append(new_list_ptr, dummy); data = list_get(new_list_ptr, i).i; mu_assert(data == i, "value at %d should be %d, is %d", i, i, data); ll = list_length(new_list_ptr); mu_assert(ll == (size_t) i+1, "length should be %d, is %lu", i+1, (unsigned long) ll); } list_destroy(new_list_ptr); ll = list_length(new_list_ptr); mu_assert(ll == 0, "should be 0, is %lu", (unsigned long) ll); return 0; } char * test_list_insert() { list_t new_list = list_create(); list_t * new_list_ptr = &new_list; size_t ll; int n0, n1, n2, n3; /* [5] -> [4,5] */ dummy.i = 5; list_append(new_list_ptr, dummy); dummy.i = 4; list_insert(new_list_ptr, 0, dummy); /* confirm length == 2 */ ll = list_length(new_list_ptr); mu_assert(ll == 2, "length should be %u, is %lu", 2U, (unsigned long) ll); /* confirm list[0] == 4 */ n0 = list_get(new_list_ptr, 0).i; mu_assert(n0==4, "should be 4, not %d", n0); /* confirm list[0] == 5 */ n1 = list_get(new_list_ptr, 1).i; mu_assert(n1==5, "should be 5, not %d", n1); /* [4,5] -> [4,3,5] */ dummy.i = 3; list_insert(new_list_ptr, 1, dummy); /* confirm list[1] == 3 */ n2 = list_get(new_list_ptr, 1).i; mu_assert(n2==3, "should be 3, not %d", n2); /* [4,3,5] -> [4,3,5,6] */ dummy.i = 6; list_insert(new_list_ptr, 3, dummy); /* confirm list[3] == 6 */ n3 = list_get(new_list_ptr, 3).i; mu_assert(n3==6, "should be 3, not %d", n3); /* confirm length == 4 */ ll = list_length(new_list_ptr); mu_assert(ll == 4, "length should be %u, is %lu", 4U, (unsigned long) ll); list_destroy(new_list_ptr); ll = list_length(new_list_ptr); mu_assert(ll == 0, "length should be %u, is %lu", 0U, (unsigned long) ll); return 0; } char * test_list_remove() { list_t new_list = list_create(); list_t * new_list_ptr = &new_list; size_t ll; int data; /* list = [1,2,3,4] */ dummy.i = 1; list_append(new_list_ptr, dummy); dummy.i = 2; list_append(new_list_ptr, dummy); dummy.i = 3; list_append(new_list_ptr, dummy); dummy.i = 4; list_append(new_list_ptr, dummy); /* remove list[1] */ list_remove(new_list_ptr, 1); ll = list_length(new_list_ptr); mu_assert(ll == 3, "length should be %u, is %lu", 3U, (unsigned long) ll); /* confirm list[0] */ data = list_get(new_list_ptr, 0).i; mu_assert(data == 1, "data at %u should be %u, is %d", 0U, 1, data); /* confirm list[1] */ data = list_get(new_list_ptr, 1).i; mu_assert(data == 3, "data at %u should be %u, is %d", 1U, 3, data); /* confirm list[2] */ data = list_get(new_list_ptr, 2).i; mu_assert(data == 4, "data at %u should be %u, is %d", 2U, 4, data); /* remove list[2] */ list_remove(new_list_ptr, 2); ll = list_length(new_list_ptr); mu_assert(ll == 2, "length should be %u, is %lu", 2U, (unsigned long) ll); /* remove list[0] */ list_remove(new_list_ptr, 0); ll = list_length(new_list_ptr); mu_assert(ll == 1, "length should be %u, is %lu", 1U, (unsigned long) ll); /* remove list[0] */ list_remove(new_list_ptr, 0); ll = list_length(new_list_ptr); mu_assert(ll == 0, "length should be %u, is %lu", 0U, (unsigned long) ll); /* destroy */ list_destroy(new_list_ptr); ll = list_length(new_list_ptr); mu_assert(ll == 0, "length should be %u, is %lu", 0U, (unsigned long) ll); return 0; } char * test_list_set() { list_t new_list = list_create(); list_t * new_list_ptr = &new_list; int data; dummy.i = 1; list_append(new_list_ptr, dummy); dummy.i = 2; list_set(new_list_ptr, 0, dummy); data = list_get(new_list_ptr, 0).i; mu_assert(data == 2, "data at %u should be %u, is %d", 0U, 2, data); dummy.i = 3; list_set(new_list_ptr, 1, dummy); mu_assert(list_error == LIST_ERR_INVALID_INDEX, "list_set with index %u should be an error", 1U); list_destroy(new_list_ptr); return 0; } char * test_list_dup() { list_t new_list = list_create(); list_t * new_list_ptr = &new_list; list_t dup_list; list_t * dup_list_ptr; int data; dummy.i = 1; list_append(new_list_ptr, dummy); dummy.i = 2; list_append(new_list_ptr, dummy); dummy.i = 3; list_append(new_list_ptr, dummy); dup_list = list_dup(new_list_ptr); dup_list_ptr = &dup_list; data = list_get(dup_list_ptr, 0).i; mu_assert(data == 1, "data at %u should be %u, is %d", 0U, 1, data); data = list_get(dup_list_ptr, 1).i; mu_assert(data == 2, "data at %u should be %u, is %d", 1U, 2, data); data = list_get(dup_list_ptr, 2).i; mu_assert(data == 3, "data at %u should be %u, is %d", 2U, 3, data); list_destroy(new_list_ptr); list_destroy(dup_list_ptr); return 0; } char * test_list_insert_invalid() { list_t new_list = list_create(); list_t * new_list_ptr = &new_list; dummy.i = 1; list_insert(new_list_ptr, 1, dummy); mu_assert(list_error != 0, "list_insert with index %u should be an error", 1U); list_destroy(new_list_ptr); return 0; } char * test_list_remove_invalid() { list_t new_list = list_create(); list_t * new_list_ptr = &new_list; dummy.i = 1; list_append(new_list_ptr, dummy); list_remove(new_list_ptr, 1); mu_assert(list_error != 0, "list_remove with index %u should be an error", 1U); dummy.i = 2; list_append(new_list_ptr, dummy); list_remove(new_list_ptr, 3); mu_assert(list_error != 0, "list_remove with index %u should be an error", 2U); list_remove(new_list_ptr, 0); list_remove(new_list_ptr, 0); mu_assert(list_error == 0, "list_remove with index %u should NOT be an error", 0U); list_remove(new_list_ptr, 0); mu_assert(list_error != 0, "list_remove with index %u should be an error", 1U); list_destroy(new_list_ptr); return 0; } char * test_list_get_set_invalid() { list_t new_list = list_create(); list_t * new_list_ptr = &new_list; int n0; dummy.i = 1; list_append(new_list_ptr, dummy); dummy.i = 2; list_append(new_list_ptr, dummy); dummy.i = 3; list_append(new_list_ptr, dummy); n0 = list_get(new_list_ptr, 3).i; mu_assert(list_error != 0, "list_remove with index %u should be an error (%d)", 3U, n0); dummy.i = 0; list_set(new_list_ptr, 4, dummy); mu_assert(list_error != 0, "list_remove with index %u should be an error", 4U); list_destroy(new_list_ptr); return 0; } char * test_list_to_str() { list_t new_list = list_create(); list_t * new_list_ptr = &new_list; char * my_str = list_to_str(new_list_ptr); int result = strcmp(my_str, "[]"); mu_assert(result == 0, "string compare should be %d", 0); free(my_str); dummy.i = 1; list_append(new_list_ptr, dummy); my_str = list_to_str(new_list_ptr); result = strcmp(my_str, "[1]"); mu_assert(result == 0, "string compare should be %d", 0); free(my_str); dummy.i = 2; list_append(new_list_ptr, dummy); my_str = list_to_str(new_list_ptr); result = strcmp(my_str, "[1, 2]"); mu_assert(result == 0, "string compare should be %d", 0); free(my_str); dummy.i = 3; list_append(new_list_ptr, dummy); my_str = list_to_str(new_list_ptr); result = strcmp(my_str, "[1, 2, 3]"); mu_assert(result == 0, "string compare should be %d", 0); free(my_str); list_remove(new_list_ptr, 1); my_str = list_to_str(new_list_ptr); result = strcmp(my_str, "[1, 3]"); mu_assert(result == 0, "string compare should be %d", 0); free(my_str); list_remove(new_list_ptr, 1); my_str = list_to_str(new_list_ptr); result = strcmp(my_str, "[1]"); mu_assert(result == 0, "string compare should be %d", 0); free(my_str); list_remove(new_list_ptr, 0); my_str = list_to_str(new_list_ptr); result = strcmp(my_str, "[]"); mu_assert(result == 0, "string compare should be %d", 0); free(my_str); list_destroy(new_list_ptr); return 0; } char * list_tests() { mu_run_test(test_empty_list); mu_run_test(test_list_length_1); mu_run_test(test_list_length_n); mu_run_test(test_list_insert); mu_run_test(test_list_remove); mu_run_test(test_list_set); mu_run_test(test_list_dup); mu_run_test(test_list_insert_invalid); mu_run_test(test_list_remove_invalid); mu_run_test(test_list_get_set_invalid); mu_run_test(test_list_to_str); return 0; }
28.466102
101
0.633026
2580372de488d8ffc78ba959b2f814b9a2370bfb
141
c
C
other.7z/SFC.7z/SFC/ソースデータ/ヨッシーアイランド/ツール/ctools/mp1cnv.c
prismotizm/gigaleak
d082854866186a05fec4e2fdf1def0199e7f3098
[ "MIT" ]
null
null
null
other.7z/SFC.7z/SFC/ソースデータ/ヨッシーアイランド/ツール/ctools/mp1cnv.c
prismotizm/gigaleak
d082854866186a05fec4e2fdf1def0199e7f3098
[ "MIT" ]
null
null
null
other.7z/SFC.7z/SFC/ソースデータ/ヨッシーアイランド/ツール/ctools/mp1cnv.c
prismotizm/gigaleak
d082854866186a05fec4e2fdf1def0199e7f3098
[ "MIT" ]
null
null
null
Name: mp1cnv.c Type: file Size: 1993 Last-Modified: '2016-05-13T04:52:55Z' SHA-1: 0753FCF4E82CC129CA75A76CE77E63754A95D8A3 Description: null
20.142857
47
0.808511
e87c1a04b7b1951f4cc02d4dc894c3c59a40683f
290
h
C
NFC-Reader-Objective-C/NFC-Reader-Objective-C/SceneDelegate.h
kevinylu/Building-an-NFC-Tag-Reader-App---Objective-C
b28cda657fb76a41da4937c5ecdc20164559bc51
[ "MIT" ]
1
2021-03-27T16:56:01.000Z
2021-03-27T16:56:01.000Z
NFC-Reader-Objective-C/NFC-Reader-Objective-C/SceneDelegate.h
kevinylu/Building-an-NFC-Tag-Reader-App-Objective-C-Swift
b28cda657fb76a41da4937c5ecdc20164559bc51
[ "MIT" ]
null
null
null
NFC-Reader-Objective-C/NFC-Reader-Objective-C/SceneDelegate.h
kevinylu/Building-an-NFC-Tag-Reader-App-Objective-C-Swift
b28cda657fb76a41da4937c5ecdc20164559bc51
[ "MIT" ]
null
null
null
// // SceneDelegate.h // NFC-Reader-Objective-C // // Created by Kevin Lu on 23/09/20. // Copyright © 2020 Trackit. All rights reserved. // #import <UIKit/UIKit.h> @interface SceneDelegate : UIResponder <UIWindowSceneDelegate> @property (strong, nonatomic) UIWindow * window; @end
17.058824
62
0.706897