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
3b73eb7b309f5a4e27a9e1f98c645059deab63ce
1,654
h
C
System/Library/PrivateFrameworks/NanoPassKit.framework/NPKStandaloneFirstUnlockCoordinator.h
zhangkn/iOS14Header
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
[ "MIT" ]
1
2020-11-04T15:43:01.000Z
2020-11-04T15:43:01.000Z
System/Library/PrivateFrameworks/NanoPassKit.framework/NPKStandaloneFirstUnlockCoordinator.h
zhangkn/iOS14Header
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
[ "MIT" ]
null
null
null
System/Library/PrivateFrameworks/NanoPassKit.framework/NPKStandaloneFirstUnlockCoordinator.h
zhangkn/iOS14Header
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
[ "MIT" ]
null
null
null
/* * This header is generated by classdump-dyld 1.0 * on Sunday, September 27, 2020 at 11:54:48 AM Mountain Standard Time * Operating System: Version 14.0 (Build 18A373) * Image Source: /System/Library/PrivateFrameworks/NanoPassKit.framework/NanoPassKit * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. */ @protocol OS_dispatch_queue; @class NSObject, NSMutableArray; @interface NPKStandaloneFirstUnlockCoordinator : NSObject { int _firstDeviceUnlockRegistrationToken; NSObject*<OS_dispatch_queue> _queue; NSMutableArray* _blocksToPerformAfterFirstDeviceUnlock; } @property (nonatomic,retain) NSObject*<OS_dispatch_queue> queue; //@synthesize queue=_queue - In the implementation block @property (nonatomic,retain) NSMutableArray * blocksToPerformAfterFirstDeviceUnlock; //@synthesize blocksToPerformAfterFirstDeviceUnlock=_blocksToPerformAfterFirstDeviceUnlock - In the implementation block @property (assign,nonatomic) int firstDeviceUnlockRegistrationToken; //@synthesize firstDeviceUnlockRegistrationToken=_firstDeviceUnlockRegistrationToken - In the implementation block -(id)initWithQueue:(id)arg1 ; -(void)dealloc; -(NSObject*<OS_dispatch_queue>)queue; -(void)setQueue:(NSObject*<OS_dispatch_queue>)arg1 ; -(void)performSubjectToFirstUnlock:(/*^block*/id)arg1 ; -(void)_performFirstUnlockWork; -(int)firstDeviceUnlockRegistrationToken; -(void)setFirstDeviceUnlockRegistrationToken:(int)arg1 ; -(NSMutableArray *)blocksToPerformAfterFirstDeviceUnlock; -(void)setBlocksToPerformAfterFirstDeviceUnlock:(NSMutableArray *)arg1 ; @end
45.944444
218
0.788996
2aa219205835b295794e346729ee7a1cb344f01e
3,075
h
C
headers/headers.h
wotwot563/aad_prt_bof
9302f21d3be00b229d5049bd0ac91a66b0eb99fd
[ "MIT" ]
8
2021-06-17T09:31:53.000Z
2022-02-17T11:03:50.000Z
headers/headers.h
wotwot563/aad_prt_bof
9302f21d3be00b229d5049bd0ac91a66b0eb99fd
[ "MIT" ]
null
null
null
headers/headers.h
wotwot563/aad_prt_bof
9302f21d3be00b229d5049bd0ac91a66b0eb99fd
[ "MIT" ]
2
2021-08-13T01:34:47.000Z
2022-03-07T15:09:17.000Z
#pragma once #pragma intrinsic(memcpy,strcpy,strcmp,strlen) #include <windows.h> #include <proofofpossessioncookieinfo.h> // #include <combaseapi.h> //KERNEL32 #ifdef BOF WINBASEAPI void *__cdecl MSVCRT$calloc(size_t _NumOfElements, size_t _SizeOfElements); WINBASEAPI size_t __cdecl MSVCRT$wcslen(const wchar_t *_Str); WINBASEAPI void __cdecl MSVCRT$free(void *_Memory); WINBASEAPI int __cdecl MSVCRT$vsnprintf(char * __restrict__ d,size_t n,const char * __restrict__ format,va_list arg); WINBASEAPI errno_t __cdecl MSVCRT$mbstowcs_s(size_t *pReturnValue, wchar_t * wcstr, size_t smt,const char *mbstr, size_t count); WINBASEAPI size_t __cdecl MSVCRT$strlen(const char *_Str); WINBASEAPI int WINAPI KERNEL32$lstrlenW (LPCWSTR lpString); WINBASEAPI LPWSTR WINAPI KERNEL32$lstrcpynW (LPWSTR lpString1, LPCWSTR lpString2, int iMaxLength); WINBASEAPI LPWSTR WINAPI KERNEL32$lstrcatW (LPWSTR lpString1, LPCWSTR lpString2); WINBASEAPI int WINAPI Kernel32$WideCharToMultiByte (UINT CodePage, DWORD dwFlags, LPCWCH lpWideCharStr, int cchWideChar, LPSTR lpMultiByteStr, int cbMultiByte, LPCCH lpDefaultChar, LPBOOL lpUsedDefaultChar); #define intAlloc(size) KERNEL32$HeapAlloc(KERNEL32$GetProcessHeap(), HEAP_ZERO_MEMORY, size) #define intFree(addr) KERNEL32$HeapFree(KERNEL32$GetProcessHeap(), 0, addr) WINBASEAPI void * WINAPI KERNEL32$HeapAlloc (HANDLE hHeap, DWORD dwFlags, SIZE_T dwBytes); WINBASEAPI BOOL WINAPI KERNEL32$HeapFree (HANDLE, DWORD, PVOID); WINBASEAPI HANDLE WINAPI KERNEL32$GetProcessHeap(); DECLSPEC_IMPORT HRESULT WINAPI OLE32$CLSIDFromString (LPCOLESTR lpsz, LPCLSID pclsid); DECLSPEC_IMPORT HRESULT WINAPI OLE32$IIDFromString (LPCOLESTR lpsz, LPIID lpiid); DECLSPEC_IMPORT HRESULT WINAPI OLE32$CoInitializeEx (LPVOID pvReserved, DWORD dwCoInit); DECLSPEC_IMPORT HRESULT WINAPI OLE32$CoCreateInstance (REFCLSID rclsid, LPUNKNOWN pUnkOuter, DWORD dwClsContext, REFIID riid, LPVOID *ppv); DECLSPEC_IMPORT void WINAPI OLE32$CoTaskMemFree(LPVOID pv); DECLSPEC_IMPORT HRESULT WINAPI COOKIE$GetCookieInfoForUri(LPCWSTR uri, DWORD *cookieInfoCount, ProofOfPossessionCookieInfo **cookieInfo); #else #define MSVCRT$calloc calloc #define MSVCRT$wcslen wcslen #define MSVCRT$free free #define MSVCRT$vsnprintf vsnprintf #define MSVCRT$mbstowcs_s mbstowcs_s #define MSVCRT$strlen strlen #define Kernel32$WideCharToMultiByte WideCharToMultiByte #define intAlloc(size) KERNEL32$HeapAlloc(KERNEL32$GetProcessHeap(), HEAP_ZERO_MEMORY, size) #define intFree(addr) KERNEL32$HeapFree(KERNEL32$GetProcessHeap(), 0, addr) #define KERNEL32$HeapAlloc HeapAlloc #define KERNEL32$HeapFree HeapFree #define KERNEL32$GetProcessHeap GetProcessHeap #define KERNEL32$lstrcpynW lstrcpynW #define KERNEL32$lstrcatW lstrcatW #define KERNEL32$lstrlenW lstrlenW #define OLE32$CLSIDFromString CLSIDFromString #define OLE32$IIDFromString IIDFromString #define OLE32$CoInitializeEx CoInitializeEx #define OLE32$CoCreateInstance CoCreateInstance #define OLE32$CoTaskMemFree CoTaskMemFree #define COOKIE$GetCookieInfoForUri GetCookieInfoForUri #define internal_printf printf #endif
46.590909
207
0.833171
468cb0e0870adc030abd4ca798d08b795d220fef
541
h
C
Pods/Yunpan/Yunpan/V+VC/Album/CameraGroup/CameraGoupCtrller.h
Akateason/TestDemoLiyp
a49c624942cc14ee043f16280f8e7ee0fb03d8af
[ "MIT" ]
null
null
null
Pods/Yunpan/Yunpan/V+VC/Album/CameraGroup/CameraGoupCtrller.h
Akateason/TestDemoLiyp
a49c624942cc14ee043f16280f8e7ee0fb03d8af
[ "MIT" ]
null
null
null
Pods/Yunpan/Yunpan/V+VC/Album/CameraGroup/CameraGoupCtrller.h
Akateason/TestDemoLiyp
a49c624942cc14ee043f16280f8e7ee0fb03d8af
[ "MIT" ]
null
null
null
// // CameraGoupCtrller.h // GroupBuying // // Created by TuTu on 16/8/24. // Copyright © 2016年 teason. All rights reserved. // #import <UIKit/UIKit.h> @class PHAssetCollection ; @protocol CameraGroupCtrllerDelegate <NSObject> - (void)selectAlbumnGroup:(PHAssetCollection *)collection ; @end @interface CameraGoupCtrller : UIViewController @property (nonatomic, weak) id <CameraGroupCtrllerDelegate> delegate ; - (instancetype)initWithFrame:(CGRect)frame ; - (void)cameraGroupAnimation:(BOOL)inOrOut onView:(UIView *)view ; @end
21.64
71
0.752311
9a36fe4eacb520357285e4e3d6c427ba3d4507bd
2,313
h
C
src/test/clxx/common/exception.t.h
ptomulik/clxx
9edfb0c39e6ab2f2d86afde0ac42c5e3f21e7ac8
[ "MIT" ]
1
2015-08-12T13:11:35.000Z
2015-08-12T13:11:35.000Z
src/test/clxx/common/exception.t.h
ptomulik/clxx
9edfb0c39e6ab2f2d86afde0ac42c5e3f21e7ac8
[ "MIT" ]
67
2015-01-03T10:11:13.000Z
2015-10-21T11:03:06.000Z
src/test/clxx/common/exception.t.h
ptomulik/clxx
9edfb0c39e6ab2f2d86afde0ac42c5e3f21e7ac8
[ "MIT" ]
null
null
null
// @COPYRIGHT@ // Licensed under MIT license (LICENSE.txt) // clxx/common/exception.t.h /** // doc: clxx/common/exception.t.h {{{ * \file clxx/common/exception.t.h * \todo Write documentation */ // }}} #ifndef CLXX_EXCEPTION_T_H_INCLUDED #define CLXX_EXCEPTION_T_H_INCLUDED #include <cxxtest/TestSuite.h> #include <clxx/common/exception.hpp> #include <stdexcept> namespace clxx { class exception_test; } /** // doc: class clxx::exception_test {{{ * \todo Write documentation */ // }}} class clxx::exception_test : public CxxTest::TestSuite { public: /** // doc: test_exception1() {{{ * \brief Ensure that we can derive new exceptions from clxx::exception */ // }}} void test_exception1( ) { struct exception1 : public clxx::exception, public std::exception { exception1() : clxx::exception(), std::exception() { } exception1(exception1 const& e) : clxx::exception(e), std::exception(e) { } virtual std::exception const& clxx2std() const noexcept { return *this; } virtual const char* what() const noexcept { return "exception1"; } }; TS_ASSERT_EQUALS(exception1().what(), "exception1"); TS_ASSERT_THROWS(throw exception1(), std::exception const&); TS_ASSERT_THROWS(throw exception1(), clxx::exception const&); TS_ASSERT_THROWS(throw exception1(), exception1 const&); } /** // doc: test_exception2() {{{ * \brief Ensure that we can derive new exceptions from clxx::exception */ // }}} void test_exception2( ) { struct exception2 : public clxx::exception, public std::runtime_error { exception2() : clxx::exception(), std::runtime_error("exception2") { } exception2(exception2 const& e) : clxx::exception(e), std::runtime_error(e) { } virtual std::exception const& clxx2std() const noexcept { return *this; } }; TS_ASSERT_EQUALS(exception2().what(), "exception2"); TS_ASSERT_THROWS(throw exception2(), std::exception const&); TS_ASSERT_THROWS(throw exception2(), std::runtime_error const&); TS_ASSERT_THROWS(throw exception2(), clxx::exception const&); TS_ASSERT_THROWS(throw exception2(), exception2 const&); } }; #endif /* CLXX_EXCEPTION_T_H_INCLUDED */ // vim: set expandtab tabstop=2 shiftwidth=2: // vim: set foldmethod=marker foldcolumn=4:
34.014706
85
0.677043
a8adfced7db54428f8ba906021a48e0d5ea9f180
453
c
C
lib/debug.c
snake-scaly/cunit
af202f7d962813a44c96d6b1edb002aa34c0978a
[ "MIT" ]
null
null
null
lib/debug.c
snake-scaly/cunit
af202f7d962813a44c96d6b1edb002aa34c0978a
[ "MIT" ]
null
null
null
lib/debug.c
snake-scaly/cunit
af202f7d962813a44c96d6b1edb002aa34c0978a
[ "MIT" ]
null
null
null
/* Copyright (c) 2021 Sergey "SnakE" Gromov. Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #include "debug.h" #include "config.h" #ifdef HAVE_CRTDBG #include <crtdbg.h> #endif int check_memory_leaks() { #ifdef HAVE_CRTDBG _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); return _CrtDumpMemoryLeaks(); #else return 0; #endif }
19.695652
98
0.750552
facea417bb03abd6aba5bbede1e1b34a4a2485cc
846
h
C
src/DepotsWindow.h
Perelandra0x309/depots
af1460f861cf59cb664827c32b45774115d72ecf
[ "BSD-3-Clause" ]
null
null
null
src/DepotsWindow.h
Perelandra0x309/depots
af1460f861cf59cb664827c32b45774115d72ecf
[ "BSD-3-Clause" ]
8
2016-12-11T08:25:16.000Z
2016-12-29T22:59:41.000Z
src/DepotsWindow.h
Perelandra0x309/depots
af1460f861cf59cb664827c32b45774115d72ecf
[ "BSD-3-Clause" ]
1
2021-02-15T05:03:18.000Z
2021-02-15T05:03:18.000Z
/* DepotsWindow.h * Copyright 2016 Brian Hill * All rights reserved. Distributed under the terms of the BSD License. */ #ifndef DEPOTS_WINDOW_H #define DEPOTS_WINDOW_H #include <Node.h> #include <Window.h> #include "AddRepoWindow.h" #include "DepotsSettings.h" #include "DepotsView.h" class DepotsWindow : public BWindow { public: DepotsWindow(); ~DepotsWindow(); virtual bool QuitRequested(); virtual void MessageReceived(BMessage*); private: DepotsSettings fSettings; DepotsView *fView; AddRepoWindow *fAddWindow; node_ref fPackageNodeRef; //node_ref to watch for changes to package-repositories directory status_t fPackageNodeStatus; bool fWatchingPackageNode; //true when package-repositories directory is being watched void _StartWatching(); void _StopWatching(); }; #endif
22.263158
71
0.737589
2b477b2f3cf7fd68e9f4c387ece10b40f7dbbb84
435
h
C
U17/U17/Libs/DKProgress/WKWebView+DKProgress.h
bzydys/U17-RxSwift
14bb585fdcbe93a7268e03c2182ff8392d4a280f
[ "MIT" ]
null
null
null
U17/U17/Libs/DKProgress/WKWebView+DKProgress.h
bzydys/U17-RxSwift
14bb585fdcbe93a7268e03c2182ff8392d4a280f
[ "MIT" ]
null
null
null
U17/U17/Libs/DKProgress/WKWebView+DKProgress.h
bzydys/U17-RxSwift
14bb585fdcbe93a7268e03c2182ff8392d4a280f
[ "MIT" ]
null
null
null
// // WKWebView+DKProgress.h // Lark // // Created by ZengFanyi on 2019/4/30. // Copyright © 2019 曾凡怡. All rights reserved. // #import <WebKit/WebKit.h> #import <UIKit/UIKit.h> @class DKProgressLayer; @interface WKWebView (DKProgress) @property (nonatomic, strong) DKProgressLayer *dk_progressLayer; /** 是否显示加载进度条, 默认YES */ @property (nonatomic, assign) BOOL dk_showProgressLayer; //- (void)dk_showCustomProgressView; @end
17.4
64
0.724138
1a06ac9fbf86c158deadd958cfabb4710350a2b2
8,623
c
C
Features/Ext4Pkg/Ext4Dxe/BlockMap.c
rohit-arm/edk2-platforms
14c218dd05ef4175fec908b6d7c8dc0b7315d5f6
[ "Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "BSD-2-Clause-Patent", "BSD-3-Clause" ]
null
null
null
Features/Ext4Pkg/Ext4Dxe/BlockMap.c
rohit-arm/edk2-platforms
14c218dd05ef4175fec908b6d7c8dc0b7315d5f6
[ "Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "BSD-2-Clause-Patent", "BSD-3-Clause" ]
null
null
null
Features/Ext4Pkg/Ext4Dxe/BlockMap.c
rohit-arm/edk2-platforms
14c218dd05ef4175fec908b6d7c8dc0b7315d5f6
[ "Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "BSD-2-Clause-Patent", "BSD-3-Clause" ]
null
null
null
/** @file Implementation of routines that deal with ext2/3 block maps. Copyright (c) 2022 Pedro Falcato All rights reserved. SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include <Ext4Dxe.h> // Note: The largest path we can take uses up 4 indices #define EXT4_MAX_BLOCK_PATH 4 typedef enum ext4_logical_block_type { EXT4_TYPE_DIRECT_BLOCK = 0, EXT4_TYPE_SINGLY_BLOCK, EXT4_TYPE_DOUBLY_BLOCK, EXT4_TYPE_TREBLY_BLOCK, EXT4_TYPE_BAD_BLOCK } EXT4_LOGICAL_BLOCK_TYPE; /** @brief Detect the type of path the logical block will follow @param[in] LogicalBlock The logical block @param[in] Partition Pointer to an EXT4_PARTITION @return The type of path the logical block will need to follow */ STATIC EXT4_LOGICAL_BLOCK_TYPE Ext4DetectBlockType ( IN UINT32 LogicalBlock, IN CONST EXT4_PARTITION *Partition ) { UINT32 Entries; UINT32 MinSinglyBlock; UINT32 MinDoublyBlock; UINT32 MinTreblyBlock; UINT32 MinQuadBlock; Entries = (Partition->BlockSize / sizeof (UINT32)); MinSinglyBlock = EXT4_DBLOCKS; MinDoublyBlock = Entries + MinSinglyBlock; MinTreblyBlock = Entries * Entries + MinDoublyBlock; MinQuadBlock = Entries * Entries * Entries + MinTreblyBlock; // Doesn't actually exist if (LogicalBlock < MinSinglyBlock) { return EXT4_TYPE_DIRECT_BLOCK; } else if ((LogicalBlock >= MinSinglyBlock) && (LogicalBlock < MinDoublyBlock)) { return EXT4_TYPE_SINGLY_BLOCK; } else if ((LogicalBlock >= MinDoublyBlock) && (LogicalBlock < MinTreblyBlock)) { return EXT4_TYPE_DOUBLY_BLOCK; } else if (((LogicalBlock >= MinTreblyBlock) && (LogicalBlock < MinQuadBlock))) { return EXT4_TYPE_TREBLY_BLOCK; } else { return EXT4_TYPE_BAD_BLOCK; } } /** @brief Get a block's path in indices @param[in] Partition Pointer to an EXT4_PARTITION @param[in] LogicalBlock Logical block @param[out] BlockPath Pointer to an array of EXT4_MAX_BLOCK_PATH elements, where the indices we'll need to read are inserted. @return The number of path elements that are required (and were inserted in BlockPath) */ UINTN Ext4GetBlockPath ( IN CONST EXT4_PARTITION *Partition, IN UINT32 LogicalBlock, OUT EXT4_BLOCK_NR BlockPath[EXT4_MAX_BLOCK_PATH] ) { // The logic behind the block map is very much like a page table // Let's think of blocks with 512 entries (exactly like a page table on x64). // On doubly indirect block paths, we subtract the min doubly blocks from the logical block. // The top 9 bits of the result are the index inside the dind block, the bottom 9 bits are the // index inside the ind block. Since Entries is always a power of 2, entries - 1 will give us // a mask of the BlockMapBits. // Note that all this math could be done with ands and shifts (similar implementations exist // in a bunch of other places), but I'm doing it a simplified way with divs and modulus, // since it's not going to be a bottleneck anyway. UINT32 Entries; UINT32 EntriesEntries; UINT32 MinSinglyBlock; UINT32 MinDoublyBlock; UINT32 MinTreblyBlock; EXT4_LOGICAL_BLOCK_TYPE Type; Entries = (Partition->BlockSize / sizeof (UINT32)); EntriesEntries = Entries * Entries; MinSinglyBlock = EXT4_DBLOCKS; MinDoublyBlock = Entries + MinSinglyBlock; MinTreblyBlock = EntriesEntries + MinDoublyBlock; Type = Ext4DetectBlockType (LogicalBlock, Partition); switch (Type) { case EXT4_TYPE_DIRECT_BLOCK: BlockPath[0] = LogicalBlock; break; case EXT4_TYPE_SINGLY_BLOCK: BlockPath[0] = EXT4_IND_BLOCK; BlockPath[1] = LogicalBlock - EXT4_DBLOCKS; break; case EXT4_TYPE_DOUBLY_BLOCK: BlockPath[0] = EXT4_DIND_BLOCK; LogicalBlock -= MinDoublyBlock; BlockPath[1] = LogicalBlock / Entries; BlockPath[2] = LogicalBlock % Entries; break; case EXT4_TYPE_TREBLY_BLOCK: BlockPath[0] = EXT4_DIND_BLOCK; LogicalBlock -= MinTreblyBlock; BlockPath[1] = LogicalBlock / EntriesEntries; BlockPath[2] = (LogicalBlock % EntriesEntries) / Entries; BlockPath[3] = (LogicalBlock % EntriesEntries) % Entries; break; default: // EXT4_TYPE_BAD_BLOCK return -1; } return Type + 1; } /** @brief Get an extent from a block map Note: Also parses file holes and creates uninitialised extents from them. @param[in] Buffer Buffer of block pointers @param[in] IndEntries Number of entries in this block pointer table @param[in] StartIndex The start index from which we want to find a contiguous extent @param[out] Extent Pointer to the resulting EXT4_EXTENT */ VOID Ext4GetExtentInBlockMap ( IN CONST UINT32 *Buffer, IN CONST UINT32 IndEntries, IN UINT32 StartIndex, OUT EXT4_EXTENT *Extent ) { UINT32 Index; UINT32 FirstBlock; UINT32 LastBlock; UINT16 Count; Count = 1; LastBlock = Buffer[StartIndex]; FirstBlock = LastBlock; if (FirstBlock == EXT4_BLOCK_FILE_HOLE) { // File hole, let's see how many blocks this hole spans Extent->ee_start_hi = 0; Extent->ee_start_lo = 0; for (Index = StartIndex + 1; Index < IndEntries; Index++) { if (Count == EXT4_EXTENT_MAX_INITIALIZED - 1) { // We've reached the max size of an uninit extent, break break; } if (Buffer[Index] == EXT4_BLOCK_FILE_HOLE) { Count++; } else { break; } } // We mark the extent as uninitialised, although there's a difference between uninit // extents and file holes. Extent->ee_len = EXT4_EXTENT_MAX_INITIALIZED + Count; return; } for (Index = StartIndex + 1; Index < IndEntries; Index++) { if (Count == EXT4_EXTENT_MAX_INITIALIZED) { // We've reached the max size of an extent, break break; } if ((Buffer[Index] == LastBlock + 1) && (Buffer[Index] != EXT4_BLOCK_FILE_HOLE)) { Count++; } else { break; } LastBlock = Buffer[Index]; } Extent->ee_start_lo = FirstBlock; Extent->ee_start_hi = 0; Extent->ee_len = Count; } /** Retrieves an extent from an EXT2/3 inode (with a blockmap). @param[in] Partition Pointer to the opened EXT4 partition. @param[in] File Pointer to the opened file. @param[in] LogicalBlock Block number which the returned extent must cover. @param[out] Extent Pointer to the output buffer, where the extent will be copied to. @retval EFI_SUCCESS Retrieval was succesful. @retval EFI_NO_MAPPING Block has no mapping. **/ EFI_STATUS Ext4GetBlocks ( IN EXT4_PARTITION *Partition, IN EXT4_FILE *File, IN EXT4_BLOCK_NR LogicalBlock, OUT EXT4_EXTENT *Extent ) { EXT4_INODE *Inode; EXT4_BLOCK_NR BlockPath[EXT4_MAX_BLOCK_PATH]; UINTN BlockPathLength; UINTN Index; UINT32 *Buffer; EFI_STATUS Status; UINT32 Block; UINT32 BlockIndex; Inode = File->Inode; BlockPathLength = Ext4GetBlockPath (Partition, LogicalBlock, BlockPath); if (BlockPathLength == (UINTN)-1) { // Bad logical block (out of range) return EFI_NO_MAPPING; } Extent->ee_block = LogicalBlock; if (BlockPathLength == 1) { // Fast path for blocks 0 - 12 that skips allocations Ext4GetExtentInBlockMap (Inode->i_data, EXT4_DBLOCKS, BlockPath[0], Extent); return EFI_SUCCESS; } Buffer = AllocatePool (Partition->BlockSize); if (Buffer == NULL) { return EFI_OUT_OF_RESOURCES; } // Note the BlockPathLength - 1 so we don't end up reading the final block for (Index = 0; Index < BlockPathLength - 1; Index++) { BlockIndex = BlockPath[Index]; if (Index == 0) { Block = Inode->i_data[BlockIndex]; } else { Block = Buffer[BlockIndex]; } if (Block == EXT4_BLOCK_FILE_HOLE) { FreePool (Buffer); return EFI_NO_MAPPING; } Status = Ext4ReadBlocks (Partition, Buffer, 1, Block); if (EFI_ERROR (Status)) { FreePool (Buffer); return Status; } } Ext4GetExtentInBlockMap (Buffer, Partition->BlockSize / sizeof (UINT32), BlockPath[BlockPathLength - 1], Extent); FreePool (Buffer); return EFI_SUCCESS; }
30.796429
116
0.654876
1515228eaf075f2bb7b256ef0d8210f31004b0a4
1,207
h
C
embedding/utilities/include/embedding.h
TheoryInPractice/aqc-virtual-embedding
3e69881c5db992f92b75f38dd42b8f8672cda898
[ "BSD-3-Clause" ]
9
2017-11-21T23:23:31.000Z
2021-09-14T08:37:49.000Z
embedding/utilities/include/embedding.h
TheoryInPractice/aqc-virtual-embedding
3e69881c5db992f92b75f38dd42b8f8672cda898
[ "BSD-3-Clause" ]
null
null
null
embedding/utilities/include/embedding.h
TheoryInPractice/aqc-virtual-embedding
3e69881c5db992f92b75f38dd42b8f8672cda898
[ "BSD-3-Clause" ]
4
2017-05-30T17:16:06.000Z
2021-09-14T08:37:50.000Z
#ifndef UTILITIES_EMBEDDING_H_ #define UTILITIES_EMBEDDING_H_ #include <fstream> #include "graph.h" class Embedding { public: Embedding(int input_g_n, int input_h_n); ~Embedding(); void add_vertex(int bag, int vertex); void remove_vertex(int bag, int vertex); bool contains(int bag, int vertex); bool is_bag_empty(int bag); bool is_empty(); void clear_bag(int bag); void clear(); int compute_qubits_used(); void print(); void write_to_file(std::string &filename); void write_to_latex(int n, Chimera &hardware, std::string &filename); protected: bool *phi; int g_n; int h_n; }; class CMR_Embedding : public Embedding { public: CMR_Embedding(int input_g_n, int input_h_n); ~CMR_Embedding(); void add_vertex(int bag, int vertex); void remove_vertex(int bag, int vertex); bool contains(int bag, int vertex); void clear_bag(int bag); void clear(); bool is_valid(); int get_qubits_used(); int get_number_of_bags(int vertex); int get_max_number_of_bags(); protected: /* counts the sum of bag sizes */ int qubits_used; /* counts how many bags v is in */ int *number_of_bags; }; #endif
22.773585
73
0.680199
36b918dd44940f6c508598017d984c9ab5978714
17,749
c
C
lib/abc/src/misc/espresso/set.c
Ace-Ma/LSOracle
6e940906303ef6c2c6b96352f44206567fdd50d3
[ "MIT" ]
9
2017-06-12T17:58:42.000Z
2021-02-04T00:02:29.000Z
reproduction-artifact/ssatABC/src/misc/espresso/set.c
nianzelee/PhD-Dissertation
061e22dd55b4e58b3de3b0e58bb1cbe11435decd
[ "Apache-2.0" ]
1
2020-12-15T05:59:37.000Z
2020-12-15T05:59:37.000Z
reproduction-artifact/ssatABC/src/misc/espresso/set.c
nianzelee/PhD-Dissertation
061e22dd55b4e58b3de3b0e58bb1cbe11435decd
[ "Apache-2.0" ]
3
2018-04-23T22:52:53.000Z
2020-12-15T16:36:19.000Z
/* * Revision Control Information * * $Source$ * $Author$ * $Revision$ * $Date$ * */ /* * set.c -- routines for maniuplating sets and set families */ /* LINTLIBRARY */ #include "espresso.h" ABC_NAMESPACE_IMPL_START static pset_family set_family_garbage = NULL; static void intcpy(d, s, n) register unsigned int *d, *s; register long n; { register int i; for(i = 0; i < n; i++) { *d++ = *s++; } } /* bit_index -- find first bit (from LSB) in a word (MSB=bit n, LSB=bit 0) */ int bit_index(a) register unsigned int a; { register int i; if (a == 0) return -1; for(i = 0; (a & 1) == 0; a >>= 1, i++) ; return i; } /* set_ord -- count number of elements in a set */ int set_ord(a) register pset a; { register int i, sum = 0; register unsigned int val; for(i = LOOP(a); i > 0; i--) if ((val = a[i]) != 0) sum += count_ones(val); return sum; } /* set_dist -- distance between two sets (# elements in common) */ int set_dist(a, b) register pset a, b; { register int i, sum = 0; register unsigned int val; for(i = LOOP(a); i > 0; i--) if ((val = a[i] & b[i]) != 0) sum += count_ones(val); return sum; } /* set_clear -- make "r" the empty set of "size" elements */ pset set_clear(r, size) register pset r; int size; { register int i = LOOPINIT(size); *r = i; do r[i] = 0; while (--i > 0); return r; } /* set_fill -- make "r" the universal set of "size" elements */ pset set_fill(r, size) register pset r; register int size; { register int i = LOOPINIT(size); *r = i; r[i] = ~ (unsigned) 0; r[i] >>= i * BPI - size; while (--i > 0) r[i] = ~ (unsigned) 0; return r; } /* set_copy -- copy set a into set r */ pset set_copy(r, a) register pset r, a; { register int i = LOOPCOPY(a); do r[i] = a[i]; while (--i >= 0); return r; } /* set_and -- compute intersection of sets "a" and "b" */ pset set_and(r, a, b) register pset r, a, b; { register int i = LOOP(a); PUTLOOP(r,i); do r[i] = a[i] & b[i]; while (--i > 0); return r; } /* set_or -- compute union of sets "a" and "b" */ pset set_or(r, a, b) register pset r, a, b; { register int i = LOOP(a); PUTLOOP(r,i); do r[i] = a[i] | b[i]; while (--i > 0); return r; } /* set_diff -- compute difference of sets "a" and "b" */ pset set_diff(r, a, b) register pset r, a, b; { register int i = LOOP(a); PUTLOOP(r,i); do r[i] = a[i] & ~b[i]; while (--i > 0); return r; } /* set_xor -- compute exclusive-or of sets "a" and "b" */ pset set_xor(r, a, b) register pset r, a, b; { register int i = LOOP(a); #ifdef IBM_WATC PUTLOOP(r,i); do r[i] = (a[i]&~b[i]) | (~a[i]&b[i]); while (--i > 0); #else PUTLOOP(r,i); do r[i] = a[i] ^ b[i]; while (--i > 0); #endif return r; } /* set_merge -- compute "a" & "mask" | "b" & ~ "mask" */ pset set_merge(r, a, b, mask) register pset r, a, b, mask; { register int i = LOOP(a); PUTLOOP(r,i); do r[i] = (a[i]&mask[i]) | (b[i]&~mask[i]); while (--i > 0); return r; } /* set_andp -- compute intersection of sets "a" and "b" , TRUE if nonempty */ bool set_andp(r, a, b) register pset r, a, b; { register int i = LOOP(a); register unsigned int x = 0; PUTLOOP(r,i); do {r[i] = a[i] & b[i]; x |= r[i];} while (--i > 0); return x != 0; } /* set_orp -- compute union of sets "a" and "b" , TRUE if nonempty */ bool set_orp(r, a, b) register pset r, a, b; { register int i = LOOP(a); register unsigned int x = 0; PUTLOOP(r,i); do {r[i] = a[i] | b[i]; x |= r[i];} while (--i > 0); return x != 0; } /* setp_empty -- check if the set "a" is empty */ bool setp_empty(a) register pset a; { register int i = LOOP(a); do if (a[i]) return FALSE; while (--i > 0); return TRUE; } /* setp_full -- check if the set "a" is the full set of "size" elements */ bool setp_full(a, size) register pset a; register int size; { register int i = LOOP(a); register unsigned int test; test = ~ (unsigned) 0; test >>= i * BPI - size; if (a[i] != test) return FALSE; while (--i > 0) if (a[i] != (~(unsigned) 0)) return FALSE; return TRUE; } /* setp_equal -- check if the set "a" equals set "b" */ bool setp_equal(a, b) register pset a, b; { register int i = LOOP(a); do if (a[i] != b[i]) return FALSE; while (--i > 0); return TRUE; } /* setp_disjoint -- check if intersection of "a" and "b" is empty */ bool setp_disjoint(a, b) register pset a, b; { register int i = LOOP(a); do if (a[i] & b[i]) return FALSE; while (--i > 0); return TRUE; } /* setp_implies -- check if "a" implies "b" ("b" contains "a") */ bool setp_implies(a, b) register pset a, b; { register int i = LOOP(a); do if (a[i] & ~b[i]) return FALSE; while (--i > 0); return TRUE; } /* sf_or -- form the "or" of all sets in a set family */ pset sf_or(A) pset_family A; { register pset or, last, p; or = set_new(A->sf_size); foreach_set(A, last, p) INLINEset_or(or, or, p); return or; } /* sf_and -- form the "and" of all sets in a set family */ pset sf_and(A) pset_family A; { register pset and, last, p; and = set_fill(set_new(A->sf_size), A->sf_size); foreach_set(A, last, p) INLINEset_and(and, and, p); return and; } /* sf_active -- make all members of the set family active */ pset_family sf_active(A) pset_family A; { register pset p, last; foreach_set(A, last, p) { SET(p, ACTIVE); } A->active_count = A->count; return A; } /* sf_inactive -- remove all inactive cubes in a set family */ pset_family sf_inactive(A) pset_family A; { register pset p, last, pdest; pdest = A->data; foreach_set(A, last, p) { if (TESTP(p, ACTIVE)) { if (pdest != p) { INLINEset_copy(pdest, p); } pdest += A->wsize; } else { A->count--; } } return A; } /* sf_copy -- copy a set family */ pset_family sf_copy(R, A) pset_family R, A; { R->sf_size = A->sf_size; R->wsize = A->wsize; /*R->capacity = A->count;*/ /*R->data = REALLOC(unsigned int, R->data, (long) R->capacity * R->wsize);*/ R->count = A->count; R->active_count = A->active_count; intcpy(R->data, A->data, (long) A->wsize * A->count); return R; } /* sf_join -- join A and B into a single set_family */ pset_family sf_join(A, B) pset_family A, B; { pset_family R; long asize = A->count * A->wsize; long bsize = B->count * B->wsize; if (A->sf_size != B->sf_size) fatal("sf_join: sf_size mismatch"); R = sf_new(A->count + B->count, A->sf_size); R->count = A->count + B->count; R->active_count = A->active_count + B->active_count; intcpy(R->data, A->data, asize); intcpy(R->data + asize, B->data, bsize); return R; } /* sf_append -- append the sets of B to the end of A, and dispose of B */ pset_family sf_append(A, B) pset_family A, B; { long asize = A->count * A->wsize; long bsize = B->count * B->wsize; if (A->sf_size != B->sf_size) fatal("sf_append: sf_size mismatch"); A->capacity = A->count + B->count; A->data = REALLOC(unsigned int, A->data, (long) A->capacity * A->wsize); intcpy(A->data + asize, B->data, bsize); A->count += B->count; A->active_count += B->active_count; sf_free(B); return A; } /* sf_new -- allocate "num" sets of "size" elements each */ pset_family sf_new(num, size) int num, size; { pset_family A; if (set_family_garbage == NULL) { A = ALLOC(set_family_t, 1); } else { A = set_family_garbage; set_family_garbage = A->next; } A->sf_size = size; A->wsize = SET_SIZE(size); A->capacity = num; A->data = ALLOC(unsigned int, (long) A->capacity * A->wsize); A->count = 0; A->active_count = 0; return A; } /* sf_save -- create a duplicate copy of a set family */ pset_family sf_save(A) register pset_family A; { return sf_copy(sf_new(A->count, A->sf_size), A); } /* sf_free -- free the storage allocated for a set family */ void sf_free(A) pset_family A; { FREE(A->data); A->next = set_family_garbage; set_family_garbage = A; } /* sf_cleanup -- free all of the set families from the garbage list */ void sf_cleanup() { register pset_family p, pnext; for(p = set_family_garbage; p != (pset_family) NULL; p = pnext) { pnext = p->next; FREE(p); } set_family_garbage = (pset_family) NULL; } /* sf_addset -- add a set to the end of a set family */ pset_family sf_addset(A, s) pset_family A; pset s; { register pset p; if (A->count >= A->capacity) { A->capacity = A->capacity + A->capacity/2 + 1; A->data = REALLOC(unsigned int, A->data, (long) A->capacity * A->wsize); } p = GETSET(A, A->count++); INLINEset_copy(p, s); return A; } /* sf_delset -- delete a set from a set family */ void sf_delset(A, i) pset_family A; int i; { (void) set_copy(GETSET(A,i), GETSET(A, --A->count));} /* sf_print -- print a set_family as a set (list the element numbers) */ void sf_print(A) pset_family A; { char *ps1(); register pset p; register int i; foreachi_set(A, i, p) printf("A[%d] = %s\n", i, ps1(p)); } /* sf_bm_print -- print a set_family as a bit-matrix */ void sf_bm_print(A) pset_family A; { char *pbv1(); register pset p; register int i; foreachi_set(A, i, p) printf("[%4d] %s\n", i, pbv1(p, A->sf_size)); } /* sf_write -- output a set family in an unintelligable manner */ void sf_write(fp, A) FILE *fp; pset_family A; { register pset p, last; (void) fprintf(fp, "%d %d\n", A->count, A->sf_size); foreach_set(A, last, p) set_write(fp, p); (void) fflush(fp); } /* sf_read -- read a set family written by sf_write */ pset_family sf_read(fp) FILE *fp; { int i, j; register pset p, last; pset_family A; (void) fscanf(fp, "%d %d\n", &i, &j); A = sf_new(i, j); A->count = i; foreach_set(A, last, p) { (void) fscanf(fp, "%x", p); for(j = 1; j <= LOOP(p); j++) (void) fscanf(fp, "%x", p+j); } return A; } /* set_write -- output a set in an unintelligable manner */ void set_write(fp, a) register FILE *fp; register pset a; { register int n = LOOP(a), j; for(j = 0; j <= n; j++) { (void) fprintf(fp, "%x ", a[j]); if ((j+1) % 8 == 0 && j != n) (void) fprintf(fp, "\n\t"); } (void) fprintf(fp, "\n"); } /* sf_bm_read -- read a set family written by sf_bm_print (almost) */ pset_family sf_bm_read(fp) FILE *fp; { int i, j, rows, cols; register pset pdest; pset_family A; (void) fscanf(fp, "%d %d\n", &rows, &cols); A = sf_new(rows, cols); for(i = 0; i < rows; i++) { pdest = GETSET(A, A->count++); (void) set_clear(pdest, A->sf_size); for(j = 0; j < cols; j++) { switch(getc(fp)) { case '0': break; case '1': set_insert(pdest, j); break; default: fatal("Error reading set family"); } } if (getc(fp) != '\n') { fatal("Error reading set family (at end of line)"); } } return A; } /* ps1 -- convert a set into a printable string */ #define largest_string 120 static char s1[largest_string]; char *ps1(a) register pset a; { register int i, num, l, len = 0, n = NELEM(a); char temp[20]; bool first = TRUE; s1[len++] = '['; for(i = 0; i < n; i++) if (is_in_set(a,i)) { if (! first) s1[len++] = ','; first = FALSE; num = i; /* Generate digits (reverse order) */ l = 0; do temp[l++] = num % 10 + '0'; while ((num /= 10) > 0); /* Copy them back in correct order */ do s1[len++] = temp[--l]; while (l > 0); if (len > largest_string-15) { s1[len++] = '.'; s1[len++] = '.'; s1[len++] = '.'; break; } } s1[len++] = ']'; s1[len++] = '\0'; return s1; } /* pbv1 -- print bit-vector */ char *pbv1(s, n) pset s; int n; { register int i; for(i = 0; i < n; i++) s1[i] = is_in_set(s,i) ? '1' : '0'; s1[n] = '\0'; return s1; } /* set_adjcnt -- adjust the counts for a set by "weight" */ void set_adjcnt(a, count, weight) register pset a; register int *count, weight; { register int i, base; register unsigned int val; for(i = LOOP(a); i > 0; ) { for(val = a[i], base = --i << LOGBPI; val != 0; base++, val >>= 1) { if (val & 1) { count[base] += weight; } } } } /* sf_count -- perform a column sum over a set family */ int *sf_count(A) pset_family A; { register pset p, last; register int i, base, *count; register unsigned int val; count = ALLOC(int, A->sf_size); for(i = A->sf_size - 1; i >= 0; i--) { count[i] = 0; } foreach_set(A, last, p) { for(i = LOOP(p); i > 0; ) { for(val = p[i], base = --i << LOGBPI; val != 0; base++, val >>= 1) { if (val & 1) { count[base]++; } } } } return count; } /* sf_count_restricted -- perform a column sum over a set family, restricting * to only the columns which are in r; also, the columns are weighted by the * number of elements which are in each row */ int *sf_count_restricted(A, r) pset_family A; register pset r; { register pset p; register int i, base, *count; register unsigned int val; int weight; pset last; count = ALLOC(int, A->sf_size); for(i = A->sf_size - 1; i >= 0; i--) { count[i] = 0; } /* Loop for each set */ foreach_set(A, last, p) { weight = 1024 / (set_ord(p) - 1); for(i = LOOP(p); i > 0; ) { for(val=p[i]&r[i], base= --i<<LOGBPI; val!=0; base++, val >>= 1) { if (val & 1) { count[base] += weight; } } } } return count; } /* * sf_delc -- delete columns first ... last of A */ pset_family sf_delc(A, first, last) pset_family A; int first, last; { return sf_delcol(A, first, last-first + 1); } /* * sf_addcol -- add columns to a set family; includes a quick check to see * if there is already enough room (and hence, can avoid copying) */ pset_family sf_addcol(A, firstcol, n) pset_family A; int firstcol, n; { int maxsize; /* Check if adding columns at the end ... */ if (firstcol == A->sf_size) { /* If so, check if there is already enough room */ maxsize = BPI * LOOPINIT(A->sf_size); if ((A->sf_size + n) <= maxsize) { A->sf_size += n; return A; } } return sf_delcol(A, firstcol, -n); } /* * sf_delcol -- add/delete columns to/from a set family * * if n > 0 then n columns starting from firstcol are deleted if n < 0 * then n blank columns are inserted starting at firstcol * (i.e., the first new column number is firstcol) * * This is done by copying columns in the array which is a relatively * slow operation. */ pset_family sf_delcol(A, firstcol, n) pset_family A; register int firstcol, n; { register pset p, last, pdest; register int i; pset_family B; B = sf_new(A->count, A->sf_size - n); foreach_set(A, last, p) { pdest = GETSET(B, B->count++); INLINEset_clear(pdest, B->sf_size); for(i = 0; i < firstcol; i++) if (is_in_set(p, i)) set_insert(pdest, i); for(i = n > 0 ? firstcol + n : firstcol; i < A->sf_size; i++) if (is_in_set(p, i)) set_insert(pdest, i - n); } sf_free(A); return B; } /* * sf_copy_col -- copy column "srccol" from "src" to column "dstcol" of "dst" */ pset_family sf_copy_col(dst, dstcol, src, srccol) pset_family dst, src; int dstcol, srccol; { register pset last, p, pdest; register int word_test, word_set; unsigned int bit_set, bit_test; /* CHEAT! form these constants outside the loop */ word_test = WHICH_WORD(srccol); bit_test = 1 << WHICH_BIT(srccol); word_set = WHICH_WORD(dstcol); bit_set = 1 << WHICH_BIT(dstcol); pdest = dst->data; foreach_set(src, last, p) { if ((p[word_test] & bit_test) != 0) pdest[word_set] |= bit_set; /* * equivalent code for this is ... * if (is_in_set(p, srccol)) set_insert(pdest, destcol); */ pdest += dst->wsize; } return dst; } /* * sf_compress -- delete columns from a matrix */ pset_family sf_compress(A, c) pset_family A; /* will be freed */ register pset c; { register pset p; register int i, bcol; pset_family B; /* create a clean set family for the result */ B = sf_new(A->count, set_ord(c)); for(i = 0; i < A->count; i++) { p = GETSET(B, B->count++); INLINEset_clear(p, B->sf_size); } /* copy each column of A which has a 1 in c */ bcol = 0; for(i = 0; i < A->sf_size; i++) { if (is_in_set(c, i)) { (void) sf_copy_col(B, bcol++, A, i); } } sf_free(A); return B; } /* * sf_transpose -- transpose a bit matrix * * There are trickier ways of doing this, but this works. */ pset_family sf_transpose(A) pset_family A; { pset_family B; register pset p; register int i, j; B = sf_new(A->sf_size, A->count); B->count = A->sf_size; foreachi_set(B, i, p) { INLINEset_clear(p, B->sf_size); } foreachi_set(A, i, p) { for(j = 0; j < A->sf_size; j++) { if (is_in_set(p, j)) { set_insert(GETSET(B, j), i); } } } sf_free(A); return B; } /* * sf_permute -- permute the columns of a set_family * * permute is an array of integers containing column numbers of A which * are to be retained. */ pset_family sf_permute(A, permute, npermute) pset_family A; register int *permute, npermute; { pset_family B; register pset p, last, pdest; register int j; B = sf_new(A->count, npermute); B->count = A->count; foreach_set(B, last, p) INLINEset_clear(p, npermute); pdest = B->data; foreach_set(A, last, p) { for(j = 0; j < npermute; j++) if (is_in_set(p, permute[j])) set_insert(pdest, j); pdest += B->wsize; } sf_free(A); return B; } ABC_NAMESPACE_IMPL_END
21.487893
78
0.577779
cf9c0525c8224af4b33757e9ce9cf49f6a85e35f
1,837
h
C
domain-server/src/DomainServerSettingsManager.h
polac/hifi
f18807862302a08577da72d38d341ec306ddfefb
[ "Apache-2.0" ]
null
null
null
domain-server/src/DomainServerSettingsManager.h
polac/hifi
f18807862302a08577da72d38d341ec306ddfefb
[ "Apache-2.0" ]
null
null
null
domain-server/src/DomainServerSettingsManager.h
polac/hifi
f18807862302a08577da72d38d341ec306ddfefb
[ "Apache-2.0" ]
null
null
null
// // DomainServerSettingsManager.h // domain-server/src // // Created by Stephen Birarda on 2014-06-24. // Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #ifndef hifi_DomainServerSettingsManager_h #define hifi_DomainServerSettingsManager_h #include <QtCore/QJsonArray> #include <QtCore/QJsonDocument> #include <HifiConfigVariantMap.h> #include <HTTPManager.h> const QString SETTINGS_PATHS_KEY = "paths"; const QString SETTINGS_PATH = "/settings"; const QString SETTINGS_PATH_JSON = SETTINGS_PATH + ".json"; class DomainServerSettingsManager : public QObject { Q_OBJECT public: DomainServerSettingsManager(); bool handlePublicHTTPRequest(HTTPConnection* connection, const QUrl& url); bool handleAuthenticatedHTTPRequest(HTTPConnection* connection, const QUrl& url); void setupConfigMap(const QStringList& argumentList); QVariant valueOrDefaultValueForKeyPath(const QString& keyPath); QVariantMap& getUserSettingsMap() { return _configMap.getUserConfig(); } QVariantMap& getSettingsMap() { return _configMap.getMergedConfig(); } private: QJsonObject responseObjectForType(const QString& typeValue, bool isAuthenticated = false); void recurseJSONObjectAndOverwriteSettings(const QJsonObject& postedObject, QVariantMap& settingsVariant); void updateSetting(const QString& key, const QJsonValue& newValue, QVariantMap& settingMap, const QJsonObject& settingDescription); QJsonObject settingDescriptionFromGroup(const QJsonObject& groupObject, const QString& settingName); void persistToFile(); QJsonArray _descriptionArray; HifiConfigVariantMap _configMap; }; #endif // hifi_DomainServerSettingsManager_h
35.326923
110
0.777899
2c97c619c2462576218ad0d06795fa8ccc6e4f6b
2,093
h
C
llvm/lib/Target/Lanai/LanaiMachineFunctionInfo.h
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
4,812
2015-01-02T19:38:10.000Z
2022-03-27T12:42:24.000Z
llvm/lib/Target/Lanai/LanaiMachineFunctionInfo.h
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
127
2015-12-03T21:42:53.000Z
2019-11-21T14:34:20.000Z
llvm/lib/Target/Lanai/LanaiMachineFunctionInfo.h
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
2,543
2015-01-01T11:18:36.000Z
2022-03-22T21:32:36.000Z
//===- LanaiMachineFuctionInfo.h - Lanai machine func info -------*- C++ -*-==// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file declares Lanai-specific per-machine-function information. // //===----------------------------------------------------------------------===// #ifndef LLVM_LIB_TARGET_LANAI_LANAIMACHINEFUNCTIONINFO_H #define LLVM_LIB_TARGET_LANAI_LANAIMACHINEFUNCTIONINFO_H #include "LanaiRegisterInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineRegisterInfo.h" namespace llvm { // LanaiMachineFunctionInfo - This class is derived from MachineFunction and // contains private Lanai target-specific information for each MachineFunction. class LanaiMachineFunctionInfo : public MachineFunctionInfo { virtual void anchor(); MachineFunction &MF; // SRetReturnReg - Lanai ABI require that sret lowering includes // returning the value of the returned struct in a register. This field // holds the virtual register into which the sret argument is passed. unsigned SRetReturnReg; // GlobalBaseReg - keeps track of the virtual register initialized for // use as the global base register. This is used for PIC in some PIC // relocation models. unsigned GlobalBaseReg; // VarArgsFrameIndex - FrameIndex for start of varargs area. int VarArgsFrameIndex; public: explicit LanaiMachineFunctionInfo(MachineFunction &MF) : MF(MF), SRetReturnReg(0), GlobalBaseReg(0), VarArgsFrameIndex(0) {} unsigned getSRetReturnReg() const { return SRetReturnReg; } void setSRetReturnReg(unsigned Reg) { SRetReturnReg = Reg; } unsigned getGlobalBaseReg(); int getVarArgsFrameIndex() const { return VarArgsFrameIndex; } void setVarArgsFrameIndex(int Index) { VarArgsFrameIndex = Index; } }; } // namespace llvm #endif // LLVM_LIB_TARGET_LANAI_LANAIMACHINEFUNCTIONINFO_H
36.086207
80
0.709986
d61522e3e94af4269a7d606a986ddd67f215550a
1,455
h
C
third_party/blink/renderer/core/feature_policy/document_policy_parser.h
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/core/feature_policy/document_policy_parser.h
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/core/feature_policy/document_policy_parser.h
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2020 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 THIRD_PARTY_BLINK_RENDERER_CORE_FEATURE_POLICY_DOCUMENT_POLICY_PARSER_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_FEATURE_POLICY_DOCUMENT_POLICY_PARSER_H_ #include "third_party/blink/public/common/feature_policy/document_policy.h" #include "third_party/blink/public/common/feature_policy/document_policy_features.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/feature_policy/policy_helper.h" #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" namespace blink { class CORE_EXPORT DocumentPolicyParser { STATIC_ONLY(DocumentPolicyParser); public: // Parse document policy header and 'policy' attribute on iframe to // DocumentPolicy::FeatureState. static base::Optional<DocumentPolicy::ParsedDocumentPolicy> Parse( const String& policy_string); // Internal parsing method for testing. static base::Optional<DocumentPolicy::ParsedDocumentPolicy> ParseInternal( const String& policy_string, const DocumentPolicyNameFeatureMap& name_feature_map, const DocumentPolicyFeatureInfoMap& feature_info_map, const DocumentPolicyFeatureSet& available_features); }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_FEATURE_POLICY_DOCUMENT_POLICY_PARSER_H_
42.794118
84
0.820619
965748ba0657c3500efe51ac57837cbc022625a9
60,150
c
C
src/protocols/survival/Packet.c
PrecipiceGames/craftd
237b9ef3063736380414a459fe4261781570ef39
[ "BSD-2-Clause" ]
2
2015-07-08T08:22:13.000Z
2016-04-23T13:34:46.000Z
src/protocols/survival/Packet.c
PrecipiceGames/craftd
237b9ef3063736380414a459fe4261781570ef39
[ "BSD-2-Clause" ]
null
null
null
src/protocols/survival/Packet.c
PrecipiceGames/craftd
237b9ef3063736380414a459fe4261781570ef39
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2010-2011 Kevin M. Bowling, <kevin.bowling@kev009.com>, USA * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "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. */ #include <craftd/Logger.h> #include <craftd/protocols/survival/Packet.h> SVPacket* SV_PacketFromBuffers (CDBuffers* buffers, bool isResponse) { SVPacket* self = CD_malloc(sizeof(SVPacket)); assert(self); if (isResponse) { self->chain = SVResponse; } else { self->chain = SVRequest; } self->type = (uint32_t) (uint8_t) SV_BufferRemoveByte(buffers->input); self->data = SV_GetPacketDataFromBuffer(self, buffers->input); if (!self->data) { ERR("unparsable packet 0x%.2X", self->type); SV_DestroyPacket(self); errno = EILSEQ; return NULL; } return self; } void SV_DestroyPacket (SVPacket* self) { assert(self); SV_DestroyPacketData(self); CD_free((void*) self->data); CD_free(self); } void SV_DestroyPacketData (SVPacket* self) { if (!self->data) { return; } switch (self->chain) { case SVRequest: { switch (self->type) { case SVLogin: { SVPacketLogin* packet = (SVPacketLogin*) self->data; SV_DestroyString(packet->request.username); } break; case SVHandshake: { SVPacketHandshake* packet = (SVPacketHandshake*) self->data; SV_DestroyString(packet->request.username); } break; case SVChat: { SVPacketChat* packet = (SVPacketChat*) self->data; SV_DestroyString(packet->request.message); } break; case SVEntityMetadata: { SVPacketEntityMetadata* packet = (SVPacketEntityMetadata*) self->data; SV_DestroyMetadata(packet->request.metadata); } break; case SVUpdateSign: { SVPacketUpdateSign* packet = (SVPacketUpdateSign*) self->data; SV_DestroyString(packet->request.first); SV_DestroyString(packet->request.second); SV_DestroyString(packet->request.third); SV_DestroyString(packet->request.fourth); } break; case SVDisconnect: { SVPacketDisconnect* packet = (SVPacketDisconnect*) self->data; SV_DestroyString(packet->request.reason); } default: break; } } break; case SVPing: { switch(self->type) { case SVDisconnect: { SVPacketDisconnect* packet = (SVPacketDisconnect*) self->data; SV_DestroyString(packet->ping.description); } break; default: break; } }break; case SVResponse: { switch (self->type) { case SVLogin: { SVPacketLogin* packet = (SVPacketLogin*) self->data; SV_DestroyString(packet->response.u1); } break; case SVHandshake: { SVPacketHandshake* packet = (SVPacketHandshake*) self->data; SV_DestroyString(packet->response.hash); } break; case SVChat: { SVPacketChat* packet = (SVPacketChat*) self->data; SV_DestroyString(packet->request.message); } break; case SVNamedEntitySpawn: { SVPacketNamedEntitySpawn* packet = (SVPacketNamedEntitySpawn*) self->data; SV_DestroyString(packet->response.name); } break; case SVSpawnMob: { SVPacketSpawnMob* packet = (SVPacketSpawnMob*) self->data; SV_DestroyMetadata(packet->response.metadata); } break; case SVPainting: { SVPacketPainting* packet = (SVPacketPainting*) self->data; SV_DestroyString(packet->response.title); } break; case SVEntityMetadata: { SVPacketEntityMetadata* packet = (SVPacketEntityMetadata*) self->data; SV_DestroyMetadata(packet->response.metadata); } break; case SVMapChunk: { SVPacketMapChunk* packet = (SVPacketMapChunk*) self->data; CD_free(packet->response.item); } break; case SVMultiBlockChange: { SVPacketMultiBlockChange* packet = (SVPacketMultiBlockChange*) self->data; CD_free(packet->response.coordinate); CD_free(packet->response.type); CD_free(packet->response.metadata); } break; case SVExplosion: { SVPacketExplosion* packet = (SVPacketExplosion*) self->data; CD_free(packet->response.item); } break; case SVOpenWindow: { SVPacketOpenWindow* packet = (SVPacketOpenWindow*) self->data; SV_DestroyString(packet->response.title); } break; case SVWindowItems: { SVPacketWindowItems* packet = (SVPacketWindowItems*) self->data; CD_free(packet->response.item); } break; case SVItemData: { SVPacketItemData* packet = (SVPacketItemData*) self->data; CD_free(packet->response.text); //This value is a byte array, not a string. Blame notch and his names! } case SVDisconnect: { SVPacketDisconnect* packet = (SVPacketDisconnect*) self->data; SV_DestroyString(packet->response.reason); } break; default: break; } } break; } } CDPointer SV_GetPacketDataFromBuffer (SVPacket* self, CDBuffer* input) { assert(self); assert(input); DEBUG("Recieved packet type %x",self->type); switch (self->chain) { case SVRequest: { switch (self->type) { case SVKeepAlive: { SVPacketKeepAlive* packet = (SVPacketKeepAlive*) CD_malloc(sizeof(SVPacketKeepAlive)); packet->keepAliveID = SV_BufferRemoveInteger(input); return (CDPointer) packet; } case SVLogin: { SVPacketLogin* packet = (SVPacketLogin*) CD_malloc(sizeof(SVPacketLogin)); SV_BufferRemoveFormat(input, "iUlibbbb", &packet->request.version, &packet->request.username, &packet->request.u1, &packet->request.u2, &packet->request.u3, &packet->request.u4, &packet->request.u5, &packet->request.u6 ); return (CDPointer) packet; } case SVHandshake: { SVPacketHandshake* packet = (SVPacketHandshake*) CD_malloc(sizeof(SVPacketHandshake)); packet->request.username = SV_BufferRemoveString16(input); return (CDPointer) packet; } case SVChat: { SVPacketChat* packet = (SVPacketChat*) CD_malloc(sizeof(SVPacketChat)); packet->request.message = SV_BufferRemoveString16(input); return (CDPointer) packet; } case SVUseEntity: { SVPacketUseEntity* packet = (SVPacketUseEntity*) CD_malloc(sizeof(SVPacketUseEntity)); SV_BufferRemoveFormat(input, "iib", &packet->request.user, &packet->request.target, &packet->request.leftClick ); return (CDPointer) packet; } case SVRespawn: { SVPacketRespawn* packet = (SVPacketRespawn*) CD_malloc(sizeof(SVPacketRespawn)); SV_BufferRemoveFormat(input, "bbbsl", &packet->request.world, &packet->request.u1, &packet->request.mode, &packet->request.worldHeight, &packet->request.mapSeed ); return (CDPointer) packet; } case SVOnGround: { SVPacketOnGround* packet = (SVPacketOnGround*) CD_malloc(sizeof(SVPacketOnGround)); packet->request.onGround = SV_BufferRemoveBoolean(input); return (CDPointer) packet; } case SVPlayerPosition: { SVPacketPlayerPosition* packet = (SVPacketPlayerPosition*) CD_malloc(sizeof(SVPacketPlayerPosition)); SV_BufferRemoveFormat(input, "ddddb", &packet->request.position.x, &packet->request.position.y, &packet->request.stance, &packet->request.position.z, &packet->request.is.onGround ); return (CDPointer) packet; } case SVPlayerLook: { SVPacketPlayerLook* packet = (SVPacketPlayerLook*) CD_malloc(sizeof(SVPacketPlayerLook)); SV_BufferRemoveFormat(input, "ffb", &packet->request.yaw, &packet->request.pitch, &packet->request.is.onGround ); return (CDPointer) packet; } case SVPlayerMoveLook: { SVPacketPlayerMoveLook* packet = (SVPacketPlayerMoveLook*) CD_malloc(sizeof(SVPacketPlayerMoveLook)); SV_BufferRemoveFormat(input, "ddddffb", &packet->request.position.x, &packet->request.stance, &packet->request.position.y, &packet->request.position.z, &packet->request.yaw, &packet->request.pitch, &packet->request.is.onGround ); return (CDPointer) packet; } case SVPlayerDigging: { SVPacketPlayerDigging* packet = (SVPacketPlayerDigging*) CD_malloc(sizeof(SVPacketPlayerDigging)); packet->request.status = SV_BufferRemoveByte(input); SV_BufferRemoveFormat(input, "ibi", &packet->request.position.x, &packet->request.position.y, &packet->request.position.z ); packet->request.face = SV_BufferRemoveByte(input); return (CDPointer) packet; } case SVPlayerBlockPlacement: { SVPacketPlayerBlockPlacement* packet = (SVPacketPlayerBlockPlacement*) CD_malloc(sizeof(SVPacketPlayerBlockPlacement)); memset(&packet->request.item, 0, sizeof(SVItemStack)); SV_BufferRemoveFormat(input, "ibibs", &packet->request.position.x, &packet->request.position.y, &packet->request.position.z, &packet->request.direction, &packet->request.item.id ); if (packet->request.item.id != -1) { SV_BufferRemoveFormat(input, "bs", &packet->request.item.count, &packet->request.item.damage ); } return (CDPointer) packet; } case SVHoldChange: { SVPacketHoldChange* packet = (SVPacketHoldChange*) CD_malloc(sizeof(SVPacketHoldChange)); packet->request.slot = SV_BufferRemoveShort(input); return (CDPointer) packet; } case SVAnimation: { SVPacketAnimation* packet = (SVPacketAnimation*) CD_malloc(sizeof(SVPacketAnimation)); SV_BufferRemoveFormat(input, "ib", &packet->request.entity.id, &packet->request.type ); return (CDPointer) packet; } case SVEntityAction: { SVPacketEntityAction* packet = (SVPacketEntityAction*) CD_malloc(sizeof(SVPacketEntityAction)); SV_BufferRemoveFormat(input, "ib", &packet->request.entity.id, &packet->request.type ); return (CDPointer) packet; } case SVStanceUpdate: { //This is most likely a packet that isn't used, but it might be in the future SVPacketStanceUpdate* packet = (SVPacketStanceUpdate*) CD_malloc(sizeof(SVPacketStanceUpdate)); SV_BufferRemoveFormat(input, "ffffBB", &packet->request.u1, &packet->request.u2, &packet->request.u3, &packet->request.u4, &packet->request.u5, &packet->request.u6 ); return (CDPointer) packet; } case SVEntityMetadata: { SVPacketEntityMetadata* packet = (SVPacketEntityMetadata*) CD_malloc(sizeof(SVPacketEntityMetadata)); SV_BufferRemoveFormat(input, "iM", &packet->request.entity.id, &packet->request.metadata ); return (CDPointer) packet; } case SVEntityEffect: { SVPacketEntityEffect* packet = (SVPacketEntityEffect*) CD_malloc(sizeof(SVPacketEntityEffect)); SV_BufferRemoveFormat(input, "ibbs", &packet->request.entity.id, &packet->request.effect, &packet->request.amplifier, &packet->request.duration ); return (CDPointer) packet; } case SVRemoveEntityEffect: { SVPacketRemoveEntityEffect* packet = (SVPacketRemoveEntityEffect*) CD_malloc(sizeof(SVPacketRemoveEntityEffect)); SV_BufferRemoveFormat(input, "ib", &packet->request.entity.id, &packet->request.effect ); return (CDPointer) packet; } case SVCloseWindow: { SVPacketCloseWindow* packet = (SVPacketCloseWindow*) CD_malloc(sizeof(SVPacketCloseWindow)); packet->request.id = SV_BufferRemoveByte(input); return (CDPointer) packet; } case SVWindowClick: { SVPacketWindowClick* packet = (SVPacketWindowClick*) CD_malloc(sizeof(SVPacketWindowClick)); memset(&packet->request.item, 0, sizeof(SVItemStack)); SV_BufferRemoveFormat(input, "bsBsBs", &packet->request.id, &packet->request.slot, &packet->request.rightClick, &packet->request.action, &packet->request.shiftPressed, &packet->request.item.id ); if (packet->request.item.id != -1) { SV_BufferRemoveFormat(input, "bs", &packet->request.item.count, &packet->request.item.damage ); } return (CDPointer) packet; } case SVTransaction: { SVPacketTransaction* packet = (SVPacketTransaction*) CD_malloc(sizeof(SVPacketTransaction)); SV_BufferRemoveFormat(input, "bsB", &packet->request.id, &packet->request.action, &packet->request.accepted ); return (CDPointer) packet; } case SVCreativeInventoryAction: { SVPacketCreativeInventoryAction* packet = (SVPacketCreativeInventoryAction*) CD_malloc(sizeof(SVPacketCreativeInventoryAction)); SV_BufferRemoveFormat(input, "ssss", &packet->request.slot, &packet->request.itemId, &packet->request.quantity, &packet->request.damage ); return (CDPointer) packet; } case SVUpdateSign: { SVPacketUpdateSign* packet = (SVPacketUpdateSign*) CD_malloc(sizeof(SVPacketUpdateSign)); SV_BufferRemoveFormat(input, "isiUUUU", &packet->request.position.x, &packet->request.position.y, &packet->request.position.z, &packet->request.first, &packet->request.second, &packet->request.third, &packet->request.fourth ); return (CDPointer) packet; } case SVIncrementStatistic: { SVPacketIncrementStatistic* packet = (SVPacketIncrementStatistic*) CD_malloc(sizeof(SVPacketIncrementStatistic)); SV_BufferRemoveFormat(input, "ib", &packet->request.id, &packet->request.amount ); return (CDPointer) packet; } case SVListPing: { return (CDPointer) CD_malloc(sizeof(SVPacketListPing)); } case SVDisconnect: { SVPacketDisconnect* packet = (SVPacketDisconnect*) CD_malloc(sizeof(SVPacketDisconnect)); packet->request.reason = SV_BufferRemoveString16(input); return (CDPointer) packet; } default: { return (CDPointer) NULL; } } } break; case SVPing: { switch(self->type) { case SVDisconnect: { SVPacketDisconnect* packet = (SVPacketDisconnect*) CD_malloc(sizeof(SVPacketDisconnect)); packet->request.reason = SV_BufferRemoveString16(input); return (CDPointer) packet; } default: { return (CDPointer) NULL; } } } break; case SVResponse: { switch (self->type) { case SVKeepAlive: { SVPacketKeepAlive* packet = (SVPacketKeepAlive*) CD_malloc(sizeof(SVPacketKeepAlive)); packet->keepAliveID = SV_BufferRemoveInteger(input); return (CDPointer) packet; } case SVLogin: { SVPacketLogin* packet = (SVPacketLogin*) CD_malloc(sizeof(SVPacketLogin)); SV_BufferRemoveFormat(input, "iUlibbbb", &packet->response.id, &packet->response.u1, &packet->response.mapSeed, &packet->response.serverMode, &packet->response.dimension, &packet->response.u2, &packet->response.worldHeight, &packet->response.maxPlayers ); return (CDPointer) packet; } case SVHandshake: { SVPacketHandshake* packet = (SVPacketHandshake*) CD_malloc(sizeof(SVPacketHandshake)); packet->response.hash = SV_BufferRemoveString16(input); return (CDPointer) packet; } case SVChat: { SVPacketChat* packet = (SVPacketChat*) CD_malloc(sizeof(SVPacketChat)); packet->response.message = SV_BufferRemoveString16(input); return (CDPointer) packet; } case SVTimeUpdate: { SVPacketTimeUpdate* packet = (SVPacketTimeUpdate*) CD_malloc(sizeof(SVPacketTimeUpdate)); packet->response.time = SV_BufferRemoveLong(input); return (CDPointer) packet; } case SVEntityEquipment: { SVPacketEntityEquipment* packet = (SVPacketEntityEquipment*) CD_malloc(sizeof(SVPacketEntityEquipment)); SV_BufferRemoveFormat(input, "isss", &packet->response.entity, &packet->response.slot, &packet->response.item, &packet->response.damage ); return (CDPointer) packet; } case SVSpawnPosition: { SVPacketSpawnPosition* packet = (SVPacketSpawnPosition*) CD_malloc(sizeof(SVPacketSpawnPosition)); SVInteger y; SV_BufferRemoveFormat(input, "iii", &packet->response.position.x, &y, &packet->response.position.z ); packet->response.position.y = y; return (CDPointer) packet; } case SVUpdateHealth: { SVPacketUpdateHealth* packet = (SVPacketUpdateHealth*) CD_malloc(sizeof(SVPacketUpdateHealth)); SV_BufferRemoveFormat(input, "ssf", &packet->response.health, &packet->response.food, &packet->response.foodSaturation ); return (CDPointer) packet; } case SVRespawn: { SVPacketRespawn* packet = (SVPacketRespawn*) CD_malloc(sizeof(SVPacketRespawn)); SV_BufferRemoveFormat(input, "bbbsl", &packet->response.world, &packet->response.u1, &packet->response.mode, &packet->response.worldHeight, &packet->response.mapSeed ); return (CDPointer) packet; } case SVPlayerMoveLook: { SVPacketPlayerMoveLook* packet = (SVPacketPlayerMoveLook*) CD_malloc(sizeof(SVPacketPlayerMoveLook)); SV_BufferRemoveFormat(input, "ddddffb", &packet->response.position.x, &packet->response.position.y, &packet->response.stance, &packet->response.position.z, &packet->response.yaw, &packet->response.pitch, &packet->response.is.onGround ); return (CDPointer) packet; } case SVUseBed: { SVPacketUseBed* packet = (SVPacketUseBed*) CD_malloc(sizeof(SVPacketUseBed)); SV_BufferRemoveFormat(input, "ibibi", &packet->response.entity.id, &packet->response.inBed, &packet->response.position.x, &packet->response.position.y, &packet->response.position.z ); return (CDPointer) packet; } case SVAnimation: { SVPacketAnimation* packet = (SVPacketAnimation*) CD_malloc(sizeof(SVPacketAnimation)); SV_BufferRemoveFormat(input, "ib", &packet->response.entity.id, &packet->response.type ); return (CDPointer) packet; } case SVNamedEntitySpawn: { SVPacketNamedEntitySpawn* packet = (SVPacketNamedEntitySpawn*) CD_malloc(sizeof(SVPacketNamedEntitySpawn)); SV_BufferRemoveFormat(input, "iUiiibbs", &packet->response.entity.id, &packet->response.name, &packet->response.position.x, &packet->response.position.y, &packet->response.position.z, &packet->response.rotation, &packet->response.pitch, &packet->response.itemId ); return (CDPointer) packet; } case SVPickupSpawn: { SVPacketPickupSpawn* packet = (SVPacketPickupSpawn*) CD_malloc(sizeof(SVPacketPickupSpawn)); SV_BufferRemoveFormat(input, "isbsiiibbb", &packet->response.entity.id, &packet->response.item.id, &packet->response.item.count, &packet->response.item.damage, &packet->response.position.x, &packet->response.position.y, &packet->response.position.z, &packet->response.rotation, &packet->response.pitch, &packet->response.roll ); return (CDPointer) packet; } case SVCollectItem: { SVPacketCollectItem* packet = (SVPacketCollectItem*) CD_malloc(sizeof(SVPacketCollectItem)); SV_BufferRemoveFormat(input, "ii", &packet->response.collected, &packet->response.collector ); return (CDPointer) packet; } case SVSpawnObject: { SVPacketSpawnObject* packet = (SVPacketSpawnObject*) CD_malloc(sizeof(SVPacketSpawnObject)); SV_BufferRemoveFormat(input, "ibiiii", &packet->response.entity.id, &packet->response.type, &packet->response.position.x, &packet->response.position.y, &packet->response.position.z, &packet->response.flag ); if (packet->response.flag > 0) { SV_BufferRemoveFormat(input, "sss", &packet->response.u1, &packet->response.u2, &packet->response.u3 ); } return (CDPointer) packet; } case SVSpawnMob: { SVPacketSpawnMob* packet = (SVPacketSpawnMob*) CD_malloc(sizeof(SVPacketSpawnMob)); SV_BufferRemoveFormat(input, "ibiiibbM", &packet->response.id, &packet->response.type, &packet->response.position.x, &packet->response.position.y, &packet->response.position.z, &packet->response.yaw, &packet->response.pitch, &packet->response.metadata ); return (CDPointer) packet; } case SVPainting: { SVPacketPainting* packet = (SVPacketPainting*) CD_malloc(sizeof(SVPacketPainting)); SVInteger y; SV_BufferRemoveFormat(input, "iUiiii", &packet->response.entity.id, &packet->response.title, &packet->response.position.x, &y, &packet->response.position.z, &packet->response.direction ); packet->response.position.y = y; return (CDPointer) packet; } case SVExperienceOrb: { SVPacketExperienceOrb* packet = (SVPacketExperienceOrb*) CD_malloc(sizeof(SVPacketExperienceOrb)); SVInteger y; SV_BufferRemoveFormat(input, "iiiis", &packet->response.entity.id, &packet->response.position.x, &y, &packet->response.position.z, &packet->response.count ); packet->response.position.y = y; return (CDPointer) packet; } case SVStanceUpdate: { //This is most likely a packet that isn't used, but it might be in the future SVPacketStanceUpdate* packet = (SVPacketStanceUpdate*) CD_malloc(sizeof(SVPacketStanceUpdate)); SV_BufferRemoveFormat(input, "ffffBB", &packet->response.u1, &packet->response.u2, &packet->response.u3, &packet->response.u4, &packet->response.u5, &packet->response.u6 ); return (CDPointer) packet; } case SVEntityVelocity: { SVPacketEntityVelocity* packet = (SVPacketEntityVelocity*) CD_malloc(sizeof(SVPacketEntityVelocity)); SV_BufferRemoveFormat(input, "isss", &packet->response.entity.id, &packet->response.velocity.x, &packet->response.velocity.y, &packet->response.velocity.z ); return (CDPointer) packet; } case SVEntityDestroy: { SVPacketEntityDestroy* packet = (SVPacketEntityDestroy*) CD_malloc(sizeof(SVPacketEntityDestroy)); packet->response.entity.id = SV_BufferRemoveInteger(input); return (CDPointer) packet; } case SVEntityCreate: { SVPacketEntityCreate* packet = (SVPacketEntityCreate*) CD_malloc(sizeof(SVPacketEntityCreate)); packet->response.entity.id = SV_BufferRemoveInteger(input); return (CDPointer) packet; } case SVEntityRelativeMove: { SVPacketEntityRelativeMove* packet = (SVPacketEntityRelativeMove*) CD_malloc(sizeof(SVPacketEntityRelativeMove)); SV_BufferRemoveFormat(input, "ibbb", &packet->response.entity.id, &packet->response.position.x, &packet->response.position.y, &packet->response.position.z ); return (CDPointer) packet; } case SVEntityLook: { SVPacketEntityLook* packet = (SVPacketEntityLook*) CD_malloc(sizeof(SVPacketEntityLook)); SV_BufferRemoveFormat(input, "ibb", &packet->response.entity.id, &packet->response.yaw, &packet->response.pitch ); return (CDPointer) packet; } case SVEntityLookMove: { SVPacketEntityLookMove* packet = (SVPacketEntityLookMove*) CD_malloc(sizeof(SVPacketEntityLookMove)); SV_BufferRemoveFormat(input, "ibbbbb", &packet->response.entity.id, &packet->response.position.x, &packet->response.position.y, &packet->response.position.z, &packet->response.yaw, &packet->response.pitch ); return (CDPointer) packet; } case SVEntityTeleport: { SVPacketEntityTeleport* packet = (SVPacketEntityTeleport*) CD_malloc(sizeof(SVPacketEntityTeleport)); SV_BufferRemoveFormat(input, "iiiibb", &packet->response.entity.id, &packet->response.position.x, &packet->response.position.y, &packet->response.position.z, &packet->response.rotation, &packet->response.pitch ); return (CDPointer) packet; } case SVEntityStatus: { SVPacketEntityStatus* packet = (SVPacketEntityStatus*) CD_malloc(sizeof(SVPacketEntityStatus)); SV_BufferRemoveFormat(input, "ib", &packet->response.entity.id, &packet->response.status ); return (CDPointer) packet; } case SVEntityAttach: { SVPacketEntityAttach* packet = (SVPacketEntityAttach*) CD_malloc(sizeof(SVPacketEntityAttach)); SV_BufferRemoveFormat(input, "ii", &packet->response.entity.id, &packet->response.vehicle.id ); return (CDPointer) packet; } case SVEntityMetadata: { SVPacketEntityMetadata* packet = (SVPacketEntityMetadata*) CD_malloc(sizeof(SVPacketEntityMetadata)); SV_BufferRemoveFormat(input, "iM", &packet->response.entity.id, &packet->response.metadata ); return (CDPointer) packet; } case SVEntityEffect: { SVPacketEntityEffect* packet = (SVPacketEntityEffect*) CD_malloc(sizeof(SVPacketEntityEffect)); SV_BufferRemoveFormat(input, "ibbs", &packet->response.entity.id, &packet->response.effect, &packet->response.amplifier, &packet->response.duration ); return (CDPointer) packet; } case SVRemoveEntityEffect: { SVPacketRemoveEntityEffect* packet = (SVPacketRemoveEntityEffect*) CD_malloc(sizeof(SVPacketRemoveEntityEffect)); SV_BufferRemoveFormat(input, "ib", &packet->response.entity.id, &packet->response.effect ); return (CDPointer) packet; } case SVExperience: { SVPacketExperience* packet = (SVPacketExperience*) CD_malloc(sizeof(SVPacketExperience)); SV_BufferRemoveFormat(input, "bbs", &packet->response.currentExperience, &packet->response.level, &packet->response.totalExperience ); return (CDPointer) packet; } case SVPreChunk: { SVPacketPreChunk* packet = (SVPacketPreChunk*) CD_malloc(sizeof(SVPacketPreChunk)); SV_BufferRemoveFormat(input, "iib", &packet->response.position.x, &packet->response.position.z, &packet->response.mode ); return (CDPointer) packet; } case SVMapChunk: { SVPacketMapChunk* packet = (SVPacketMapChunk*) CD_malloc(sizeof(SVPacketMapChunk)); SVShort y; SV_BufferRemoveFormat(input, "isibbbi", &packet->response.position.x, &y, &packet->response.position.z, &packet->response.size.x, &packet->response.size.y, &packet->response.size.z, &packet->response.length ); packet->response.size.x++; packet->response.size.y++; packet->response.size.z++; packet->response.position.y = y; packet->response.item = (SVByte*)CD_BufferRemove(input, packet->response.length * SVByteSize); return (CDPointer) packet; } case SVMultiBlockChange: { SVPacketMultiBlockChange* packet = (SVPacketMultiBlockChange*) CD_malloc(sizeof(SVPacketMultiBlockChange)); SV_BufferRemoveFormat(input, "iis", &packet->response.position.x, &packet->response.position.z, &packet->response.length ); packet->response.coordinate = (SVShort*)CD_BufferRemove(input, packet->response.length * SVShortSize); packet->response.type = (SVByte*)CD_BufferRemove(input, packet->response.length * SVByteSize); packet->response.metadata = (SVByte*)CD_BufferRemove(input, packet->response.length * SVByteSize); return (CDPointer) packet; } case SVBlockChange: { SVPacketBlockChange* packet = (SVPacketBlockChange*) CD_malloc(sizeof(SVPacketBlockChange)); SV_BufferRemoveFormat(input, "ibibb", &packet->response.position.x, &packet->response.position.y, &packet->response.position.z, &packet->response.type, &packet->response.metadata ); return (CDPointer) packet; } case SVPlayNoteBlock: { SVPacketPlayNoteBlock* packet = (SVPacketPlayNoteBlock*) CD_malloc(sizeof(SVPacketPlayNoteBlock)); SVShort y; SV_BufferRemoveFormat(input, "isibb", &packet->response.position.x, &y, &packet->response.position.z, &packet->response.data1, &packet->response.data2 ); packet->response.position.y = y; return (CDPointer) packet; } case SVExplosion: { SVPacketExplosion* packet = (SVPacketExplosion*) CD_malloc(sizeof(SVPacketExplosion)); SV_BufferRemoveFormat(input, "dddfi", &packet->response.position.x, &packet->response.position.y, &packet->response.position.z, &packet->response.radius, &packet->response.length ); packet->response.item = (SVRelativePosition*)CD_BufferRemove(input, packet->response.length * sizeof(SVRelativePosition)); return (CDPointer) packet; } case SVSoundEffect: { SVPacketSoundEffect* packet = (SVPacketSoundEffect*) CD_malloc(sizeof(SVPacketSoundEffect)); SV_BufferRemoveFormat(input, "iibii", &packet->response.effect, &packet->response.position.x, &packet->response.position.y, &packet->response.position.z, &packet->response.data ); return (CDPointer) packet; } case SVState: { SVPacketState* packet = (SVPacketState*) CD_malloc(sizeof(SVPacketState)); SV_BufferRemoveFormat(input, "bb", &packet->response.reason, &packet->response.gameMode ); return (CDPointer) packet; } case SVThunderbolt: { SVPacketThunderbolt* packet = (SVPacketThunderbolt*) CD_malloc(sizeof(SVPacketThunderbolt)); SV_BufferRemoveFormat(input, "iBiii", &packet->response.entity, &packet->response.u1, &packet->response.position.x, &packet->response.position.y, &packet->response.position.z ); return (CDPointer) packet; } case SVOpenWindow: { SVPacketOpenWindow* packet = (SVPacketOpenWindow*) CD_malloc(sizeof(SVPacketOpenWindow)); SV_BufferRemoveFormat(input, "bbUb", &packet->response.id, &packet->response.type, &packet->response.title, &packet->response.slots ); return (CDPointer) packet; } case SVCloseWindow: { SVPacketCloseWindow* packet = (SVPacketCloseWindow*) CD_malloc(sizeof(SVPacketCloseWindow)); packet->response.id = SV_BufferRemoveByte(input); return (CDPointer) packet; } case SVSetSlot: { SVPacketSetSlot* packet = (SVPacketSetSlot*) CD_malloc(sizeof(SVPacketSetSlot)); SV_BufferRemoveFormat(input, "bss", &packet->response.windowId, &packet->response.item.slot, &packet->response.item.id ); if (packet->response.item.id != -1) { packet->response.item.count = SV_BufferRemoveByte(input); packet->response.item.damage = SV_BufferRemoveShort(input); } return (CDPointer) packet; } case SVWindowItems: { SVPacketWindowItems* packet = (SVPacketWindowItems*) CD_malloc(sizeof(SVPacketWindowItems)); SV_BufferRemoveFormat(input, "bs", &packet->response.id, &packet->response.length ); packet->response.item = (SVItemStack*) CD_malloc(sizeof(SVItemStack) * packet->response.length); int i; for (i=0; i<packet->response.length; i++) { SVShort itemId = SV_BufferRemoveShort(input); if (itemId == -1) continue; packet->response.item[i].id = itemId; packet->response.item[i].count = SV_BufferRemoveByte(input); packet->response.item[i].damage = SV_BufferRemoveShort(input); } return (CDPointer) packet; } case SVUpdateProgressBar: { SVPacketUpdateProgressBar* packet = (SVPacketUpdateProgressBar*) CD_malloc(sizeof(SVPacketUpdateProgressBar)); SV_BufferRemoveFormat(input, "bss", &packet->response.id, &packet->response.bar, &packet->response.value ); } case SVTransaction: { SVPacketTransaction* packet = (SVPacketTransaction*) CD_malloc(sizeof(SVPacketTransaction)); SV_BufferRemoveFormat(input, "bsB", &packet->response.id, &packet->response.action, &packet->response.accepted ); return (CDPointer) packet; } case SVCreativeInventoryAction: { SVPacketCreativeInventoryAction* packet = (SVPacketCreativeInventoryAction*) CD_malloc(sizeof(SVPacketCreativeInventoryAction)); SV_BufferRemoveFormat(input, "ssss", &packet->response.slot, &packet->response.itemId, &packet->response.quantity, &packet->response.damage ); return (CDPointer) packet; } case SVUpdateSign: { SVPacketUpdateSign* packet = (SVPacketUpdateSign*) CD_malloc(sizeof(SVPacketUpdateSign)); SV_BufferRemoveFormat(input, "isiUUUU", &packet->response.position.x, &packet->response.position.y, &packet->response.position.z, &packet->response.first, &packet->response.second, &packet->response.third, &packet->response.fourth ); return (CDPointer) packet; } case SVItemData: { SVPacketItemData* packet = (SVPacketItemData*) CD_malloc(sizeof(SVPacketItemData)); SV_BufferRemoveFormat(input, "ssb", &packet->response.itemType, &packet->response.itemId, &packet->response.textLength ); packet->response.text = (SVByte*)CD_BufferRemove(input, (uint8_t)packet->response.textLength * SVByteSize); return (CDPointer) packet; } case SVPlayerListItem: { SVPacketPlayerListItem* packet = (SVPacketPlayerListItem*) CD_malloc(sizeof(SVPacketPlayerListItem)); SV_BufferRemoveFormat(input, "UBs", &packet->response.playerName, &packet->response.online, &packet->response.ping ); return (CDPointer) packet; } case SVDisconnect: { SVPacketDisconnect* packet = (SVPacketDisconnect*) CD_malloc(sizeof(SVPacketDisconnect)); packet->response.reason = SV_BufferRemoveString16(input); return (CDPointer) packet; } default: { return (CDPointer) NULL; } } } break; } return (CDPointer) NULL; } CDBuffer* SV_PacketToBuffer (SVPacket* self) { CDBuffer* data = CD_CreateBuffer(); assert(self); SV_BufferAddByte(data, self->type); switch (self->chain) { case SVRequest: { switch (self->type) { case SVKeepAlive: { SVPacketKeepAlive* packet = (SVPacketKeepAlive*) self->data; SV_BufferAddInteger(data, packet->keepAliveID); } break; case SVLogin: { SVPacketLogin* packet = (SVPacketLogin*) self->data; SV_BufferAddFormat(data, "iUlibbbb", packet->request.version, packet->request.username, packet->request.u1, packet->request.u2, packet->request.u3, packet->request.u4, packet->request.u5, packet->request.u6 ); } break; case SVHandshake: { SVPacketHandshake* packet = (SVPacketHandshake*) self->data; SV_BufferAddString16(data, packet->request.username); } break; case SVChat: { SVPacketChat* packet = (SVPacketChat*) self->data; SV_BufferAddString16(data, packet->request.message); } break; case SVUseEntity: { SVPacketUseEntity* packet = (SVPacketUseEntity*) self->data; SV_BufferAddFormat(data, "iib", packet->request.user, packet->request.target, packet->request.leftClick ); } break; case SVRespawn: { SVPacketRespawn* packet = (SVPacketRespawn*) self->data; SV_BufferAddFormat(data, "bbbsl", packet->request.world, packet->request.u1, packet->request.mode, packet->request.worldHeight, packet->request.mapSeed ); } break; case SVOnGround: { SVPacketOnGround* packet = (SVPacketOnGround*) self->data; SV_BufferAddBoolean(data, packet->request.onGround); } break; case SVPlayerPosition: { SVPacketPlayerPosition* packet = (SVPacketPlayerPosition*) self->data; SV_BufferAddFormat(data, "ddddb", packet->request.position.x, packet->request.position.y, packet->request.stance, packet->request.position.z, packet->request.is.onGround ); } break; case SVPlayerLook: { SVPacketPlayerLook* packet = (SVPacketPlayerLook*) self->data; SV_BufferAddFormat(data, "ffb", packet->request.yaw, packet->request.pitch, packet->request.is.onGround ); } break; case SVPlayerMoveLook: { SVPacketPlayerMoveLook* packet = (SVPacketPlayerMoveLook*) self->data; SV_BufferAddFormat(data, "ddddffb", packet->request.position.x, packet->request.stance, packet->request.position.y, packet->request.position.z, packet->request.yaw, packet->request.pitch, packet->request.is.onGround ); } break; case SVPlayerDigging: { SVPacketPlayerDigging* packet = (SVPacketPlayerDigging*) self->data; SV_BufferAddByte(data, packet->request.status); SV_BufferAddFormat(data, "ibi", packet->request.position.x, packet->request.position.y, packet->request.position.z ); SV_BufferAddByte(data, packet->request.face); } break; case SVPlayerBlockPlacement: { SVPacketPlayerBlockPlacement* packet = (SVPacketPlayerBlockPlacement*) self->data; SV_BufferAddFormat(data, "ibibs", packet->request.position.x, packet->request.position.y, packet->request.position.z, packet->request.direction, packet->request.item.id ); if (packet->request.item.id != -1) { SV_BufferAddFormat(data, "bs", packet->request.item.count, packet->request.item.damage ); } } break; case SVHoldChange: { SVPacketHoldChange* packet = (SVPacketHoldChange*) self->data; SV_BufferAddShort(data, packet->request.slot); } break; case SVAnimation: { SVPacketAnimation* packet = (SVPacketAnimation*) self->data; SV_BufferAddFormat(data, "ib", packet->request.entity.id, packet->request.type ); } break; case SVEntityAction: { SVPacketEntityAction* packet = (SVPacketEntityAction*) self->data; SV_BufferAddFormat(data, "ib", packet->request.entity.id, packet->request.type ); } break; case SVStanceUpdate: { //This is most likely a packet that isn't used, but it might be in the future SVPacketStanceUpdate* packet = (SVPacketStanceUpdate*) self->data; SV_BufferAddFormat(data, "ffffBB", packet->request.u1, packet->request.u2, packet->request.u3, packet->request.u4, packet->request.u5, packet->request.u6 ); } break; case SVEntityMetadata: { SVPacketEntityMetadata* packet = (SVPacketEntityMetadata*) self->data; SV_BufferAddFormat(data, "iM", packet->request.entity.id, packet->request.metadata ); } break; case SVEntityEffect: { SVPacketEntityEffect* packet = (SVPacketEntityEffect*) self->data; SV_BufferAddFormat(data, "ibbs", packet->request.entity.id, packet->request.effect, packet->request.amplifier, packet->request.duration ); } break; case SVRemoveEntityEffect: { SVPacketRemoveEntityEffect* packet = (SVPacketRemoveEntityEffect*) self->data; SV_BufferAddFormat(data, "ib", packet->request.entity.id, packet->request.effect ); } break; case SVCloseWindow: { SVPacketCloseWindow* packet = (SVPacketCloseWindow*) self->data; SV_BufferAddByte(data, packet->request.id); } break; case SVWindowClick: { SVPacketWindowClick* packet = (SVPacketWindowClick*) self->data; SV_BufferAddFormat(data, "bsBsBs", packet->request.id, packet->request.slot, packet->request.rightClick, packet->request.action, packet->request.shiftPressed, packet->request.item.id ); if (packet->request.item.id != -1) { SV_BufferAddFormat(data, "bs", packet->request.item.count, packet->request.item.damage ); } } break; case SVTransaction: { SVPacketTransaction* packet = (SVPacketTransaction*) self->data; SV_BufferAddFormat(data, "bsB", packet->request.id, packet->request.action, packet->request.accepted ); } break; case SVCreativeInventoryAction: { SVPacketCreativeInventoryAction* packet = (SVPacketCreativeInventoryAction*) self->data; SV_BufferAddFormat(data, "ssss", packet->request.slot, packet->request.itemId, packet->request.quantity, packet->request.damage ); } break; case SVUpdateSign: { SVPacketUpdateSign* packet = (SVPacketUpdateSign*) self->data; SV_BufferAddFormat(data, "isiUUUU", packet->request.position.x, packet->request.position.y, packet->request.position.z, packet->request.first, packet->request.second, packet->request.third, packet->request.fourth ); } break; case SVListPing: { } break; case SVDisconnect: { SVPacketDisconnect* packet = (SVPacketDisconnect*) self->data; SV_BufferAddString16(data, packet->request.reason); } break; default: { return NULL; }; } } break; case SVPing: { switch(self->type) { case SVDisconnect: { SVPacketDisconnect* packet = (SVPacketDisconnect*) self->data; SV_BufferAddString16(data, packet->ping.description); } break; default: { return NULL; }; } } break; case SVResponse: { switch (self->type) { case SVKeepAlive: { SVPacketKeepAlive* packet = (SVPacketKeepAlive*) self->data; SV_BufferAddInteger(data, packet->keepAliveID); } break; case SVLogin: { SVPacketLogin* packet = (SVPacketLogin*) self->data; SV_BufferAddFormat(data, "iUlibbbb", packet->response.id, packet->response.u1, packet->response.mapSeed, packet->response.serverMode, packet->response.dimension, packet->response.u2, packet->response.worldHeight, packet->response.maxPlayers ); } break; case SVHandshake: { SVPacketHandshake* packet = (SVPacketHandshake*) self->data; SV_BufferAddString16(data, packet->response.hash); } break; case SVChat: { SVPacketChat* packet = (SVPacketChat*) self->data; SV_BufferAddString16(data, packet->response.message); } break; case SVTimeUpdate: { SVPacketTimeUpdate* packet = (SVPacketTimeUpdate*) self->data; SV_BufferAddLong(data, packet->response.time); } break; case SVEntityEquipment: { SVPacketEntityEquipment* packet = (SVPacketEntityEquipment*) self->data; SV_BufferAddFormat(data, "isss", packet->response.entity.id, packet->response.slot, packet->response.item, packet->response.damage ); } break; case SVSpawnPosition: { SVPacketSpawnPosition* packet = (SVPacketSpawnPosition*) self->data; SV_BufferAddFormat(data, "iii", packet->response.position.x, packet->response.position.y, packet->response.position.z ); } break; case SVUpdateHealth: { SVPacketUpdateHealth* packet = (SVPacketUpdateHealth*) self->data; SV_BufferAddFormat(data, "ssf", packet->response.health, packet->response.food, packet->response.foodSaturation ); } break; case SVRespawn: { SVPacketRespawn* packet = (SVPacketRespawn*) self->data; SV_BufferAddFormat(data, "bbbsl", packet->response.world, packet->response.u1, packet->response.mode, packet->response.worldHeight, packet->response.mapSeed ); } break; case SVPlayerMoveLook: { SVPacketPlayerMoveLook* packet = (SVPacketPlayerMoveLook*) self->data; SV_BufferAddFormat(data, "ddddffB", packet->response.position.x, packet->response.position.y, packet->response.stance, packet->response.position.z, packet->response.yaw, packet->response.pitch, packet->response.is.onGround ); } break; case SVUseBed: { SVPacketUseBed* packet = (SVPacketUseBed*) self->data; SV_BufferAddFormat(data, "ibibi", packet->response.entity.id, packet->response.inBed, packet->response.position.x, packet->response.position.y, packet->response.position.z ); } break; case SVAnimation: { SVPacketAnimation* packet = (SVPacketAnimation*) self->data; SV_BufferAddFormat(data, "ib", packet->response.entity.id, packet->response.type ); } break; case SVNamedEntitySpawn: { SVPacketNamedEntitySpawn* packet = (SVPacketNamedEntitySpawn*) self->data; SV_BufferAddFormat(data, "iUiiibbs", packet->response.entity.id, packet->response.name, packet->response.position.x, packet->response.position.y, packet->response.position.z, packet->response.rotation, packet->response.pitch, packet->response.itemId ); } break; case SVPickupSpawn: { SVPacketPickupSpawn* packet = (SVPacketPickupSpawn*) self->data; SV_BufferAddFormat(data, "isbsiiibbb", packet->response.entity.id, packet->response.item.id, packet->response.item.count, packet->response.item.damage, packet->response.position.x, packet->response.position.y, packet->response.position.z, packet->response.rotation, packet->response.pitch, packet->response.roll ); } break; case SVCollectItem: { SVPacketCollectItem* packet = (SVPacketCollectItem*) self->data; SV_BufferAddFormat(data, "ii", packet->response.collected, packet->response.collector ); } break; case SVSpawnObject: { SVPacketSpawnObject* packet = (SVPacketSpawnObject*) self->data; SV_BufferAddFormat(data, "ibiiii", packet->response.entity.id, packet->response.type, packet->response.position.x, packet->response.position.y, packet->response.position.z, packet->response.flag ); if(packet->response.flag > 0) { //These fields are sent under this condition SV_BufferAddShort(data, packet->response.u1); SV_BufferAddShort(data, packet->response.u2); SV_BufferAddShort(data, packet->response.u3); } } break; case SVSpawnMob: { SVPacketSpawnMob* packet = (SVPacketSpawnMob*) self->data; SV_BufferAddFormat(data, "ibiiibbM", packet->response.id, packet->response.type, packet->response.position.x, packet->response.position.y, packet->response.position.z, packet->response.yaw, packet->response.pitch, packet->response.metadata ); } break; case SVPainting: { SVPacketPainting* packet = (SVPacketPainting*) self->data; SV_BufferAddFormat(data, "iUiiii", packet->response.entity.id, packet->response.title, packet->response.position.x, packet->response.position.y, packet->response.position.z, packet->response.direction ); } break; case SVExperienceOrb: { SVPacketExperienceOrb* packet = (SVPacketExperienceOrb*) self->data; SV_BufferAddFormat(data, "iiiis", packet->response.entity.id, packet->response.position.x, packet->response.position.y, packet->response.position.z, packet->response.count ); } break; case SVStanceUpdate: { SVPacketStanceUpdate* packet = (SVPacketStanceUpdate*) self->data; SV_BufferAddFormat(data, "ffffBB", packet->response.u1, packet->response.u2, packet->response.u3, packet->response.u4, packet->response.u5, packet->response.u6 ); } break; case SVEntityVelocity: { SVPacketEntityVelocity* packet = (SVPacketEntityVelocity*) self->data; SV_BufferAddFormat(data, "isss", packet->response.entity.id, packet->response.velocity.x, packet->response.velocity.y, packet->response.velocity.z ); } break; case SVEntityDestroy: { SVPacketEntityDestroy* packet = (SVPacketEntityDestroy*) self->data; SV_BufferAddInteger(data, packet->response.entity.id); } break; case SVEntityCreate: { SVPacketEntityCreate* packet = (SVPacketEntityCreate*) self->data; SV_BufferAddInteger(data, packet->response.entity.id); } break; case SVEntityRelativeMove: { SVPacketEntityRelativeMove* packet = (SVPacketEntityRelativeMove*) self->data; SV_BufferAddFormat(data, "ibbb", packet->response.entity.id, packet->response.position.x, packet->response.position.y, packet->response.position.z ); } break; case SVEntityLook: { SVPacketEntityLook* packet = (SVPacketEntityLook*) self->data; SV_BufferAddFormat(data, "ibb", packet->response.entity.id, packet->response.yaw, packet->response.pitch ); } break; case SVEntityLookMove: { SVPacketEntityLookMove* packet = (SVPacketEntityLookMove*) self->data; SV_BufferAddFormat(data, "ibbbbb", packet->response.entity.id, packet->response.position.x, packet->response.position.y, packet->response.position.z, packet->response.yaw, packet->response.pitch ); } break; case SVEntityTeleport: { SVPacketEntityTeleport* packet = (SVPacketEntityTeleport*) self->data; SV_BufferAddFormat(data, "iiiibb", packet->response.entity.id, packet->response.position.x, packet->response.position.y, packet->response.position.z, packet->response.rotation, packet->response.pitch ); } break; case SVEntityStatus: { SVPacketEntityStatus* packet = (SVPacketEntityStatus*) self->data; SV_BufferAddFormat(data, "ib", packet->response.entity.id, packet->response.status ); } break; case SVEntityAttach: { SVPacketEntityAttach* packet = (SVPacketEntityAttach*) self->data; SV_BufferAddFormat(data, "ii", packet->response.entity.id, packet->response.vehicle.id ); } break; case SVEntityMetadata: { SVPacketEntityMetadata* packet = (SVPacketEntityMetadata*) self->data; SV_BufferAddFormat(data, "iM", packet->response.entity.id, packet->response.metadata ); } break; case SVEntityEffect: { SVPacketEntityEffect* packet = (SVPacketEntityEffect*) self->data; SV_BufferAddFormat(data, "ibbs", packet->response.entity.id, packet->response.effect, packet->response.amplifier, packet->response.duration ); } break; case SVRemoveEntityEffect: { SVPacketRemoveEntityEffect* packet = (SVPacketRemoveEntityEffect*) self->data; SV_BufferAddFormat(data, "ib", packet->response.entity.id, packet->response.effect ); } break; case SVExperience: { SVPacketExperience* packet = (SVPacketExperience*) self->data; SV_BufferAddFormat(data, "bbs", packet->response.currentExperience, packet->response.level, packet->response.totalExperience ); } break; case SVPreChunk: { SVPacketPreChunk* packet = (SVPacketPreChunk*) self->data; SV_BufferAddFormat(data, "iiB", packet->response.position.x, packet->response.position.z, packet->response.mode ); } break; case SVMapChunk: { SVPacketMapChunk* packet = (SVPacketMapChunk*) self->data; SV_BufferAddFormat(data, "isibbb", packet->response.position.x, packet->response.position.y, packet->response.position.z, packet->response.size.x - 1, packet->response.size.y - 1, packet->response.size.z - 1 ); SV_BufferAddInteger(data, packet->response.length); CD_BufferAdd(data, (CDPointer) packet->response.item, packet->response.length * SVByteSize); } break; case SVMultiBlockChange: { SVPacketMultiBlockChange* packet = (SVPacketMultiBlockChange*) self->data; SV_BufferAddFormat(data, "ii", packet->response.position.x, packet->response.position.z ); SV_BufferAddShort(data, packet->response.length); CD_BufferAdd(data, (CDPointer) packet->response.coordinate, packet->response.length * SVShortSize); CD_BufferAdd(data, (CDPointer) packet->response.type, packet->response.length * SVByteSize); CD_BufferAdd(data, (CDPointer) packet->response.metadata, packet->response.length * SVByteSize); } break; case SVBlockChange: { SVPacketBlockChange* packet = (SVPacketBlockChange*) self->data; SV_BufferAddFormat(data, "ibibb", packet->response.position.x, packet->response.position.y, packet->response.position.z, packet->response.type, packet->response.metadata ); } break; case SVPlayNoteBlock: { //TODO: Rename to SVBlockAction SVPacketPlayNoteBlock* packet = (SVPacketPlayNoteBlock*) self->data; SV_BufferAddFormat(data, "isibb", packet->response.position.x, packet->response.position.y, packet->response.position.z, packet->response.data1, packet->response.data2 ); } break; case SVExplosion: { SVPacketExplosion* packet = (SVPacketExplosion*) self->data; SV_BufferAddFormat(data, "dddf", packet->response.position.x, packet->response.position.y, packet->response.position.z, packet->response.radius ); SV_BufferAddInteger(data, packet->response.length); CD_BufferAdd(data, (CDPointer) packet->response.item, packet->response.length * 3 * SVByteSize); } break; case SVSoundEffect: { SVPacketSoundEffect* packet = (SVPacketSoundEffect*) self->data; SV_BufferAddFormat(data, "iibii", packet->response.effect, packet->response.position.x, packet->response.position.y, packet->response.position.z, packet->response.data ); } break; case SVState: { SVPacketState* packet = (SVPacketState*) self->data; SV_BufferAddFormat(data, "bb", packet->response.reason, packet->response.gameMode ); } break; case SVThunderbolt: { SVPacketThunderbolt* packet = (SVPacketThunderbolt*) self->data; SV_BufferAddFormat(data, "iBiii", packet->response.entity.id, packet->response.u1, packet->response.position.x, packet->response.position.y, packet->response.position.z ); } case SVOpenWindow: { SVPacketOpenWindow* packet = (SVPacketOpenWindow*) self->data; SV_BufferAddFormat(data, "bbSb", packet->response.id, packet->response.type, packet->response.title, packet->response.slots ); } break; case SVCloseWindow: { SVPacketCloseWindow* packet = (SVPacketCloseWindow*) self->data; SV_BufferAddByte(data, packet->response.id); } break; case SVSetSlot: { SVPacketSetSlot* packet = (SVPacketSetSlot*) self->data; SV_BufferAddFormat(data, "bss", packet->response.windowId, packet->response.item.slot, packet->response.item.id ); if (packet->response.item.id != -1) { SV_BufferAddFormat(data, "bs", packet->response.item.count, packet->response.item.damage ); } } break; case SVWindowItems: { SVPacketWindowItems* packet = (SVPacketWindowItems*) self->data; SV_BufferAddByte(data, packet->response.id); SV_BufferAddShort(data, packet->response.length); for (size_t i = 0; i < packet->response.length; i++) { if (packet->response.item[i].id == -1) { SV_BufferAddShort(data, -1); } else { SV_BufferAddFormat(data, "sbs", packet->response.item[i].id, packet->response.item[i].count, packet->response.item[i].damage ); } } } break; case SVUpdateProgressBar: { SVPacketUpdateProgressBar* packet = (SVPacketUpdateProgressBar*) self->data; SV_BufferAddFormat(data, "bss", packet->response.id, packet->response.bar, packet->response.value ); } break; case SVTransaction: { SVPacketTransaction* packet = (SVPacketTransaction*) self->data; SV_BufferAddFormat(data, "bsB", packet->response.id, packet->response.action, packet->response.accepted ); } break; case SVCreativeInventoryAction: { SVPacketCreativeInventoryAction* packet = (SVPacketCreativeInventoryAction*) self->data; SV_BufferAddFormat(data, "ssss", packet->response.slot, packet->response.itemId, packet->response.quantity, packet->response.damage ); } break; case SVUpdateSign: { SVPacketUpdateSign* packet = (SVPacketUpdateSign*) self->data; SV_BufferAddFormat(data, "isiUUUU", packet->response.position.x, packet->response.position.y, packet->response.position.z, packet->response.first, packet->response.second, packet->response.third, packet->response.fourth ); } break; case SVItemData: { SVPacketItemData* packet = (SVPacketItemData*) self->data; SV_BufferAddFormat(data, "isiUUUU", packet->response.itemType, packet->response.itemId, packet->response.textLength ); CD_BufferAdd(data, (CDPointer) packet->response.text, packet->response.textLength * SVByteSize); } break; case SVIncrementStatistic: { SVPacketIncrementStatistic* packet = (SVPacketIncrementStatistic*) self->data; SV_BufferAddFormat(data, "ib", packet->response.id, packet->response.amount ); } break; case SVPlayerListItem: { SVPacketPlayerListItem* packet = (SVPacketPlayerListItem*) self->data; SV_BufferAddFormat(data, "Ubs", packet->response.playerName, packet->response.online, packet->response.ping ); } break; case SVDisconnect: { SVPacketDisconnect* packet = (SVPacketDisconnect*) self->data; SV_BufferAddString16(data, packet->response.reason); } break; default: { return NULL; }; } } break; } return data; }
26.876676
133
0.656259
327cb25e24ad0cd0505e4803477a525415445075
2,810
h
C
kernel/commands.h
JEJacobi/SSMOS
f803bb9712c52511e10dbf3753714df682135fc2
[ "Unlicense" ]
null
null
null
kernel/commands.h
JEJacobi/SSMOS
f803bb9712c52511e10dbf3753714df682135fc2
[ "Unlicense" ]
null
null
null
kernel/commands.h
JEJacobi/SSMOS
f803bb9712c52511e10dbf3753714df682135fc2
[ "Unlicense" ]
null
null
null
// Commands, definitions, and handlers for the terminal. #ifndef KERNEL_COMMANDS #define KERNEL_COMMANDS #include "string.h" struct command { char* name; // The name and calling string of the command. char* help; // The help string of the command. char* format; // The format for any parameters. int (*call)(char*); // The function pointer to the command. /* All commands return an int as an error status, and take whatever else was in the terminal as a char*. It's left up to the calling function to sort and handle these parameters. */ }; struct alias { string* alias; string* command; }; extern struct element* aliases; struct command* find_cmd(char* input); struct alias* find_alias(char* input); // COMMAND HANDLERS int help(char* params); // Display help strings and list functions. int history(char* params); // Display command history. int disk(char* params); // Switch current working disk or print information about connected drives. int list(char* params); // List files in a specified directory. int find(char* params); // Finds any files with the string indicated on the disk. int edit(char* params); // Basic ASCII text editor. int makedir(char* params); // Creates directories indicated. int copy(char* params); // Copies file(s) to the location indicated. int move(char* params); // Moves file(s) to the location indicated. int delete(char* params); // Delete a file. int view(char* params); // View a file in ASCII. int memview(char* params); // View the current memory at a certain location. int echo(char* params); // Echo a string onto a new line. int cls(char* params); // Clear the screen. int tcolor(char* params); // Sets the terminal's color and refreshes the screen. int alias(char* params); // Alias a string as a command. int cprompt(char* params); // Change the command prompt to what's entered. int cpuinfo(char* params); // Display available CPU information, features, and instruction sets. int syslog(char* params); // Displays the system log. int memory(char* params); // Displays operating system memory information. int reboot(char* params); // Reboot the computer. int shutdown(char* params); // Shut down the computer. int time(char* params); // Print the total uptime and the real time. int debug(char* params); // Triggers Bochs' magic breakpoint, totally useless running on an actual system. int about(char* params); // About SSMOS. int version(char* params); // Get the current version of SSMOS and maybe the release date. // COMMAND LIST extern struct command commands[]; extern int num_commands; #endif
40.724638
109
0.673665
681453b1fe29bfcce4a52f8f3cda1cf2ef215cf3
7,288
c
C
clang/test/Analysis/equality_tracking.c
LaudateCorpus1/llvm-project
ff2e0f0c1112558b3f30d8afec7c9882c33c79e3
[ "Apache-2.0" ]
null
null
null
clang/test/Analysis/equality_tracking.c
LaudateCorpus1/llvm-project
ff2e0f0c1112558b3f30d8afec7c9882c33c79e3
[ "Apache-2.0" ]
null
null
null
clang/test/Analysis/equality_tracking.c
LaudateCorpus1/llvm-project
ff2e0f0c1112558b3f30d8afec7c9882c33c79e3
[ "Apache-2.0" ]
null
null
null
// RUN: %clang_analyze_cc1 -verify %s \ // RUN: -analyzer-checker=core,debug.ExprInspection \ // RUN: -analyzer-config eagerly-assume=false #define NULL (void *)0 #define UCHAR_MAX (unsigned char)(~0U) #define CHAR_MAX (char)(UCHAR_MAX & (UCHAR_MAX >> 1)) #define CHAR_MIN (char)(UCHAR_MAX & ~(UCHAR_MAX >> 1)) void clang_analyzer_eval(int); void clang_analyzer_warnIfReached(void); int getInt(void); void zeroImpliesEquality(int a, int b) { clang_analyzer_eval((a - b) == 0); // expected-warning{{UNKNOWN}} if ((a - b) == 0) { clang_analyzer_eval(b != a); // expected-warning{{FALSE}} clang_analyzer_eval(b == a); // expected-warning{{TRUE}} clang_analyzer_eval(!(a != b)); // expected-warning{{TRUE}} clang_analyzer_eval(!(b == a)); // expected-warning{{FALSE}} return; } clang_analyzer_eval((a - b) == 0); // expected-warning{{FALSE}} clang_analyzer_eval(b == a); // expected-warning{{FALSE}} clang_analyzer_eval(b != a); // expected-warning{{TRUE}} } void zeroImpliesReversedEqual(int a, int b) { clang_analyzer_eval((b - a) == 0); // expected-warning{{UNKNOWN}} if ((b - a) == 0) { clang_analyzer_eval(b != a); // expected-warning{{FALSE}} clang_analyzer_eval(b == a); // expected-warning{{TRUE}} return; } clang_analyzer_eval((b - a) == 0); // expected-warning{{FALSE}} clang_analyzer_eval(b == a); // expected-warning{{FALSE}} clang_analyzer_eval(b != a); // expected-warning{{TRUE}} } void canonicalEqual(int a, int b) { clang_analyzer_eval(a == b); // expected-warning{{UNKNOWN}} if (a == b) { clang_analyzer_eval(b == a); // expected-warning{{TRUE}} return; } clang_analyzer_eval(a == b); // expected-warning{{FALSE}} clang_analyzer_eval(b == a); // expected-warning{{FALSE}} } void test(int a, int b, int c, int d) { if (a == b && c == d) { if (a == 0 && b == d) { clang_analyzer_eval(c == 0); // expected-warning{{TRUE}} } c = 10; if (b == d) { clang_analyzer_eval(c == 10); // expected-warning{{TRUE}} clang_analyzer_eval(d == 10); // expected-warning{{UNKNOWN}} // expected-warning@-1{{FALSE}} clang_analyzer_eval(b == a); // expected-warning{{TRUE}} clang_analyzer_eval(a == d); // expected-warning{{TRUE}} b = getInt(); clang_analyzer_eval(a == d); // expected-warning{{TRUE}} clang_analyzer_eval(a == b); // expected-warning{{UNKNOWN}} } } if (a != b && b == c) { if (c == 42) { clang_analyzer_eval(b == 42); // expected-warning{{TRUE}} clang_analyzer_eval(a != 42); // expected-warning{{TRUE}} } } } void testIntersection(int a, int b, int c) { if (a < 42 && b > 15 && c >= 25 && c <= 30) { if (a != b) return; clang_analyzer_eval(a > 15); // expected-warning{{TRUE}} clang_analyzer_eval(b < 42); // expected-warning{{TRUE}} clang_analyzer_eval(a <= 30); // expected-warning{{UNKNOWN}} if (c == b) { // For all equal symbols, we should track the minimal common range. // // Also, it should be noted that c is dead at this point, but the // constraint initially associated with c is still around. clang_analyzer_eval(a >= 25 && a <= 30); // expected-warning{{TRUE}} clang_analyzer_eval(b >= 25 && b <= 30); // expected-warning{{TRUE}} } } } void testPromotion(int a, char b) { if (b > 10) { if (a == b) { // FIXME: support transferring char ranges onto equal int symbols // when char is promoted to int clang_analyzer_eval(a > 10); // expected-warning{{UNKNOWN}} clang_analyzer_eval(a <= CHAR_MAX); // expected-warning{{UNKNOWN}} } } } void testPromotionOnlyTypes(int a, char b) { if (a == b) { // FIXME: support transferring char ranges onto equal int symbols // when char is promoted to int clang_analyzer_eval(a <= CHAR_MAX); // expected-warning{{UNKNOWN}} } } void testDowncast(int a, unsigned char b) { if (a <= -10) { if ((unsigned char)a == b) { // Even though ranges for a and b do not intersect, // ranges for (unsigned char)a and b do. clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}} } if (a == b) { // FIXME: This case on the other hand is different, it shouldn't be // reachable. However, the corrent symbolic information available // to the solver doesn't allow it to distinguish this expression // from the previous one. clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}} } } } void testPointers(int *a, int *b, int *c, int *d) { if (a == b && c == d) { if (a == NULL && b == d) { clang_analyzer_eval(c == NULL); // expected-warning{{TRUE}} } } if (a != b && b == c) { if (c == NULL) { clang_analyzer_eval(a != NULL); // expected-warning{{TRUE}} } } } void testDisequalitiesAfter(int a, int b, int c) { if (a >= 10 && b <= 42) { if (a == b && c == 15 && c != a) { clang_analyzer_eval(b != c); // expected-warning{{TRUE}} clang_analyzer_eval(a != 15); // expected-warning{{TRUE}} clang_analyzer_eval(b != 15); // expected-warning{{TRUE}} clang_analyzer_eval(b >= 10); // expected-warning{{TRUE}} clang_analyzer_eval(a <= 42); // expected-warning{{TRUE}} } } } void testDisequalitiesBefore(int a, int b, int c) { if (a >= 10 && b <= 42 && c == 15) { if (a == b && c != a) { clang_analyzer_eval(b != c); // expected-warning{{TRUE}} clang_analyzer_eval(a != 15); // expected-warning{{TRUE}} clang_analyzer_eval(b != 15); // expected-warning{{TRUE}} clang_analyzer_eval(b >= 10); // expected-warning{{TRUE}} clang_analyzer_eval(a <= 42); // expected-warning{{TRUE}} } } } void avoidInfeasibleConstraintsForClasses(int a, int b) { if (a >= 0 && a <= 10 && b >= 20 && b <= 50) { if ((b - a) == 0) { clang_analyzer_warnIfReached(); // no warning } if (a == b) { clang_analyzer_warnIfReached(); // no warning } if (a != b) { clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}} } else { clang_analyzer_warnIfReached(); // no warning } } } void avoidInfeasibleConstraintforGT(int a, int b) { int c = b - a; if (c <= 0) return; // c > 0 // b - a > 0 // b > a if (a != b) { clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}} return; } clang_analyzer_warnIfReached(); // no warning // a == b if (c < 0) ; } void avoidInfeasibleConstraintforLT(int a, int b) { int c = b - a; if (c >= 0) return; // c < 0 // b - a < 0 // b < a if (a != b) { clang_analyzer_warnIfReached(); // expected-warning{{REACHABLE}} return; } clang_analyzer_warnIfReached(); // no warning // a == b if (c < 0) ; } void implyDisequalityFromGT(int a, int b) { if (a > b) { clang_analyzer_eval(a == b); // expected-warning{{FALSE}} clang_analyzer_eval(a != b); // expected-warning{{TRUE}} } } void implyDisequalityFromLT(int a, int b) { if (a < b) { clang_analyzer_eval(a == b); // expected-warning{{FALSE}} clang_analyzer_eval(a != b); // expected-warning{{TRUE}} } }
30.881356
79
0.588639
65110ffc9b65b609c136dff7133d85084793cf22
415
h
C
ImageScaling/DownloadDialog.h
waitwalker/QtWidgetDemos
fe0ef951b9e058a93ada4b3399c4daa900694131
[ "MIT" ]
1
2021-09-03T08:52:55.000Z
2021-09-03T08:52:55.000Z
ImageScaling/DownloadDialog.h
waitwalker/QtWidgetDemos
fe0ef951b9e058a93ada4b3399c4daa900694131
[ "MIT" ]
null
null
null
ImageScaling/DownloadDialog.h
waitwalker/QtWidgetDemos
fe0ef951b9e058a93ada4b3399c4daa900694131
[ "MIT" ]
null
null
null
#ifndef DOWNLOADDIALOG_H #define DOWNLOADDIALOG_H #include <QDialog> namespace Ui { class DownloadDialog; } class DownloadDialog : public QDialog { Q_OBJECT public: explicit DownloadDialog(QWidget *parent = nullptr); ~DownloadDialog(); QList<QUrl> getUrls() const; signals: void getImageURLS(QList<QString> &imageUrls); private: Ui::DownloadDialog *ui; }; #endif // DOWNLOADDIALOG_H
14.821429
55
0.725301
45ab8dc713777a6c132b5163e8194c4164649a36
4,747
h
C
Frameworks/GameController.framework/_GCControllerManager.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
36
2016-04-20T04:19:04.000Z
2018-10-08T04:12:25.000Z
Frameworks/GameController.framework/_GCControllerManager.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
null
null
null
Frameworks/GameController.framework/_GCControllerManager.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/GameController.framework/GameController */ @interface _GCControllerManager : NSObject <GameControllerClientProtocol> { NSXPCConnection * _connection; NSMutableDictionary * _controllersByRegistryID; NSMutableDictionary * _controllersByUDID; NSObject<OS_dispatch_queue> * _controllersQueue; long long _currentMediaRemoteInputMode; NSThread * _hidInputThread; struct __CFRunLoop { } * _hidInputThreadRunLoop; struct __IOHIDManager { } * _hidManager; struct __IOHIDEventSystemClient { } * _hidSystemClient; NSObject<OS_dispatch_queue> * _hidSystemClientQueue; NSMutableArray * _hidThreadExecutionBlocks; struct __CFRunLoopSource { } * _hidThreadRunLoopSource; bool _idleTimerNeedsReset; NSTimer * _idleWatchTimer; bool _isAppInBackground; id /* block */ _logger; <GameControllerDaemon> * _remote; id /* block */ _requestConnectedHostsCallback; bool _shouldKeepRunning; unsigned int _usbAddedIterator; struct IONotificationPort { } * _usbNotify; unsigned int _usbRemovedIterator; } @property (nonatomic, retain) NSXPCConnection *connection; @property (nonatomic, readonly, retain) NSObject<OS_dispatch_queue> *controllersQueue; @property (readonly, copy) NSString *debugDescription; @property (readonly, copy) NSString *description; @property (readonly) unsigned long long hash; @property (nonatomic, readonly, retain) NSThread *hidInputThread; @property (nonatomic, readonly) struct __CFRunLoop { }*hidInputThreadRunLoop; @property (nonatomic) struct __IOHIDManager { }*hidManager; @property (nonatomic, readonly) NSMutableArray *hidThreadExecutionBlocks; @property (nonatomic, readonly) struct __CFRunLoopSource { }*hidThreadRunLoopSource; @property (nonatomic) bool idleTimerNeedsReset; @property (nonatomic, readonly) bool isAppInBackground; @property (nonatomic, copy) id /* block */ logger; @property (nonatomic, retain) <GameControllerDaemon> *remote; @property (readonly) Class superclass; - (void).cxx_destruct; - (void)CBApplicationDidBecomeActive; - (void)CBApplicationWillResignActive; - (void)addController:(id)arg1; - (void)addControllerWithServiceRef:(struct __IOHIDServiceClient { }*)arg1; - (void)async_HIDBlock:(id /* block */)arg1; - (id)connection; - (void)controller:(id)arg1 setValue:(float)arg2 forElement:(int)arg3; - (void)controllerWithUDID:(unsigned long long)arg1 setData:(id)arg2; - (void)controllerWithUDID:(unsigned long long)arg1 setValue0:(float)arg2 setValue1:(float)arg3 setValue2:(float)arg4 setValue3:(float)arg5 forElement:(int)arg6; - (void)controllerWithUDID:(unsigned long long)arg1 setValue:(float)arg2 forElement:(int)arg3; - (id)controllers; - (id)controllersQueue; - (void)dealloc; - (id)firstMicroGamepad; - (id)hidInputThread; - (struct __CFRunLoop { }*)hidInputThreadRunLoop; - (struct __IOHIDManager { }*)hidManager; - (id)hidThreadExecutionBlocks; - (struct __CFRunLoopSource { }*)hidThreadRunLoopSource; - (bool)idleTimerNeedsReset; - (id)init; - (bool)isAppInBackground; - (bool)isExistingController:(id)arg1; - (bool)isPhysicalB239:(id)arg1; - (void)launchHIDInputThread; - (id /* block */)logger; - (void)microControllerWithDigitizerX:(float)arg1 withY:(float)arg2 withTimeStamp:(unsigned long long)arg3 touchDown:(bool)arg4; - (void)microControllerWithUDID:(unsigned long long)arg1 setDigitizerX:(float)arg2 digitizerY:(float)arg3 withTimeStamp:(unsigned long long)arg4 touchDown:(bool)arg5; - (void)open; - (id)remote; - (void)removeController:(id)arg1; - (void)removeControllerWithServiceRef:(struct __IOHIDServiceClient { }*)arg1; - (void)replyConnectedHosts:(id)arg1; - (void)requestConnectedHostsWithHandler:(id /* block */)arg1; - (void)setConnection:(id)arg1; - (void)setHidManager:(struct __IOHIDManager { }*)arg1; - (void)setIdleTimerNeedsReset:(bool)arg1; - (void)setLogger:(id /* block */)arg1; - (void)setRemote:(id)arg1; - (void)startHIDDeviceMonitor; - (void)startHIDEventMonitor; - (void)startIdleWatchTimer; - (void)stopHIDDeviceMonitor; - (void)stopHIDEventMonitor; - (void)threadHIDInputOffMain:(id)arg1; - (void)threadHIDInputOnMain:(id)arg1; - (void)updateControllerWithEvent:(struct __IOHIDEvent { struct __CFRuntimeBase { unsigned long long x_1_1_1; unsigned char x_1_1_2[4]; unsigned int x_1_1_3; } x1; unsigned long long x2; unsigned long long x3; unsigned long long x4; unsigned int x5; char *x6; void *x7; void *x8; struct __CFArray {} *x9; struct __IOHIDEvent {} *x10; long long x11; long long x12; struct IOHIDEventData { unsigned int x_13_1_1; unsigned int x_13_1_2; unsigned int x_13_1_3; unsigned char x_13_1_4; unsigned char x_13_1_5[3]; } x13[0]; }*)arg1; - (void)updateIdleTimer:(id)arg1; @end
48.938144
526
0.771013
109de63248285a26c36e7dc39625ba88d724c4f2
8,596
h
C
fuse_core/include/fuse_core/autodiff_local_parameterization.h
congleetea/fuse
7a87a59915a213431434166c96d0705ba6aa00b2
[ "BSD-3-Clause" ]
null
null
null
fuse_core/include/fuse_core/autodiff_local_parameterization.h
congleetea/fuse
7a87a59915a213431434166c96d0705ba6aa00b2
[ "BSD-3-Clause" ]
null
null
null
fuse_core/include/fuse_core/autodiff_local_parameterization.h
congleetea/fuse
7a87a59915a213431434166c96d0705ba6aa00b2
[ "BSD-3-Clause" ]
2
2020-07-21T10:48:28.000Z
2021-10-18T10:44:23.000Z
/* * Software License Agreement (BSD License) * * Copyright (c) 2019, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FUSE_CORE_AUTODIFF_LOCAL_PARAMETERIZATION_H #define FUSE_CORE_AUTODIFF_LOCAL_PARAMETERIZATION_H #include <fuse_core/local_parameterization.h> #include <fuse_core/macros.h> #include <ceres/internal/autodiff.h> #include <memory> namespace fuse_core { /** * @brief Create a local parameterization with the Jacobians computed via automatic differentiation. * * To get an auto differentiated local parameterization, you must define two classes with a templated operator() * (a.k.a. a functor). * * The first functor should compute: * * Plus(x, delta) -> x_plus_delta * * And the second functor should compute the inverse operation: * * Minus(x1, x2) -> delta * * Minus() should be defined such that if Plus(x1, delta) -> x2, then Minus(x1, x2) -> delta * * The autodiff framework substitutes appropriate "Jet" objects for the template parameter T in order to compute * the derivative when necessary, but this is hidden, and you should write the function as if T were a scalar type * (e.g. a double-precision floating point number). * * Additionally the GlobalSize and LocalSize must be specified as template parameters. * - GlobalSize is the size of the variables x1 and x2. If this is a quaternion, the GloblaSize would be 4. * - LocalSize is the size of delta, and may be different from GlobalSize. For quaternions, there are only 3 degrees * of freedom, so the LocalSize is 3. * * For more information on local parameterizations, see fuse_core::LocalParameterization */ template <typename PlusFunctor, typename MinusFunctor, int kGlobalSize, int kLocalSize> class AutoDiffLocalParameterization : public LocalParameterization { public: SMART_PTR_DEFINITIONS(AutoDiffLocalParameterization<PlusFunctor, MinusFunctor, kGlobalSize, kLocalSize>); /** * @brief Constructs new PlusFunctor and MinusFunctor instances */ AutoDiffLocalParameterization(); /** * @brief Takes ownership of the provided PlusFunctor and MinusFunctor instances */ AutoDiffLocalParameterization(PlusFunctor* plus_functor, MinusFunctor* minus_functor); /** * @brief Generalization of the addition operation, implemented by the provided PlusFunctor * * @param[in] x The starting variable value, of size \p GlobalSize() * @param[in] delta The variable increment to apply, of size \p LocalSize() * @param[out] x_plus_delta The final variable value, of size \p GlobalSize() * @return True if successful, false otherwise */ bool Plus( const double* x, const double* delta, double* x_plus_delta) const override; /** * @brief The Jacobian of Plus(x, delta) w.r.t delta at delta = 0, computed using automatic differentiation * * @param[in] x The value used to evaluate the Jacobian, of size GloblaSize() * @param[out] jacobian The Jacobian in row-major order, of size \p GlobalSize() x \p LocalSize() * @return True is successful, false otherwise */ bool ComputeJacobian( const double* x, double* jacobian) const override; /** * @brief Generalization of the subtraction operation, implemented by the provided MinusFunctor * * @param[in] x1 The value of the first variable, of size \p GlobalSize() * @param[in] x2 The value of the second variable, of size \p GlobalSize() * @param[out] delta The difference between the second variable and the first, of size \p LocalSize() * @return True if successful, false otherwise */ bool Minus( const double* x1, const double* x2, double* delta) const override; /** * @brief The Jacobian of Minus(x1, x2) w.r.t x2 evaluated at x1 = x2 = x, computed using automatic differentiation * @param[in] x The value used to evaluate the Jacobian, of size \p GlobalSize() * @param[out] jacobian The Jacobian in row-major order, of size \p LocalSize() x \p GlobalSize() * @return True is successful, false otherwise */ bool ComputeMinusJacobian( const double* x, double* jacobian) const override; /** * @brief The size of the variable parameterization in the nonlinear manifold */ int GlobalSize() const override { return kGlobalSize; } /** * @brief The size of a delta vector in the linear tangent space to the nonlinear manifold */ int LocalSize() const override { return kLocalSize; } private: std::unique_ptr<PlusFunctor> plus_functor_; std::unique_ptr<MinusFunctor> minus_functor_; }; template <typename PlusFunctor, typename MinusFunctor, int kGlobalSize, int kLocalSize> AutoDiffLocalParameterization<PlusFunctor, MinusFunctor, kGlobalSize, kLocalSize>::AutoDiffLocalParameterization() : plus_functor_(new PlusFunctor()), minus_functor_(new MinusFunctor()) { } template <typename PlusFunctor, typename MinusFunctor, int kGlobalSize, int kLocalSize> AutoDiffLocalParameterization<PlusFunctor, MinusFunctor, kGlobalSize, kLocalSize>::AutoDiffLocalParameterization( PlusFunctor* plus_functor, MinusFunctor* minus_functor) : plus_functor_(plus_functor), minus_functor_(minus_functor) { } template <typename PlusFunctor, typename MinusFunctor, int kGlobalSize, int kLocalSize> bool AutoDiffLocalParameterization<PlusFunctor, MinusFunctor, kGlobalSize, kLocalSize>::Plus( const double* x, const double* delta, double* x_plus_delta) const { return (*plus_functor_)(x, delta, x_plus_delta); } template <typename PlusFunctor, typename MinusFunctor, int kGlobalSize, int kLocalSize> bool AutoDiffLocalParameterization<PlusFunctor, MinusFunctor, kGlobalSize, kLocalSize>::ComputeJacobian( const double* x, double* jacobian) const { double zero_delta[kLocalSize] = {}; // zero-initialize double x_plus_delta[kGlobalSize]; const double* parameter_ptrs[2] = {x, zero_delta}; double* jacobian_ptrs[2] = {NULL, jacobian}; return ceres::internal::AutoDiff<PlusFunctor, double, kGlobalSize, kLocalSize> ::Differentiate(*plus_functor_, parameter_ptrs, kGlobalSize, x_plus_delta, jacobian_ptrs); } template <typename PlusFunctor, typename MinusFunctor, int kGlobalSize, int kLocalSize> bool AutoDiffLocalParameterization<PlusFunctor, MinusFunctor, kGlobalSize, kLocalSize>::Minus( const double* x1, const double* x2, double* delta) const { return (*minus_functor_)(x1, x2, delta); } template <typename PlusFunctor, typename MinusFunctor, int kGlobalSize, int kLocalSize> bool AutoDiffLocalParameterization<PlusFunctor, MinusFunctor, kGlobalSize, kLocalSize>::ComputeMinusJacobian( const double* x, double* jacobian) const { double delta[kLocalSize] = {}; // zero-initialize const double* parameter_ptrs[2] = {x, x}; double* jacobian_ptrs[2] = {NULL, jacobian}; return ceres::internal::AutoDiff<MinusFunctor, double, kGlobalSize, kGlobalSize> ::Differentiate(*minus_functor_, parameter_ptrs, kLocalSize, delta, jacobian_ptrs); } } // namespace fuse_core #endif // FUSE_CORE_AUTODIFF_LOCAL_PARAMETERIZATION_H
39.612903
117
0.746277
10d3e0915327d349b06862b56fb6f0ee4037da88
10,766
h
C
tools/layer.h
codeplaysoftware/SYCL-DNN
db554c9592f86c58adddc01df101da591a61de51
[ "Apache-2.0" ]
85
2018-06-04T08:07:20.000Z
2022-03-30T15:53:46.000Z
tools/layer.h
codeplaysoftware/SYCL-DNN
db554c9592f86c58adddc01df101da591a61de51
[ "Apache-2.0" ]
8
2019-07-19T11:10:43.000Z
2021-02-05T10:18:49.000Z
tools/layer.h
codeplaysoftware/SYCL-DNN
db554c9592f86c58adddc01df101da591a61de51
[ "Apache-2.0" ]
19
2018-12-28T12:09:22.000Z
2022-01-08T02:55:14.000Z
/* * Copyright Codeplay Software Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "sycldnn/conv2d/launch.h" #include "sycldnn/conv2d/selector/default_selector.h" #include "sycldnn/conv2d/workspace_size.h" #include "sycldnn/helpers/padding.h" #include "sycldnn/helpers/ratio.h" #include "sycldnn/pointwise/launch.h" #include "sycldnn/pointwise/params.h" #include "sycldnn/pooling/launch.h" #include "sycldnn/binaryop/launch.h" #include "sycldnn/binaryop/operators.h" #include "sycldnn/batchnorm/launch.h" #include "sycldnn/batchnorm/sizes.h" #include "sycldnn/matmul/launch.h" #include "sycldnn/matmul/params.h" #include "sycldnn/softmax/launch.h" #include "sycldnn/softmax/sizes.h" #include "sycldnn/padding_mode.h" #include "sycldnn/status.h" #include <CL/sycl.hpp> namespace sycldnn { // Base class of all layer types to present unified interface and construction template <typename DType, typename Backend> struct Layer { using DeviceMem = typename Backend::template pointer_type<DType>; Backend& backend_; Layer(Backend& b) : backend_(b) {} virtual ~Layer() = default; virtual DeviceMem get_output() = 0; virtual size_t get_output_size() const = 0; virtual sycldnn::SNNStatus run() = 0; }; template <typename DType, typename Backend> struct ConvolutionLayer : Layer<DType, Backend> { using DeviceMem = typename Backend::template pointer_type<DType>; sycldnn::conv2d::Conv2DParams params_; sycldnn::conv2d::ConvSizes sizes_; DeviceMem input_; DeviceMem filter_; DeviceMem output_; DeviceMem workspace_; size_t workspace_size_; sycldnn::conv2d::Selector& selector_; // Sets parameters and copies data into filter buffer ConvolutionLayer(sycldnn::conv2d::Conv2DParams const& params, DeviceMem const input, DeviceMem const weights, DeviceMem output, DeviceMem workspace, size_t workspace_size, Backend& b, sycldnn::conv2d::Selector& selector) : Layer<DType, Backend>(b), params_{params}, sizes_{sycldnn::conv2d::get_sizes<sycldnn::conv2d::conv_type::Forward>( params_)}, input_{input}, filter_{weights}, output_{output}, workspace_{workspace}, workspace_size_{workspace_size}, selector_{selector} {} DeviceMem get_output() override { return output_; } size_t get_output_size() const override { return sizes_.output_size; } sycldnn::SNNStatus run() override { return sycldnn::conv2d::launch<DType, sycldnn::conv2d::conv_type::Forward>( input_, filter_, output_, params_, selector_, this->backend_, workspace_, workspace_size_); } }; template <typename DType, typename Backend> struct BiasAddLayer : Layer<DType, Backend> { using DeviceMem = typename Backend::template pointer_type<DType>; sycldnn::binaryop::BinaryParams params_; DeviceMem input_; DeviceMem biases_; DeviceMem output_; BiasAddLayer(sycldnn::binaryop::BinaryParams const& params, DeviceMem const input, DeviceMem const bias, DeviceMem output, Backend& b) : Layer<DType, Backend>(b), params_{params}, input_{input}, biases_{bias}, output_{output} {} DeviceMem get_output() override { return output_; } size_t get_output_size() const override { return params_.lhs_items; } sycldnn::SNNStatus run() override { return sycldnn::binaryop::launch<DType, sycldnn::binaryop::Add>( input_, biases_, output_, params_, this->backend_); } }; template <typename DType, typename Backend, typename Operation> struct BatchNormLayer; template <typename DType, typename Backend> struct BatchNormLayer<DType, Backend, sycldnn::batchnorm::Training> : Layer<DType, Backend> { using DeviceMem = typename Backend::template pointer_type<DType>; sycldnn::batchnorm::BatchNormParams params_; sycldnn::batchnorm::BatchNormSizes sizes_; DeviceMem input_; DeviceMem beta_; DeviceMem gamma_; DeviceMem mean_; DeviceMem variance_; DeviceMem output_; BatchNormLayer(sycldnn::batchnorm::BatchNormParams const& params, DeviceMem const input, DeviceMem const beta, DeviceMem const gamma, DeviceMem mean, DeviceMem variance, DeviceMem output, Backend& b) : Layer<DType, Backend>(b), params_{params}, sizes_{sycldnn::batchnorm::get_sizes(params)}, input_{input}, beta_{beta}, gamma_{gamma}, mean_{mean}, variance_{variance}, output_{output} {} DeviceMem get_output() override { return output_; } size_t get_output_size() const override { return sizes_.output_size; } sycldnn::SNNStatus run() override { return sycldnn::batchnorm::launch<DType, Backend, sycldnn::batchnorm::Training>( input_, beta_, gamma_, mean_, variance_, output_, params_, this->backend_); } }; template <typename DType, typename Backend> struct BatchNormLayer<DType, Backend, sycldnn::batchnorm::Inference> : Layer<DType, Backend> { using DeviceMem = typename Backend::template pointer_type<DType>; sycldnn::batchnorm::BatchNormParams params_; sycldnn::batchnorm::BatchNormSizes sizes_; DeviceMem input_; DeviceMem beta_; DeviceMem gamma_; DeviceMem mean_; DeviceMem variance_; DeviceMem output_; BatchNormLayer(sycldnn::batchnorm::BatchNormParams const& params, DeviceMem const input, DeviceMem const beta, DeviceMem const gamma, DeviceMem const mean, DeviceMem const variance, DeviceMem output, Backend& b) : Layer<DType, Backend>(b), params_{params}, sizes_{sycldnn::batchnorm::get_sizes(params)}, input_{input}, beta_{beta}, gamma_{gamma}, mean_{mean}, variance_{variance}, output_{output} {} DeviceMem get_output() override { return output_; } size_t get_output_size() const override { return sizes_.output_size; } sycldnn::SNNStatus run() override { return sycldnn::batchnorm::launch<DType, Backend, sycldnn::batchnorm::Inference>( input_, beta_, gamma_, mean_, variance_, output_, params_, this->backend_); } }; template <typename DType, typename Backend, template <typename> class ActivationType> struct ActivationLayer : Layer<DType, Backend> { using DeviceMem = typename Backend::template pointer_type<DType>; sycldnn::pointwise::PointwiseParams params_; DeviceMem input_; DeviceMem output_; ActivationLayer(sycldnn::pointwise::PointwiseParams const& params, DeviceMem const input, DeviceMem output, Backend& b) : Layer<DType, Backend>(b), params_{params}, input_{input}, output_{output} {} DeviceMem get_output() override { return output_; } size_t get_output_size() const override { return params_.size; } sycldnn::SNNStatus run() override { return sycldnn::pointwise::launch<DType, ActivationType, sycldnn::pointwise::Forward>( input_, output_, params_.size, this->backend_); } }; template <typename DType, typename Backend, template <typename> class PoolingType> struct PoolingLayer : Layer<DType, Backend> { using DeviceMem = typename Backend::template pointer_type<DType>; sycldnn::pooling::PoolingParams params_; sycldnn::pooling::PoolingSizes sizes_; DeviceMem input_; DeviceMem output_; PoolingLayer(sycldnn::pooling::PoolingParams const& params, DeviceMem const input, DeviceMem output, Backend& b) : Layer<DType, Backend>(b), params_{params}, sizes_{sycldnn::pooling::get_sizes<sycldnn::pooling::Forward>(params_)}, input_{input}, output_{output} {} DeviceMem get_output() override { return output_; } size_t get_output_size() const override { return sizes_.output_size; } sycldnn::SNNStatus run() override { return sycldnn::pooling::launch<DType, PoolingType, sycldnn::pooling::Forward>( input_, output_, params_, this->backend_); } }; template <typename DType, typename Backend> struct FCLayer : Layer<DType, Backend> { using DeviceMem = typename Backend::template pointer_type<DType>; sycldnn::matmul::MatmulParams params_; DeviceMem input_; DeviceMem weights_; DeviceMem output_; FCLayer(sycldnn::matmul::MatmulParams const& p, DeviceMem const input, DeviceMem const weights, DeviceMem output, Backend& b) : Layer<DType, Backend>(b), params_(p), input_{input}, weights_{weights}, output_{output} {} DeviceMem get_output() override { return output_; } size_t get_output_size() const override { return params_.n; } sycldnn::SNNStatus run() override { using ConstPointer = typename Backend::template pointer_type<DType const>; return {this->backend_.template matmul<false, false>( ConstPointer{input_}, ConstPointer{weights_}, output_, params_.beta, params_.m, params_.k, params_.n), sycldnn::StatusCode::OK}; } }; template <typename DType, typename Backend> struct SoftmaxLayer : Layer<DType, Backend> { using DeviceMem = typename Backend::template pointer_type<DType>; sycldnn::softmax::SoftmaxParams params_; sycldnn::softmax::SoftmaxSizes sizes_; DeviceMem input_; DeviceMem workspace_; DeviceMem output_; SoftmaxLayer(sycldnn::softmax::SoftmaxParams const& params, DeviceMem const input, DeviceMem workspace, DeviceMem output, Backend& b) : Layer<DType, Backend>(b), params_{params}, sizes_{sycldnn::softmax::get_sizes(params)}, input_{input}, workspace_{workspace}, output_{output} {} DeviceMem get_output() override { return output_; } size_t get_output_size() const override { return sizes_.output_size; } sycldnn::SNNStatus run() override { return sycldnn::softmax::launch_forward<DType, sycldnn::softmax::Softmax, Backend>( input_, workspace_, output_, params_, this->backend_); } }; } // namespace sycldnn
34.50641
80
0.688371
a28272d5145d42fdad4cc9408ee4b98bb53b4331
4,778
c
C
libloragw/src/sx125x_spi.c
bangdracaena/lora_gateway
56579cb3242d316c57249271214400d283d65aab
[ "MIT" ]
null
null
null
libloragw/src/sx125x_spi.c
bangdracaena/lora_gateway
56579cb3242d316c57249271214400d283d65aab
[ "MIT" ]
null
null
null
libloragw/src/sx125x_spi.c
bangdracaena/lora_gateway
56579cb3242d316c57249271214400d283d65aab
[ "MIT" ]
null
null
null
/* / _____) _ | | ( (____ _____ ____ _| |_ _____ ____| |__ \____ \| ___ | (_ _) ___ |/ ___) _ \ _____) ) ____| | | || |_| ____( (___| | | | (______/|_____)_|_|_| \__)_____)\____)_| |_| (C)2019 Semtech Description: Functions used to handle LoRa concentrator SX1255/SX1257 radios. License: Revised BSD License, see LICENSE.TXT file include in the project */ /* -------------------------------------------------------------------------- */ /* --- DEPENDANCIES --------------------------------------------------------- */ #include <stdint.h> /* C99 types */ #include <stdbool.h> /* bool type */ #include <stdio.h> /* printf fprintf */ #include <string.h> /* memset */ #include <sys/ioctl.h> #include <linux/spi/spidev.h> #include "sx125x_spi.h" #include "loragw_spi.h" /* -------------------------------------------------------------------------- */ /* --- PRIVATE MACROS ------------------------------------------------------- */ #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) #if DEBUG_RAD == 1 #define DEBUG_MSG(str) fprintf(stdout, str) #define DEBUG_PRINTF(fmt, args...) fprintf(stdout,"%s:%d: "fmt, __FUNCTION__, __LINE__, args) #define CHECK_NULL(a) if(a==NULL){fprintf(stderr,"%s:%d: ERROR: NULL POINTER AS ARGUMENT\n", __FUNCTION__, __LINE__);return LGW_SPI_ERROR;} #else #define DEBUG_MSG(str) #define DEBUG_PRINTF(fmt, args...) #define CHECK_NULL(a) if(a==NULL){return LGW_SPI_ERROR;} #endif /* -------------------------------------------------------------------------- */ /* --- PRIVATE TYPES -------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ /* --- PRIVATE CONSTANTS ---------------------------------------------------- */ #define READ_ACCESS 0x00 #define WRITE_ACCESS 0x80 /* -------------------------------------------------------------------------- */ /* --- PRIVATE VARIABLES ---------------------------------------------------- */ /* -------------------------------------------------------------------------- */ /* --- PRIVATE FUNCTIONS ---------------------------------------------------- */ /* -------------------------------------------------------------------------- */ /* --- PUBLIC FUNCTIONS DEFINITION ------------------------------------------ */ /* Simple read */ int sx125x_spi_r(void *com_target, uint8_t spi_mux_target, uint8_t address, uint8_t *data) { int com_device; uint8_t out_buf[3]; uint8_t command_size; uint8_t in_buf[ARRAY_SIZE(out_buf)]; struct spi_ioc_transfer k; int a; /* check input variables */ CHECK_NULL(com_target); CHECK_NULL(data); com_device = *(int *)com_target; /* prepare frame to be sent */ out_buf[0] = spi_mux_target; out_buf[1] = READ_ACCESS | (address & 0x7F); out_buf[2] = 0x00; command_size = 3; /* I/O transaction */ memset(&k, 0, sizeof(k)); /* clear k */ k.tx_buf = (unsigned long) out_buf; k.rx_buf = (unsigned long) in_buf; k.len = command_size; k.cs_change = 0; a = ioctl(com_device, SPI_IOC_MESSAGE(1), &k); /* determine return code */ if (a != (int)k.len) { DEBUG_MSG("ERROR: SPI READ FAILURE\n"); return LGW_SPI_ERROR; } else { //DEBUG_MSG("Note: SPI read success\n"); *data = in_buf[command_size - 1]; return LGW_SPI_SUCCESS; } } /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ int sx125x_spi_w(void *spi_target, uint8_t spi_mux_target, uint8_t address, uint8_t data) { int spi_device; uint8_t out_buf[3]; uint8_t command_size; struct spi_ioc_transfer k; int a; /* check input variables */ CHECK_NULL(spi_target); spi_device = *(int *)spi_target; /* must check that spi_target is not null beforehand */ /* prepare frame to be sent */ out_buf[0] = spi_mux_target; out_buf[1] = WRITE_ACCESS | (address & 0x7F); out_buf[2] = data; command_size = 3; /* I/O transaction */ memset(&k, 0, sizeof(k)); /* clear k */ k.tx_buf = (unsigned long) out_buf; k.len = command_size; k.speed_hz = SPI_SPEED; k.cs_change = 0; k.bits_per_word = 8; a = ioctl(spi_device, SPI_IOC_MESSAGE(1), &k); /* determine return code */ if (a != (int)k.len) { DEBUG_MSG("ERROR: SPI WRITE FAILURE\n"); return LGW_SPI_ERROR; } else { //DEBUG_MSG("Note: SPI write success\n"); return LGW_SPI_SUCCESS; } } /* --- EOF ------------------------------------------------------------------ */
33.886525
158
0.458769
a2d24b10edab393df112e4d0b3108203e7c885f1
2,561
h
C
cocos2d-x-3.15.1/external/spidermonkey/include/win32/js/Vector.h
ibubue/BPUIKitAppIntegrateCocos2dx
6410770b86367f0a71555dd47f8c2e9bf5f0ab99
[ "MIT" ]
2,494
2015-02-11T04:34:13.000Z
2022-03-31T14:21:47.000Z
frameworks/cocos2d-x/external/spidermonkey/include/wp_8.1/js/Vector.h
bunny1985/literaki
dc6b00da3923f4aac82dc20b422a50ca87045a84
[ "MIT" ]
685
2015-02-11T17:14:26.000Z
2021-04-13T09:58:39.000Z
frameworks/cocos2d-x/external/spidermonkey/include/wp_8.1/js/Vector.h
bunny1985/literaki
dc6b00da3923f4aac82dc20b422a50ca87045a84
[ "MIT" ]
598
2015-01-02T02:38:13.000Z
2022-03-09T03:31:37.000Z
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * vim: set ts=8 sts=4 et sw=4 tw=99: * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef js_Vector_h #define js_Vector_h #include "mozilla/Vector.h" /* Silence dire "bugs in previous versions of MSVC have been fixed" warnings */ #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4345) #endif namespace js { class TempAllocPolicy; // If we had C++11 template aliases, we could just use this: // // template <typename T, // size_t MinInlineCapacity = 0, // class AllocPolicy = TempAllocPolicy> // using Vector = mozilla::Vector<T, MinInlineCapacity, AllocPolicy>; // // ...and get rid of all the CRTP madness in mozilla::Vector(Base). But we // can't because compiler support's not up to snuff. (Template aliases are in // gcc 4.7 and clang 3.0 and are expected to be in MSVC 2013.) Instead, have a // completely separate class inheriting from mozilla::Vector, and throw CRTP at // the problem til things work. // // This workaround presents a couple issues. First, because js::Vector is a // distinct type from mozilla::Vector, overload resolution, method calls, etc. // are affected. *Hopefully* this won't be too bad in practice. (A bunch of // places had to be fixed when mozilla::Vector was introduced, but it wasn't a // crazy number.) Second, mozilla::Vector's interface has to be made subclass- // ready via CRTP -- or rather, via mozilla::VectorBase, which basically no one // should use. :-) Third, we have to redefine the constructors and the non- // inherited operators. Blech. Happily there aren't too many of these, so it // isn't the end of the world. template <typename T, size_t MinInlineCapacity = 0, class AllocPolicy = TempAllocPolicy> class Vector : public mozilla::VectorBase<T, MinInlineCapacity, AllocPolicy, Vector<T, MinInlineCapacity, AllocPolicy> > { typedef typename mozilla::VectorBase<T, MinInlineCapacity, AllocPolicy, Vector> Base; public: explicit Vector(AllocPolicy alloc = AllocPolicy()) : Base(alloc) {} Vector(Vector &&vec) : Base(mozilla::Move(vec)) {} Vector &operator=(Vector &&vec) { return Base::operator=(mozilla::Move(vec)); } }; } // namespace js #endif /* js_Vector_h */
38.223881
89
0.675908
2ec98f2aa5045f54d7827676feaaeebdd173fd71
1,094
c
C
libft/ft_strcat.c
Eduard953/so_long
51a2af76e44dcbd7d3b95e2b20dfbf8109803ad8
[ "Unlicense" ]
null
null
null
libft/ft_strcat.c
Eduard953/so_long
51a2af76e44dcbd7d3b95e2b20dfbf8109803ad8
[ "Unlicense" ]
null
null
null
libft/ft_strcat.c
Eduard953/so_long
51a2af76e44dcbd7d3b95e2b20dfbf8109803ad8
[ "Unlicense" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strcat.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ebeiline <ebeiline@student.42wolfsburg. +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/05/22 18:59:45 by ebeiline #+# #+# */ /* Updated: 2021/05/29 16:54:56 by ebeiline ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" char *strcat(char *dest, const char *src) { int i; i = 0; while (dest[i] != '\0') i++; while (*src) { dest[i] = *src; src++; i++; } dest[i] = '\0'; return (dest); }
35.290323
80
0.189214
2c07580afabdd53c56c102b6ba2e54ec36ce03e3
152
c
C
src/AtmelStudio_MakeFileSample/Utility.c
vincoss/Avr-Samples
2ac14a0c857b8634d6330d2bcbc31db38b69bfef
[ "Apache-2.0" ]
null
null
null
src/AtmelStudio_MakeFileSample/Utility.c
vincoss/Avr-Samples
2ac14a0c857b8634d6330d2bcbc31db38b69bfef
[ "Apache-2.0" ]
null
null
null
src/AtmelStudio_MakeFileSample/Utility.c
vincoss/Avr-Samples
2ac14a0c857b8634d6330d2bcbc31db38b69bfef
[ "Apache-2.0" ]
null
null
null
/* * Utility.c * * Created: 27/01/2018 9:43:48 PM * Author : Ferdinand Lukasak */ #include "Utility.h" int Utility_GetSamplePin(void) { return 5; }
10.857143
32
0.664474
4e4b87153d124814fb813863a064520351478599
2,145
h
C
include/LuaGlue/LuaGlueConstant.h
moneymanagerex/LuaGlue
ccffa36799596cc2e9a179fe18d2bf6ce07ff09a
[ "Zlib" ]
null
null
null
include/LuaGlue/LuaGlueConstant.h
moneymanagerex/LuaGlue
ccffa36799596cc2e9a179fe18d2bf6ce07ff09a
[ "Zlib" ]
1
2021-11-28T09:30:12.000Z
2021-11-28T09:30:12.000Z
include/LuaGlue/LuaGlueConstant.h
moneymanagerex/LuaGlue
ccffa36799596cc2e9a179fe18d2bf6ce07ff09a
[ "Zlib" ]
3
2017-01-01T14:58:11.000Z
2021-11-27T15:55:57.000Z
#ifndef LUAGLUE_CONSTANT_H_GUARD #define LUAGLUE_CONSTANT_H_GUARD #include <string> #include <stdexcept> #include <lua.hpp> #include "LuaGlue/LuaGlueBase.h" class LuaGlueConstant { public: enum { CTYPE_INT = 1, CTYPE_NUM, CTYPE_STR }; LuaGlueConstant(const LuaGlueConstant &c) : name_(c.name_), type_(c.type_) { switch(type_) { case CTYPE_INT: int_value_ = c.int_value_; break; case CTYPE_NUM: num_value_ = c.num_value_; break; case CTYPE_STR: str_value_ = new std::string(c.str_value_->c_str()); break; default: break; } } LuaGlueConstant(const std::string &n, int v) : name_(n), int_value_(v), type_(CTYPE_INT) { } LuaGlueConstant(const std::string &n, double v) : name_(n), num_value_(v), type_(CTYPE_NUM) { } LuaGlueConstant(const std::string &n, const std::string &v) : name_(n), str_value_(new std::string(v)), type_(CTYPE_STR) { } ~LuaGlueConstant() { if(type_ == CTYPE_STR) delete str_value_; } const int &intValue() const { if(type_ == CTYPE_INT) return int_value_; else throw std::runtime_error("invalid Constant type (int)"); } const double &numValue() const { if(type_ == CTYPE_NUM) return num_value_; else throw std::runtime_error("invalid Constant type (num)"); } const std::string &strValue() const { if(type_ == CTYPE_STR) return *str_value_; else throw std::runtime_error("invalid Constant type (str)"); } const std::string &name() const { return name_; } bool glue(LuaGlueBase *luaGlue) { switch(type_) { case CTYPE_INT: lua_pushinteger(luaGlue->state(), int_value_); break; case CTYPE_NUM: lua_pushnumber(luaGlue->state(), num_value_); break; case CTYPE_STR: lua_pushstring(luaGlue->state(), str_value_->c_str()); break; default: return false; } lua_setfield(luaGlue->state(), -2, name_.c_str()); return true; } private: std::string name_; union { int int_value_; double num_value_; std::string *str_value_; }; int type_; }; #endif /* LUAGLUE_CONSTANT_H_GUARD */
23.571429
146
0.648485
bdd756f4da45606285485ec2099405f3f54211dd
3,986
c
C
src/input.c
TheShoutingParrot/C-Standards
bb55fffe3d3900627c2d24c37503b07510663931
[ "MIT" ]
null
null
null
src/input.c
TheShoutingParrot/C-Standards
bb55fffe3d3900627c2d24c37503b07510663931
[ "MIT" ]
null
null
null
src/input.c
TheShoutingParrot/C-Standards
bb55fffe3d3900627c2d24c37503b07510663931
[ "MIT" ]
null
null
null
//=============================================================================================// // FILENAME : input.c // // DESCRIPTION : // This file defines input handling. As of now, it only supports mouse and keyboard input. // Controller support may come at a future date. // // NOTES : // 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. // // AUTHOR : Joshua Crotts START DATE : 18 Jun 2020 // //=============================================================================================// #include "../include/input.h" static int16_t previous_frame_key = -1; static inline void Stds_UpdateMouseState( void ); static inline void Stds_KeyPressed( const SDL_KeyboardEvent * ); static inline void Stds_KeyReleased( const SDL_KeyboardEvent * ); static inline void Stds_MousePressed( const SDL_MouseButtonEvent * ); static inline void Stds_MouseReleased( const SDL_MouseButtonEvent * ); static inline void Stds_MouseMoved( const SDL_MouseMotionEvent * ); /** * Starts the SDL event loop. * * @param void. * * @return void. */ void Stds_ProcessInput( void ) { SDL_Event event; while ( SDL_PollEvent( &event ) ) { Stds_UpdateMouseState(); switch ( event.type ) { case SDL_QUIT: exit( EXIT_SUCCESS ); break; case SDL_KEYDOWN: Stds_KeyPressed( &event.key ); break; case SDL_KEYUP: Stds_KeyReleased( &event.key ); break; case SDL_MOUSEBUTTONDOWN: Stds_MousePressed( &event.button ); break; case SDL_MOUSEBUTTONUP: Stds_MouseReleased( &event.button ); break; case SDL_MOUSEWHEEL: app.mouse.wheel = event.wheel.y; break; case SDL_MOUSEMOTION: Stds_MouseMoved( &event.motion ); default: break; } } } /** * * * @param void. * * @return void. */ static inline void Stds_UpdateMouseState( void ) { SDL_GetMouseState( &app.mouse.x, &app.mouse.y ); app.mouse.is_moving = false; } /** * * * @param * * @return void. */ static inline void Stds_KeyPressed( const SDL_KeyboardEvent *event ) { if ( event->repeat == 0 && event->keysym.scancode < MAX_KEYBOARD_KEYS ) { app.keyboard[event->keysym.scancode] = 1; } } /** * * * @param * * @return void. */ static inline void Stds_KeyReleased( const SDL_KeyboardEvent *event ) { if ( event->repeat == 0 && event->keysym.scancode < MAX_KEYBOARD_KEYS ) { app.keyboard[event->keysym.scancode] = 0; } } /** * * * @param * * @return void. */ static inline void Stds_MousePressed( const SDL_MouseButtonEvent *event ) { app.mouse.button[event->button] = 1; } /** * */ static inline void Stds_MouseReleased( const SDL_MouseButtonEvent *event ) { app.mouse.button[event->button] = 0; } /** * */ static inline void Stds_MouseMoved( const SDL_MouseMotionEvent *e ) { app.mouse.is_moving = true; }
26.573333
97
0.637481
0818cf2e5ce7401bcc7f9ccdf6f411d3acd990bb
514
h
C
zircon/system/uapp/thermal-cli/thermal-cli.h
zhangpf/fuchsia-rs
903568f28ddf45f09157ead36d61b50322c9cf49
[ "BSD-3-Clause" ]
null
null
null
zircon/system/uapp/thermal-cli/thermal-cli.h
zhangpf/fuchsia-rs
903568f28ddf45f09157ead36d61b50322c9cf49
[ "BSD-3-Clause" ]
5
2020-09-06T09:02:06.000Z
2022-03-02T04:44:22.000Z
zircon/system/uapp/thermal-cli/thermal-cli.h
ZVNexus/fuchsia
c5610ad15208208c98693618a79c705af935270c
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #pragma once #include <lib/zx/channel.h> #include <memory> class ThermalCli { public: ThermalCli(zx::channel channel) : channel_(std::move(channel)) {} zx_status_t PrintTemperature(); zx_status_t FanLevelCommand(const char* value); int FrequencyCommand(uint32_t cluster, const char* value); private: zx::channel channel_; };
24.47619
73
0.729572
4d0bac64317deb3130ee151298b3f8ead0f86b6e
564
h
C
trick_sims/SIM_balloon/models/atmosphere/include/atmosphere.h
cmarsalc/trick
dbdeb5fc8a3dffde87fb15a9d2fb900ddab7f01d
[ "NASA-1.3" ]
647
2015-05-07T16:08:16.000Z
2022-03-30T02:33:21.000Z
trick_sims/SIM_balloon/models/atmosphere/include/atmosphere.h
cmarsalc/trick
dbdeb5fc8a3dffde87fb15a9d2fb900ddab7f01d
[ "NASA-1.3" ]
995
2015-04-30T19:44:31.000Z
2022-03-31T20:14:44.000Z
trick_sims/SIM_balloon/models/atmosphere/include/atmosphere.h
cmarsalc/trick
dbdeb5fc8a3dffde87fb15a9d2fb900ddab7f01d
[ "NASA-1.3" ]
251
2015-05-15T09:24:34.000Z
2022-03-22T20:39:05.000Z
#ifndef ATMOSPHERE_H #define ATMOSPHERE_H #ifdef __cplusplus extern "C" { #endif /* Returns atmospheric density (kg/m^3) at the given altitude (m).*/ double US_STD_density ( double alt_m ); /* Returns acceleration of gravity (m/s^2) at the given altitude (m).*/ double US_STD_gravity( double alt_m); /* Returns atmospheric temperature (℃) at the given altitude (m).*/ double US_STD_temperature( double alt_m ); /* Returns atmospheric pressure (pascals) at the given altitude (m).*/ double US_STD_pressure( double alt_m); #ifdef __cplusplus } #endif #endif
22.56
71
0.739362
d978f615c11123439c9e74d707daba7bfe2c17af
123
h
C
IntMath.h
weiyork/Win-Console
257cd4e64d8c1f8f97b653e3df8162ad14bc4595
[ "MIT" ]
null
null
null
IntMath.h
weiyork/Win-Console
257cd4e64d8c1f8f97b653e3df8162ad14bc4595
[ "MIT" ]
1
2018-02-05T02:48:34.000Z
2018-02-05T02:48:34.000Z
IntMath.h
weiyork/Win-Console
257cd4e64d8c1f8f97b653e3df8162ad14bc4595
[ "MIT" ]
null
null
null
#include"IMath.h" class CIntMath:public IMath { public: virtual int Add(int a, int b); virtual int Sub(int a,int b); };
13.666667
31
0.691057
8abe9d455ae22a7d97520e509ad5c0d09621a9e6
848
h
C
PD_Micro/mybuttstuff.h
jdimpson/PD_Micro
70fd545913e0db0cdef9b3ca6c087a7898c725db
[ "MIT" ]
null
null
null
PD_Micro/mybuttstuff.h
jdimpson/PD_Micro
70fd545913e0db0cdef9b3ca6c087a7898c725db
[ "MIT" ]
null
null
null
PD_Micro/mybuttstuff.h
jdimpson/PD_Micro
70fd545913e0db0cdef9b3ca6c087a7898c725db
[ "MIT" ]
null
null
null
/******* * Copyright 2021 Jeremy D. Impson <jdimpson at acm.org> * mybuttstuff is a button library for arduino and circuitpython * that makes it easy to detech when momentary switches are held * for specific lengths of time, and to avoid unwanted repeating * repetition when a button is held down. * * This software is available to be used under the terms described * in what is commonly knownas the MIT License, which can be found * in the file LICENSE. *******/ #ifndef MYBUTTSTUFF_H #define MYBUTTSTUFF_H struct mybuttstuff { int buttpin; unsigned long lastdebounce; unsigned long mono; unsigned long holding; bool wastouched; bool tchanged; bool pressed; bool released; }; void mybuttsetup(int pin, int pull); void mybuttloop(); bool mybuttheldfor(unsigned long msecs, bool reset); #endif /* MYBUTTSUFF_H */
27.354839
66
0.73467
caa0e2c2c3c39cb325d2bdb01566c58b4d794a3c
19,239
c
C
DIR819_v1.06/src/opensource/dlna/dlna_bcm/dms/CDS_Iface.c
Sirherobrine23/Dir819gpl_code
8af92d65416198755974e3247b7bbe7f1151d525
[ "BSD-2-Clause" ]
1
2022-03-19T06:38:01.000Z
2022-03-19T06:38:01.000Z
DIR819_v1.06/src/opensource/dlna/dlna_bcm/dms/CDS_Iface.c
Sirherobrine23/Dir819gpl_code
8af92d65416198755974e3247b7bbe7f1151d525
[ "BSD-2-Clause" ]
null
null
null
DIR819_v1.06/src/opensource/dlna/dlna_bcm/dms/CDS_Iface.c
Sirherobrine23/Dir819gpl_code
8af92d65416198755974e3247b7bbe7f1151d525
[ "BSD-2-Clause" ]
1
2022-03-19T06:38:03.000Z
2022-03-19T06:38:03.000Z
/*************************************************************************** * (c)2004-2009 Broadcom Corporation * * This program is the proprietary software of Broadcom Corporation and/or its licensors, * and may only be used, duplicated, modified or distributed pursuant to the terms and * conditions of a separate, written license agreement executed between you and Broadcom * (an "Authorized License"). Except as set forth in an Authorized License, Broadcom grants * no license (express or implied), right to use, or waiver of any kind with respect to the * Software, and Broadcom expressly reserves all rights in and to the Software and all * intellectual property rights therein. IF YOU HAVE NO AUTHORIZED LICENSE, THEN YOU * HAVE NO RIGHT TO USE THIS SOFTWARE IN ANY WAY, AND SHOULD IMMEDIATELY * NOTIFY BROADCOM AND DISCONTINUE ALL USE OF THE SOFTWARE. * * Except as expressly set forth in the Authorized License, * * 1. This program, including its structure, sequence and organization, constitutes the valuable trade * secrets of Broadcom, and you shall use all reasonable efforts to protect the confidentiality thereof, * and to use this information only in connection with your use of Broadcom integrated circuit products. * * 2. TO THE MAXIMUM EXTENT PERMITTED BY LAW, THE SOFTWARE IS PROVIDED "AS IS" * AND WITH ALL FAULTS AND BROADCOM MAKES NO PROMISES, REPRESENTATIONS OR * WARRANTIES, EITHER EXPRESS, IMPLIED, STATUTORY, OR OTHERWISE, WITH RESPECT TO * THE SOFTWARE. BROADCOM SPECIFICALLY DISCLAIMS ANY AND ALL IMPLIED WARRANTIES * OF TITLE, MERCHANTABILITY, NONINFRINGEMENT, FITNESS FOR A PARTICULAR PURPOSE, * LACK OF VIRUSES, ACCURACY OR COMPLETENESS, QUIET ENJOYMENT, QUIET POSSESSION * OR CORRESPONDENCE TO DESCRIPTION. YOU ASSUME THE ENTIRE RISK ARISING OUT OF * USE OR PERFORMANCE OF THE SOFTWARE. * * 3. TO THE MAXIMUM EXTENT PERMITTED BY LAW, IN NO EVENT SHALL BROADCOM OR ITS * LICENSORS BE LIABLE FOR (i) CONSEQUENTIAL, INCIDENTAL, SPECIAL, INDIRECT, OR * EXEMPLARY DAMAGES WHATSOEVER ARISING OUT OF OR IN ANY WAY RELATING TO YOUR * USE OF OR INABILITY TO USE THE SOFTWARE EVEN IF BROADCOM HAS BEEN ADVISED OF * THE POSSIBILITY OF SUCH DAMAGES; OR (ii) ANY AMOUNT IN EXCESS OF THE AMOUNT * ACTUALLY PAID FOR THE SOFTWARE ITSELF OR U.S. $1, WHICHEVER IS GREATER. THESE * LIMITATIONS SHALL APPLY NOTWITHSTANDING ANY FAILURE OF ESSENTIAL PURPOSE OF * ANY LIMITED REMEDY. * * $brcm_Workfile: CDS_Iface.c $ * $brcm_Revision: 3 $ * $brcm_Date: 7/24/09 10:42a $ * * Module Description: * * Revision History: * * $brcm_Log: /AppLibs/dlna/dms/CDS_Iface.c $ * * 3 7/24/09 10:42a ajitabhp * PR55165: Changes For Compiling DMS as library. * * 2 6/29/09 12:13p ajitabhp * PR55165: Added Path Input From User. * ***************************************************************************/ //#include "server.h" //#include "action.h" #include "CDS_Iface.h" #include "trace.h" #include "DMS.h" #include "UTF8Utils.h" #include "upnp_priv.h" char *browse_type_list[] = {CDS_BROWSE_METADATA, CDS_BROWSE_CHILDREN, 0}; static BUPnPStateVariableInfo SearchCapabilities = { "SearchCapabilities", 0, BUPnPType_String, "", {NULL} }; static BUPnPStateVariableInfo SortCapabilities = { "SortCapabilities", 0, BUPnPType_String, "", {NULL} }; static BUPnPStateVariableInfo SystemUpdateID = { "SystemUpdateID", BUPnPAttribute_Evented, BUPnPType_UI4, "0", {NULL} }; static BUPnPStateVariableInfo A_ARG_TYPE_ObjectID = { "A_ARG_TYPE_ObjectID", 0, BUPnPType_String, "", {NULL} }; static BUPnPStateVariableInfo A_ARG_TYPE_Result = { "A_ARG_TYPE_Result", BUPnPAttribute_List, BUPnPType_String, "", {NULL} }; static BUPnPStateVariableInfo A_ARG_TYPE_BrowseFlag = { "A_ARG_TYPE_BrowseFlag", BUPnPAttribute_List, BUPnPType_String, "", {browse_type_list} }; static BUPnPStateVariableInfo A_ARG_TYPE_Filter = { "A_ARG_TYPE_Filter", 0, BUPnPType_String, "", {NULL} }; static BUPnPStateVariableInfo A_ARG_TYPE_SortCriteria = { "A_ARG_TYPE_SortCriteria", 0, BUPnPType_String, "", {NULL} }; static BUPnPStateVariableInfo A_ARG_TYPE_Index = { "A_ARG_TYPE_Index", 0, BUPnPType_UI4, "", {NULL} }; static BUPnPStateVariableInfo A_ARG_TYPE_Count = { "A_ARG_TYPE_Count", 0, BUPnPType_UI4, "", {NULL} }; static BUPnPStateVariableInfo A_ARG_TYPE_UpdateID = { "A_ARG_TYPE_UpdateID", 0, BUPnPType_UI4, "", {NULL} }; static BUPnPStateVariableInfo A_ARG_TYPE_URI = { "A_ARG_TYPE_URI", 0, BUPnPType_String, "", {NULL} }; static BUPnPStateVariableInfo A_ARG_TYPE_TransferID = { "A_ARG_TYPE_TransferID", 0, BUPnPType_String, "", {NULL} }; static BUPnPStateVariableInfo* CDSStateVariables[] = { &SearchCapabilities, &SortCapabilities, &SystemUpdateID, &A_ARG_TYPE_ObjectID, &A_ARG_TYPE_Result, &A_ARG_TYPE_BrowseFlag, &A_ARG_TYPE_Filter, &A_ARG_TYPE_SortCriteria, &A_ARG_TYPE_Index, &A_ARG_TYPE_Count, &A_ARG_TYPE_UpdateID, &A_ARG_TYPE_URI, &A_ARG_TYPE_TransferID, NULL }; /* Action argument list */ BUPnPArgumentInfo SearchCaps= {"SearchCaps", BUPnPAttribute_Out, &SearchCapabilities}; static BUPnPArgumentInfo *GetSearchCapabilitiesArguments[] = { &SearchCaps, NULL }; BUPnPArgumentInfo SortCaps = {"SortCaps", BUPnPAttribute_Out, &SortCapabilities}; static BUPnPArgumentInfo *GetSortCapabilitiesArguments[] = { &SortCaps, NULL }; BUPnPArgumentInfo Id = {"Id", BUPnPAttribute_Out, &SystemUpdateID}; static BUPnPArgumentInfo *GetSystemUpdateIDArguments[] = { &Id, NULL }; static BUPnPArgumentInfo ObjectID = {"ObjectID", BUPnPAttribute_In, &A_ARG_TYPE_ObjectID}; static BUPnPArgumentInfo BrowseFlag = {"BrowseFlag", BUPnPAttribute_In, &A_ARG_TYPE_BrowseFlag}; static BUPnPArgumentInfo Filter = {"Filter", BUPnPAttribute_In, &A_ARG_TYPE_Filter}; static BUPnPArgumentInfo StartingIndex = {"StartingIndex", BUPnPAttribute_In, &A_ARG_TYPE_Index}; static BUPnPArgumentInfo RequestedCount = {"RequestedCount", BUPnPAttribute_In, &A_ARG_TYPE_Count}; static BUPnPArgumentInfo SortCriteria = {"SortCriteria", BUPnPAttribute_In, &A_ARG_TYPE_SortCriteria}; static BUPnPArgumentInfo Result = {"Result", BUPnPAttribute_Out, &A_ARG_TYPE_Result}; static BUPnPArgumentInfo NumberReturned = {"NumberReturned", BUPnPAttribute_Out, &A_ARG_TYPE_Count}; static BUPnPArgumentInfo TotalMatches = {"TotalMatches", BUPnPAttribute_Out, &A_ARG_TYPE_Count}; static BUPnPArgumentInfo UpdateID = {"UpdateID", BUPnPAttribute_Out, &A_ARG_TYPE_UpdateID}; static BUPnPArgumentInfo *BrowseArguments[] = { &ObjectID, &BrowseFlag, &Filter, &StartingIndex, &RequestedCount, &SortCriteria, &Result, &NumberReturned, &TotalMatches, &UpdateID, NULL }; static BUPnPArgumentInfo ContainerID = {"ContainerID", BUPnPAttribute_In, &A_ARG_TYPE_ObjectID}; static BUPnPArgumentInfo Elements = {"Elements", BUPnPAttribute_In, &A_ARG_TYPE_Result}; static BUPnPArgumentInfo ObjectIDOut = {"ObjectID", BUPnPAttribute_Out, &A_ARG_TYPE_ObjectID}; static BUPnPArgumentInfo *CreateObjectArguments[] = { &ContainerID, &Elements, &ObjectIDOut, &Result, NULL }; static BUPnPArgumentInfo *DestroyObjectArguments[] = { &ObjectID, NULL }; static BUPnPArgumentInfo SourceURI = {"SourceURI", BUPnPAttribute_In, &A_ARG_TYPE_URI}; static BUPnPArgumentInfo DestinationURI = {"DestinationURI", BUPnPAttribute_In, &A_ARG_TYPE_URI}; static BUPnPArgumentInfo TransferID = {"TransferID", BUPnPAttribute_Out, &A_ARG_TYPE_TransferID}; static BUPnPArgumentInfo *ImportResourceArguments[] = { &SourceURI, &DestinationURI, &TransferID, NULL }; static BUPnPArgumentInfo ResourceURI = {"ResourceURI", BUPnPAttribute_In, &A_ARG_TYPE_URI}; static BUPnPArgumentInfo *DeleteResourceArguments[] = { &ResourceURI, NULL }; /************************ Search Is not Implemented yet static UPnPArgumentInfo SearchArguments[] = { {"ContainerID", UPnPAttribute_In, &A_ARG_TYPE_ObjectID}, {"SearchCriteria", UPnPAttribute_In, &A_ARG_TYPE_SearchCriteria}, {"Filter", UPnPAttribute_In, &A_ARG_TYPE_Filter}, {"StartingIndex", UPnPAttribute_In, &A_ARG_TYPE_Index}, {"RequestCount", UPnPAttribute_In, &A_ARG_TYPE_Count}, {"SortCriteria", UPnPAttribute_In, &A_ARG_TYPE_SortCriteria}, {"Result", UPnPAttribute_Out, &A_ARG_TYPE_Result}, {"NuberReturned", UPnPAttribute_Out, &A_ARG_TYPE_Count}, {"TotalMatches", UPnPAttribute_Out, &A_ARG_TYPE_Count}, {"UpdateID", UPnPAttribute_Out, &A_ARG_TYPE_UpdateID}, }; *******************************************************/ BUPnPActionInfo GetSearchCapabilities = {"GetSearchCapabilities", cds_get_search_capabilities_if,GetSearchCapabilitiesArguments}; BUPnPActionInfo GetSortCapabilities = {"GetSortCapabilities", cds_get_sort_capabilities_if, GetSortCapabilitiesArguments}; BUPnPActionInfo GetSystemUpdateID = {"GetSystemUpdateID", cds_get_system_updateid_if, GetSystemUpdateIDArguments}; BUPnPActionInfo Browse = {"Browse", cds_browse_if, BrowseArguments}; BUPnPActionInfo DestroyObject = {"DestroyObject", cds_destroy_object_if, DestroyObjectArguments}; BUPnPActionInfo CreateObject = {"CreateObject", cds_create_object_if, CreateObjectArguments}; BUPnPActionInfo ImportResource = {"ImportResource", cds_import_resource_if, ImportResourceArguments}; BUPnPActionInfo DeleteResource = {"DeleteResource", cds_delete_resource_if, DeleteResourceArguments}; static BUPnPActionInfo *cdsActions[] = { &GetSearchCapabilities, &GetSortCapabilities, &GetSystemUpdateID, &Browse, &CreateObject, &DestroyObject, &ImportResource, &DeleteResource, //{"Search", cds_serach_if, SearchArguments}, NULL }; BUPnPServiceInfo Service_ContentDirectory = { "urn:schemas-upnp-org:service:ContentDirectory:1", /* serviceType */ "urn:upnp-org:serviceId:ContentDirectory", /* serviceId */ "/cds", /* SCPDURL */ "/cds_control", /* ControlURL */ "/cds_event", /* EventSubURL */ cdsActions, /* Actions */ CDSStateVariables, /* state variables */ }; extern DMS_CONTEXT gDmsContext; /* Add by tuhanyu, for create/destory object and import/delete resource action, 2011/05/03, start */ extern int transfer_count; extern Url url[2]; BUPnPError cds_delete_resource_if(BUPnPServiceHandle hService, BUPnPActionHandle hAction) { BC_STATUS ret_sts = BC_UPNP_E_SUCCESS; char *temp; /* Get Arguments */ BUPnPAction_GetStringArgument(hAction, 0,(const char **) &temp); ret_sts = cds_delete_resource(temp); return ret_sts; } BUPnPError cds_import_resource_if(BUPnPServiceHandle hService, BUPnPActionHandle hAction) { BC_STATUS ret_sts = BC_UPNP_E_SUCCESS; cds_import_resource_in_params Inargs={0,NULL}; char *temp; Url srcUrl, dstUrl; SOCKET s = 0; if(transfer_count >= CDS_MAX_TRANSFER) { printf("cds_import_resource_if: max num of download task is %d \n", CDS_MAX_TRANSFER); return UPNP_E_ACTION_FAILED; } /* Get Arguments */ BUPnPAction_GetStringArgument(hAction, 0,(const char **) &temp); if(temp) { Inargs.SourceURI = strdup(temp); } else { printf("cds_import_resource_if: source URI failed.\n"); return UPNP_E_NO_SUCH_SOURCE_RESOURCE; } temp = NULL; BUPnPAction_GetStringArgument(hAction, 1,(const char **) &temp); if(temp) { Inargs.DestinationURI = strdup(temp); } else { printf("cds_import_resource_if: destination URI failed.\n"); free(Inargs.SourceURI); return UPNP_E_NO_SUCH_DESTINATION_RESOURCE; } if(Url_Create(&dstUrl, Inargs.DestinationURI)) { printf("cds_import_resource_if: destination URI failed.\n"); free(Inargs.SourceURI); free(Inargs.DestinationURI); return UPNP_E_NO_SUCH_DESTINATION_RESOURCE; } if(Url_Create(&srcUrl, Inargs.SourceURI)) { printf("cds_import_resource_if: source URI failed.\n"); free(Inargs.SourceURI); free(Inargs.DestinationURI); Url_Destroy(&dstUrl); return UPNP_E_NO_SUCH_SOURCE_RESOURCE; } if(!(s = BSocket_CreateTcpClient(srcUrl.host, srcUrl.port))) { printf("cds_import_resource_if: create tcp client socket failed.\n"); free(Inargs.SourceURI); free(Inargs.DestinationURI); Url_Destroy(&dstUrl); Url_Destroy(&srcUrl); return UPNP_E_NO_SUCH_SOURCE_RESOURCE; } closesocket(s); memcpy(&url[0], &srcUrl, sizeof(Url)); memcpy(&url[1], &dstUrl, sizeof(Url)); bthread_create(cds_download_mediafile, NULL); transfer_count++; free(Inargs.SourceURI); free(Inargs.DestinationURI); return ret_sts; } BUPnPError cds_destroy_object_if(BUPnPServiceHandle hService, BUPnPActionHandle hAction) { BC_STATUS ret_sts = BC_UPNP_E_SUCCESS; cds_destroy_object_in_params Inargs={0,NULL}; char *ObjectID; /* Get Arguments */ BUPnPAction_GetStringArgument(hAction, 0,(const char **) &ObjectID); Inargs.ObjectID = strtoul(ObjectID, NULL, 10); ret_sts = cds_destroy_object(&Inargs); return ret_sts; } BUPnPError cds_create_object_if(BUPnPServiceHandle hService, BUPnPActionHandle hAction) { BC_STATUS ret_sts = BC_UPNP_E_SUCCESS; cds_create_object_in_params Inargs={0,NULL}; pcds_create_object_out_params pOut; char *ObjectID; char *temp; pOut = (pcds_create_object_out_params)malloc(sizeof(pcds_create_object_out_params)); if(pOut == NULL) return UPNP_E_OUT_OF_MEMORY; if(!(pOut->ResultOutBuff = buffer_new())) { free(pOut); return UPNP_E_OUT_OF_MEMORY; } if(!(Inargs.Elements = buffer_new())) { buffer_free(pOut->ResultOutBuff); free(pOut); return UPNP_E_OUT_OF_MEMORY; } /* Get Arguments */ BUPnPAction_GetStringArgument(hAction, 0,(const char **) &ObjectID); Inargs.ContainerID = strtoul(ObjectID, NULL, 10); BUPnPAction_GetStringArgument(hAction, 1,(const char **) &temp); Inargs.Elements->buf = strdup(temp); ret_sts = cds_create_object(&Inargs, pOut); if(ret_sts == BC_UPNP_E_SUCCESS) { char *utf8_buf = EncodeToUTF8(pOut->ResultOutBuff->buf); BUPnPAction_SetUInt32Argument(hAction, 2, pOut->ObjectID); BUPnPAction_SetStringArgument(hAction, 3, utf8_buf); if(utf8_buf) free(utf8_buf); } buffer_free(pOut->ResultOutBuff); buffer_free(Inargs.Elements); free(pOut); return ret_sts; } /* Add by tuhanyu, end */ BUPnPError cds_browse_if(BUPnPServiceHandle hService, BUPnPActionHandle hAction) { BC_STATUS ret_sts = BC_UPNP_E_SUCCESS; cds_browse_in_params Inargs={0,NULL,NULL,0,0,NULL}; pcds_browse_out_params pOut; char *ObjectID; pOut = (pcds_browse_out_params)malloc(sizeof(cds_browse_out_params)); if(pOut == NULL) return UPNP_E_OUT_OF_MEMORY; if(!(pOut->ResultOutBuff = buffer_new())) { free(pOut); return UPNP_E_OUT_OF_MEMORY; } /* Get Arguments */ BUPnPAction_GetStringArgument(hAction, 0,(const char **) &ObjectID); Inargs.ObjectID = strtoul(ObjectID, NULL, 10); BUPnPAction_GetStringArgument(hAction, 1,(const char **) &Inargs.BrowseFlag); BUPnPAction_GetStringArgument(hAction, 2,(const char **) &Inargs.Filter); BUPnPAction_GetUInt32Argument(hAction, 3, &Inargs.StartingIndex); BUPnPAction_GetUInt32Argument(hAction, 4, &Inargs.RequestedCount); BUPnPAction_GetStringArgument(hAction, 5,(const char **) &Inargs.SortCriteria); /* Modified by tuhanyu, change scanning media file to periodically, 2011/04/02, start */ #if 0 /* auto refresh media data base when on browser */ ret_sts = cds_finish(); if(ret_sts != BC_UPNP_E_SUCCESS){ BcmLogMsg("%s:Failed Cleanup\n",__FUNCTION__); } ret_sts = cds_init(gDmsContext.ContentXferbaseurl, "/mnt", Inargs.ObjectID); if(ret_sts != BC_UPNP_E_SUCCESS){ BcmLogMsg("%s:Failed Initialization\n",__FUNCTION__); } #else ret_sts = cds_update(); if(ret_sts != BC_UPNP_E_SUCCESS){ BcmLogMsg("%s:Failed Cleanup\n",__FUNCTION__); printf("cds_browse_if: media data scanning has not finished, please wait.....\n"); buffer_free(pOut->ResultOutBuff); free(pOut); return ret_sts; } #endif /* Modified by tuhanyu, end */ ret_sts = cds_browse(&Inargs, pOut); if(ret_sts == BC_UPNP_E_SUCCESS) { char *utf8_buf = EncodeToUTF8(pOut->ResultOutBuff->buf); BUPnPAction_SetStringArgument(hAction, 6, utf8_buf); if(utf8_buf) free(utf8_buf); BUPnPAction_SetUInt32Argument(hAction, 7, pOut->NumberReturned); BUPnPAction_SetUInt32Argument(hAction, 8, pOut->TotalMatches); BUPnPAction_SetUInt32Argument(hAction, 9, pOut->UpdateID); } buffer_free(pOut->ResultOutBuff); free(pOut); return ret_sts; } BUPnPError cds_get_search_capabilities_if(BUPnPServiceHandle hService, BUPnPActionHandle hAction) { BC_STATUS ret_sts = BC_UPNP_E_SUCCESS; char caps[256]; ret_sts = cds_get_search_caps(&caps[0]); BUPnPAction_SetStringArgument(hAction,0,caps); return ret_sts; } BUPnPError cds_get_sort_capabilities_if(BUPnPServiceHandle hService, BUPnPActionHandle hAction) { BC_STATUS ret_sts = BC_UPNP_E_SUCCESS; char caps[256]; ret_sts = cds_get_sort_caps(&caps[0]); BUPnPAction_SetStringArgument(hAction,0,caps); return ret_sts; } BUPnPError cds_get_system_updateid_if(BUPnPServiceHandle hService, BUPnPActionHandle hAction) { unsigned int id; id = cds_get_system_update_id(); BUPnPAction_SetUInt32Argument(hAction, 0, id); return UPNP_E_SUCCESS; } /*Do Any Initialization Here*/ void cds_service_start_if(char * baseServerUrl, char *ContentDir) { #if 0 /* Be invoked when on browser */ BC_STATUS ret_sts = BC_UPNP_E_SUCCESS; char cds_url[512]; sprintf(cds_url,"%s%s",baseServerUrl,Service_ContentDirectory.scpdUrl); ret_sts = cds_init(cds_url,ContentDir); if(ret_sts != BC_UPNP_E_SUCCESS){ BcmLogMsg("%s:Failed Initialization\n",__FUNCTION__); } #endif /* Add by tuhanyu, create a thread for scanning media file, 2011/04/02, start */ bthread_create(cds_scan_thread, NULL); /* Add by tuhanyu, end */ return; } /*Do Any Cleanup Here*/ void cds_service_stop_if() { #if 0 /* Be invoked when on browser */ BC_STATUS ret_sts = BC_UPNP_E_SUCCESS; ret_sts = cds_finish(); if(ret_sts != BC_UPNP_E_SUCCESS){ BcmLogMsg("%s:Failed Cleanup\n",__FUNCTION__); } #endif return; }
35.107664
145
0.697282
f09072e63e9d1e7dae5ff136ae21727fedd1c216
2,237
h
C
src/mongo/util/debug_util.h
danx0r/mongo
70d4944c235bcdf7fbbc63971099563d2af72956
[ "Apache-2.0" ]
72
2020-06-12T06:33:41.000Z
2021-03-22T03:15:56.000Z
src/mongo/util/debug_util.h
danx0r/mongo
70d4944c235bcdf7fbbc63971099563d2af72956
[ "Apache-2.0" ]
9
2020-07-02T09:36:49.000Z
2021-03-25T23:54:00.000Z
src/mongo/util/debug_util.h
danx0r/mongo
70d4944c235bcdf7fbbc63971099563d2af72956
[ "Apache-2.0" ]
14
2020-06-12T03:08:03.000Z
2021-02-03T11:43:09.000Z
// debug_util.h /* Copyright 2009 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects * for all of the code used other than as permitted herein. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you do not * wish to do so, delete this exception statement from your version. If you * delete this exception statement from all source files in the program, * then also delete it in the license file. */ #pragma once #include "mongo/config.h" namespace mongo { #if defined(MONGO_CONFIG_DEBUG_BUILD) const bool kDebugBuild = true; #else const bool kDebugBuild = false; #endif #define MONGO_DEV if (kDebugBuild) #define DEV MONGO_DEV // The following declare one unique counter per enclosing function. // NOTE The implementation double-increments on a match, but we don't really care. #define MONGO_SOMETIMES(occasion, howOften) \ for (static unsigned occasion = 0; ++occasion % howOften == 0;) #define SOMETIMES MONGO_SOMETIMES #define MONGO_OCCASIONALLY SOMETIMES(occasionally, 16) #define OCCASIONALLY MONGO_OCCASIONALLY #define MONGO_RARELY SOMETIMES(rarely, 128) #define RARELY MONGO_RARELY } // namespace mongo
38.568966
82
0.745194
29d3c0eb54b870c39a4216f2fdb44aab1be99219
4,159
h
C
wrappers/7.0.0/vtkHyperOctreeSampleFunctionWrap.h
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
6
2016-02-03T12:48:36.000Z
2020-09-16T15:07:51.000Z
wrappers/7.0.0/vtkHyperOctreeSampleFunctionWrap.h
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
4
2016-02-13T01:30:43.000Z
2020-03-30T16:59:32.000Z
wrappers/7.0.0/vtkHyperOctreeSampleFunctionWrap.h
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
null
null
null
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #ifndef NATIVE_EXTENSION_VTK_VTKHYPEROCTREESAMPLEFUNCTIONWRAP_H #define NATIVE_EXTENSION_VTK_VTKHYPEROCTREESAMPLEFUNCTIONWRAP_H #include <nan.h> #include <vtkSmartPointer.h> #include <vtkHyperOctreeSampleFunction.h> #include "vtkHyperOctreeAlgorithmWrap.h" #include "../../plus/plus.h" class VtkHyperOctreeSampleFunctionWrap : public VtkHyperOctreeAlgorithmWrap { public: using Nan::ObjectWrap::Wrap; static void Init(v8::Local<v8::Object> exports); static void InitPtpl(); static void ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info); VtkHyperOctreeSampleFunctionWrap(vtkSmartPointer<vtkHyperOctreeSampleFunction>); VtkHyperOctreeSampleFunctionWrap(); ~VtkHyperOctreeSampleFunctionWrap( ); static Nan::Persistent<v8::FunctionTemplate> ptpl; private: static void New(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetDepth(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetDimension(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetHeight(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetImplicitFunction(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetLevels(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetMTime(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetMinLevels(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetOrigin(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetOutputScalarType(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetSize(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetThreshold(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetWidth(const Nan::FunctionCallbackInfo<v8::Value>& info); static void IsA(const Nan::FunctionCallbackInfo<v8::Value>& info); static void NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetDepth(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetDimension(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetHeight(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetImplicitFunction(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetLevels(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetMinLevels(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetOrigin(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetOutputScalarType(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetOutputScalarTypeToChar(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetOutputScalarTypeToDouble(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetOutputScalarTypeToFloat(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetOutputScalarTypeToInt(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetOutputScalarTypeToLong(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetOutputScalarTypeToShort(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetOutputScalarTypeToUnsignedChar(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetOutputScalarTypeToUnsignedInt(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetOutputScalarTypeToUnsignedLong(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetOutputScalarTypeToUnsignedShort(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetSize(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetThreshold(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetWidth(const Nan::FunctionCallbackInfo<v8::Value>& info); #ifdef VTK_NODE_PLUS_VTKHYPEROCTREESAMPLEFUNCTIONWRAP_CLASSDEF VTK_NODE_PLUS_VTKHYPEROCTREESAMPLEFUNCTIONWRAP_CLASSDEF #endif }; #endif
54.012987
99
0.795864
af9dfeb657894bd18f84f175af5b47d4622f595a
864
h
C
src/composite/SequenceNode.h
GugaLincon/behavior-tree
e7678c1a2150baa9eff97a4c13d6ad9163fa5f3e
[ "MIT" ]
1
2021-02-15T18:23:30.000Z
2021-02-15T18:23:30.000Z
src/composite/SequenceNode.h
GugaLincon/behavior-tree
e7678c1a2150baa9eff97a4c13d6ad9163fa5f3e
[ "MIT" ]
null
null
null
src/composite/SequenceNode.h
GugaLincon/behavior-tree
e7678c1a2150baa9eff97a4c13d6ad9163fa5f3e
[ "MIT" ]
null
null
null
#ifndef SEQUENCENODE_H #define SEQUENCENODE_H #include "CompositeNode.h" namespace behavior_tree { /** * Represents a sequence node. * A sequence ticks all its children as long as they return SUCCESS. If any child returns FAILURE, * the sequence is aborted, returning FAILURE. */ class SequenceNode : public CompositeNode { public: /** * Default constructor. */ SequenceNode(); /** * Sets the first child to run on execution of the sequence node. */ void enter() override; /** * Tries to execute all of its children, stopping at the first non-SUCCESS returned. * @return RUNNING, if a child returns RUNNING. FAILURE, if a child returns FAILURE. SUCCESS, if all children * return SUCCESS. */ ExecutionStatus execute() override; protected: int runningChild; }; } #endif //SEQUENCENODE_H
22.736842
113
0.6875
cbe3931fc7f18677aad9fcf615e0b96407f94154
422
h
C
Sources/SRGIdentity/UIWindow+SRGIdentity.h
SRGSSR/srgidentity-ios
8b852be038b73b552d5f9b6d499536b70401d0bf
[ "MIT" ]
1
2022-01-04T13:45:34.000Z
2022-01-04T13:45:34.000Z
Sources/SRGIdentity/UIWindow+SRGIdentity.h
SRGSSR/srgidentity-apple
c4eb6fbb3e84f8cdc340a55b50475eeddd1db011
[ "MIT" ]
5
2019-12-13T14:53:24.000Z
2021-01-06T12:13:00.000Z
Sources/SRGIdentity/UIWindow+SRGIdentity.h
SRGSSR/srgidentity-ios
8b852be038b73b552d5f9b6d499536b70401d0bf
[ "MIT" ]
null
null
null
// // Copyright (c) SRG SSR. All rights reserved. // // License information is available from the LICENSE file. // @import UIKit; NS_ASSUME_NONNULL_BEGIN @interface UIWindow (SRGIdentity) /** * Return the topmost view controller (either root view controller or presented modally). */ @property (nonatomic, readonly, nullable) __kindof UIViewController *srgidentity_topViewController; @end NS_ASSUME_NONNULL_END
20.095238
99
0.767773
8b5e56fb5a70f548b200f2ecb5b87657c72ab615
723
h
C
trunk/src/Interfaces/ComputeEngineInterface.h
bwfrazie/CEM
88ef4aac8e5c0a4a9b7120162b4e3448fdb0aa7f
[ "MIT" ]
null
null
null
trunk/src/Interfaces/ComputeEngineInterface.h
bwfrazie/CEM
88ef4aac8e5c0a4a9b7120162b4e3448fdb0aa7f
[ "MIT" ]
3
2017-08-12T18:38:33.000Z
2017-08-26T04:40:40.000Z
trunk/src/Interfaces/ComputeEngineInterface.h
shockwavefraz/CEM
88ef4aac8e5c0a4a9b7120162b4e3448fdb0aa7f
[ "MIT" ]
1
2021-02-23T11:16:19.000Z
2021-02-23T11:16:19.000Z
/** * @file ComputeEngineInterface.h * @brief Virtual class definition for Computational Engines, defines the interface * @details Required Interface functions: * @author Ben Frazier * @date 08/12/2017 */ #ifndef COMPUTE_ENGINE_INTERFACE_H #define COMPUTE_ENGINE_INTERFACE_H #include <vector> #include "CEMCommon.h" struct InputStruct; namespace CEM { class SourceControlInterface; class ComputeEngineInterface { public: virtual void UpdateFields(double time, std::shared_ptr<SourceControlInterface> source) = 0; virtual double getEField(int index)=0; virtual double getHField(int index)=0; virtual Eigen::MatrixXd getEField()=0; virtual Eigen::MatrixXd getHField()=0; }; } #endif
21.264706
95
0.749654
272ec338b7907aab357e3f5760d2261f034f94d3
27,440
c
C
HAL/src/eoss3_hal_spi.c
Thirsty2/qorc-sdk
5b4de88b2ad6e81f3341f2632b6304e806af7e79
[ "Apache-2.0" ]
null
null
null
HAL/src/eoss3_hal_spi.c
Thirsty2/qorc-sdk
5b4de88b2ad6e81f3341f2632b6304e806af7e79
[ "Apache-2.0" ]
null
null
null
HAL/src/eoss3_hal_spi.c
Thirsty2/qorc-sdk
5b4de88b2ad6e81f3341f2632b6304e806af7e79
[ "Apache-2.0" ]
null
null
null
/*========================================================== * Copyright 2020 QuickLogic Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *==========================================================*/ /*========================================================== * * File : eoss3_hal_spi.c * Purpose: This file contains HAL API for SPI * *=========================================================*/ #include "Fw_global_config.h" #ifndef SPI_WB_INTERFACE /* Standard includes. */ #include <stdio.h> #include <string.h> #include "FreeRTOS.h" #include "semphr.h" #include "task.h" #include "dbg_uart.h" #include "sec_debug.h" #include "eoss3_dev.h" #include "eoss3_hal_spi.h" #include "s3x_clock_hal.h" #include "eoss3_hal_pad_config.h" SPI_HandleTypeDef *SPIHandle; static SemaphoreHandle_t xLockSPI1Bus, xWaitForIntr; static int SPI_Instance_count = 0; // Number of SPI driver object instantiated typedef union SPI_WR_WORD { UINT8_t tb_r[2]; UINT16_t tw_r; }SPI_Wr; /// @cond HAL_SPI_LOCAL_FUN /*! * \fn void assert_failed(UINT8_t *file, UINT32_t line) * \brief This function trigger assert on invalid parameter */ void assert_failed(const char *file, int line) { dbg_str_str("Wrong parameter value: file", file); dbg_str_int("line",line); dbg_fatal_error("assert-hal-spi"); return; } /// @endcond void unlock_spi1_bus(UINT8_t Ctx) { if(xLockSPI1Bus) { if (Ctx == CTX_ISR) { BaseType_t xHigherPriorityTaskWoken = pdFALSE;; if (xSemaphoreGiveFromISR(xLockSPI1Bus,&xHigherPriorityTaskWoken) == pdTRUE) { portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); } } else { if (xSemaphoreGive(xLockSPI1Bus) != pdTRUE) { printf("[HAL SPI] : Error : unable to release lock to spibus1\n"); } } } } void lock_spi1_bus(void) { if(xLockSPI1Bus) { if (xSemaphoreTake(xLockSPI1Bus, portMAX_DELAY) != pdTRUE) { dbg_fatal_error("[HAL SPI] : Error unable to take lock to spibus1\n"); return; } } } static void SPI_Enable(SPI_HandleTypeDef *hspi, UINT8_t ucEnable) { if (ucEnable == 1) SPI_MS->SSIENR = SSIENR_SSI_EN; else SPI_MS->SSIENR = SSIENR_SSI_DISABLE; } /*! * \fn static HAL_StatusTypeDef SPI_PollTxFifoEmptyFlag(void) * \brief Function to poll TxFIFO Empty flag set */ static void SPI_PollTxFifoEmptyFlag(void) { volatile UINT32_t temp = 0; do { temp = SPI_MS->SR; if((temp & SR_TFE) && !(temp & SR_BUSY)) { break; } } while(1); } /*! * \fn static void SPI_FiFoWrite(SPI_HandleTypeDef *hspi) * \brief Function to write SPI data register * \param hspi --- handle to SPI structure */ static void SPI_FiFoWrite(SPI_HandleTypeDef *hspi) { SPI_Wr spi_w; UINT8_t *txb = (UINT8_t *) (hspi->pTxBuffer); UINT32_t ulLen = hspi->usTxXferSize; if (ulLen > 0) { if (hspi->Init.ucCmdType == PROGRAM_CMD) { /* byte len to wordLen */ ulLen >>= 1; while (ulLen > 0) { spi_w.tb_r[1] = *txb++; spi_w.tb_r[0] = *txb++; SPI_MS->DR0 = spi_w.tw_r; ulLen--; } } else { //slave select enable while((SPI_MS->SR & SR_TFE) == 0) ; //wait until Tx Fifo Empty is set do { SPI_MS->DR0 = *txb++; ulLen--; } while (ulLen > 0); } } //slave select enable if(hspi->Init.ucSSn == SPI_SLAVE_1_SELECT) SPI_MS->SER = SER_SS_0_N_SELECTED; else if(hspi->Init.ucSSn == SPI_SLAVE_2_SELECT) SPI_MS->SER = SER_SS_1_N_SELECTED; else SPI_MS->SER = SER_SS_2_N_SELECTED; } /*! * \fn static void SPI_FiFoRead(SPI_HandleTypeDef *hspi) * \brief Function to read SPI data register during SPI flash read * \param hspi --- SPI handle */ static void SPI_FiFoRead(SPI_HandleTypeDef *hspi) { UINT8_t *rxbuf = (UINT8_t*) (hspi->pRxBuffer); UINT16_t len = hspi->usRxXferSize; int temp; if (len > 0) { do { temp = 1000; //Poll Rx FIFO Not Empty do { temp--; if (SPI_MS->SR & SR_RFNE) { *rxbuf++ = SPI_MS->DR0; len--; } else break; }while(temp > 0); } while (len > 0); } } /*! * \fn static void SPI_FlashRead(SPI_HandleTypeDef *hspi) * \brief Function to read SPI data register during SPI flash read * \param hspi --- SPI handle */ static void SPI_FlashRead(SPI_HandleTypeDef *hspi) { UINT8_t *rxbuf = (UINT8_t*) (hspi->pRxBuffer); UINT16_t len = hspi->usRxXferSize; SPI_MS->DR0 = 0; if(hspi->Init.ucSSn == SPI_SLAVE_1_SELECT) SPI_MS->SER = SER_SS_0_N_SELECTED; else if(hspi->Init.ucSSn == SPI_SLAVE_2_SELECT) SPI_MS->SER = SER_SS_1_N_SELECTED; else SPI_MS->SER = SER_SS_2_N_SELECTED; if (len > 0) { do { //Poll Rx FIFO Not Empty do { if (SPI_MS->SR & SR_RFNE) break; } while (1); *rxbuf++ = SPI_MS->DR0; len--; } while (len > 0); } } HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, UINT8_t *pData, UINT32_t ulTxLen, void (*HAL_SPI_Callback)(void)) { UINT32_t ulDomainClk = 0; if (pData == NULL || ulTxLen == 0) { printf("[HAL_SPI_Transmit]: Invalid parameters received: len = %d\r\n",ulTxLen); return HAL_ERROR; } lock_spi1_bus(); assert_param(IS_SPI_SSN_VALID(hspi->Init.ucSSn)); assert_param(IS_SPIx_VALID(hspi->ucSPIx)); SPIHandle = hspi; //Initialize the structure hspi->pTxBuffer = pData; hspi->pRxBuffer = NULL; hspi->TxISR = NULL; hspi->RxISR = NULL; hspi->usRxXferSize = 0; hspi->HAL_SPI_TxRxComplCallback = NULL; hspi->usTxXferCount = ulTxLen; //Invalid parameter check if (hspi->Init.ucCmdType == READ_CMD || hspi->Init.ucCmdType == CMD_WithResponse) { printf( "HAL_SPI_Transmit: Invalid parameter ucCmdType = %d received\r\n", hspi->Init.ucCmdType); unlock_spi1_bus(CTX_TASK); return HAL_ERROR; } //Disable chip SPI_Enable(hspi, 0); ulDomainClk = S3x_Clk_Get_Rate(S3X_A1_CLK); //check if the C02 domain is less than the request freq. If so, set the BAUDR to 2. if(ulDomainClk <= hspi->Init.ucFreq) { SPI_MS->BAUDR = 2; } else { SPI_MS->BAUDR = ((ulDomainClk/hspi->Init.ucFreq) & 0x1) ? ((ulDomainClk/hspi->Init.ucFreq) + 1) : (ulDomainClk/hspi->Init.ucFreq); } //slave select disable SPI_MS->SER = 0; //update the spi transfer mode if (hspi->Init.ucCmdType == PROGRAM_CMD) { SPI_MS->CTRLR0 = (CTRLR0_TMOD_TX | CTRLR0_DFS_16_BIT | (hspi->Init.ulCLKPolarity << BYTE_IDX_7) | (hspi->Init.ulCLKPhase << BYTE_IDX_6)); } else if (hspi->Init.ucCmdType == CMD_NoResponse) { SPI_MS->CTRLR0 = (CTRLR0_TMOD_TX | CTRLR0_DFS_8_BIT | (hspi->Init.ulCLKPolarity << BYTE_IDX_7) | (hspi->Init.ulCLKPhase << BYTE_IDX_6)); } //Disable SPI master interrupts SPI_MS->IMR = ((SPI_MS->IMR) & ~(ISR_TXEIM_ACTIVE)); //Enable SPI SPI_Enable(hspi, 1); do { hspi->usTxXferSize = (hspi->usTxXferCount <= SPI1_XFER_LEN_MAX) ? hspi->usTxXferCount : SPI1_XFER_LEN_MAX; if((hspi->usTxXferCount <= SPI1_XFER_LEN_MAX) && HAL_SPI_Callback) hspi->HAL_SPI_TxRxComplCallback = HAL_SPI_Callback; else hspi->State = HAL_SPI_STATE_TX_BUSY; //Enable the SPI_MS interrupt SPI_FiFoWrite(hspi); SPI_MS->IMR |= ISR_TXEIM_ACTIVE; //Enable interrupts if(hspi->State == HAL_SPI_STATE_TX_BUSY) { /* block until xWaitForIntr semaphore is given from IAR after * transction is complete */ if (xSemaphoreTake(xWaitForIntr, portMAX_DELAY) != pdTRUE) { printf("[HAL SPI] : Error unable to take lock to spibus1\n"); return HAL_TIMEOUT; } hspi->State = HAL_SPI_STATE_READY; } hspi->pTxBuffer = hspi->pTxBuffer + hspi->usTxXferSize; hspi->usTxXferCount -= hspi->usTxXferSize; } while (hspi->usTxXferCount > 0); if (!hspi->HAL_SPI_TxRxComplCallback) { //Disable chip SPI_MS->SSIENR = SSIENR_SSI_DISABLE; //slave select disable SPI_MS->SER = 0; unlock_spi1_bus(CTX_TASK); } return HAL_OK; } HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, UINT8_t *pTxData, const UINT32_t usTxSize, UINT8_t *pRxData, const UINT32_t usRxSize, void (*HAL_SPI_Callback)(void)) { UINT32_t ulDomainClk = 0; if (pTxData == NULL || pRxData == NULL || usTxSize == 0 || usRxSize == 0) return HAL_ERROR; lock_spi1_bus(); assert_param(IS_SPI_SSN_VALID(hspi->Init.ucSSn)); assert_param(IS_SPIx_VALID(hspi->ucSPIx)); SPIHandle = hspi; //Initialize the structure hspi->pTxBuffer = pTxData; hspi->pRxBuffer = pRxData; hspi->usTxXferSize = usTxSize; hspi->usTxXferCount = usTxSize; hspi->usRxXferCount = usRxSize; hspi->usRxXferSize = usRxSize; hspi->TxISR = NULL; hspi->RxISR = NULL; //Invalid parameter check if (hspi->Init.ucCmdType == CMD_NoResponse || hspi->Init.ucCmdType == PROGRAM_CMD) { printf("HAL_SPI_TransmitReceive: Invalid CmdType = %d \r\n",hspi->Init.ucCmdType); unlock_spi1_bus(CTX_TASK); return HAL_ERROR; } //Disable chip SPI_MS->SSIENR = SSIENR_SSI_DISABLE; ulDomainClk = S3x_Clk_Get_Rate(S3X_A1_CLK); //check if the C02 domain is less than the request freq. If so, set the BAUDR to 2. if(ulDomainClk <= hspi->Init.ucFreq) { SPI_MS->BAUDR = 2; } else { SPI_MS->BAUDR = ((ulDomainClk/hspi->Init.ucFreq) & 0x1) ? ((ulDomainClk/hspi->Init.ucFreq) + 1) : (ulDomainClk/hspi->Init.ucFreq); } //slave select enable SPI_MS->SER = 0; //Disable SPI master interrupts SPI_MS->IMR = ((SPI_MS->IMR) & ~(ISR_TXEIM_ACTIVE)); //configure the SPI transfer mode if (hspi->Init.ucCmdType == CMD_WithResponse) { SPI_MS->CTRLR0 = (CTRLR0_TMOD_EEPROM | CTRLR0_DFS_8_BIT | (hspi->Init.ulCLKPolarity << BYTE_IDX_7) | (hspi->Init.ulCLKPhase << BYTE_IDX_6)); SPI_MS->CTRLR1 = (hspi->usRxXferSize - 1); } else if (hspi->Init.ucCmdType == READ_CMD) { SPI_MS->CTRLR0 = (CTRLR0_TMOD_EEPROM | CTRLR0_DFS_8_BIT | (hspi->Init.ulCLKPolarity << BYTE_IDX_7) | (hspi->Init.ulCLKPhase << BYTE_IDX_6)); if(hspi->usRxXferSize % 4) SPI_MS->CTRLR1 = (((hspi->usRxXferSize + 3) / 4) * 4)-1; else SPI_MS->CTRLR1 = hspi->usRxXferSize - 1; //set the DMA destination address DMA_SPI_MS->DMA_DEST_ADDR = (UINT32_t) pRxData; //set the DMA transfer count if(hspi->usRxXferSize % 4) DMA_SPI_MS->DMA_XFER_CNT = (((hspi->usRxXferSize + 3) / 4) * 4)-1; else DMA_SPI_MS->DMA_XFER_CNT = hspi->usRxXferSize - 1; //Enable DMA interrupts DMA_SPI_MS->DMA_INTR_MASK = DMA_RX_DATA_AVAIL_INTR_MSK; //Enable the RX FIFO Full interrupt for DMA to run SPI_MS->IMR |= ISR_RXFIM_ACTIVE; } //Enable SPI //SPI_MS->SSIENR = SSIENR_SSI_EN; /*Fix : Enable SPI after DMA Enable*/ //poll for TxFifo Empty SPI_PollTxFifoEmptyFlag(); if (hspi->Init.ucCmdType == READ_CMD) { if(HAL_SPI_Callback) {//non blocking callback from ISR hspi->HAL_SPI_TxRxComplCallback = HAL_SPI_Callback; } else//Blocking mode ISR will signal completion { hspi->State = HAL_SPI_STATE_RX_BUSY; hspi->HAL_SPI_TxRxComplCallback = NULL; } //enable DMA for read DMA_SPI_MS->DMA_CTRL = DMA_CTRL_START_BIT; } //Enable SPI SPI_MS->SSIENR = SSIENR_SSI_EN; // For EEPROM tranfer mode, Tx FIFO must be filled without interruptions taskENTER_CRITICAL(); SPI_FiFoWrite(hspi); taskEXIT_CRITICAL(); //poll for TxFifo Empty SPI_PollTxFifoEmptyFlag(); if (hspi->Init.ucCmdType == CMD_WithResponse) { SPI_FiFoRead(hspi); unlock_spi1_bus(CTX_TASK); } else if(hspi->State == HAL_SPI_STATE_RX_BUSY) { if (xSemaphoreTake(xWaitForIntr, 1000 /* portMAX_DELAY */) != pdTRUE) { printf("[HAL SPI] : Error unable to take lock to spibus1\n"); unlock_spi1_bus(CTX_TASK); return HAL_TIMEOUT; } hspi->State = HAL_SPI_STATE_READY; unlock_spi1_bus(CTX_TASK); } return HAL_OK; } /*! *\fn HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, UINT8_t *pRxData,UINT16_t usRxSize, void (*HAL_SPI_Callback)(void)) *\brief Read an amount of data *\param hspi --- SPI handle *\param pRxData --- Pointer to data buffer *\param usRxSize --- amount of data to be read *\param callback function *\return HAL status */ HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, UINT8_t *pRxData,const UINT16_t usRxSize, void (*HAL_SPI_RxCompCallback)(void)) { UINT32_t ulDomainClk = 0; if (pRxData == NULL || usRxSize == 0) return HAL_ERROR; lock_spi1_bus(); assert_param(IS_SPI_SSN_VALID(hspi->Init.ucSSn)); assert_param(IS_SPIx_VALID(hspi->ucSPIx)); SPIHandle = hspi; //Initialize the structure hspi->pRxBuffer = pRxData; hspi->usRxXferCount = usRxSize; hspi->usRxXferSize = usRxSize; hspi->pTxBuffer = NULL; hspi->usTxXferCount = 0; hspi->usTxXferSize = 0; hspi->TxISR = NULL; hspi->RxISR = NULL; //Invalid parameter check if (hspi->Init.ucCmdType != READ_CMD) { printf("HAL_SPI_ReceiveOnly: Invalid CmdType = %d\r\n",hspi->Init.ucCmdType); unlock_spi1_bus(CTX_TASK); return HAL_ERROR; } //Disable chip SPI_MS->SSIENR = SSIENR_SSI_DISABLE; ulDomainClk = S3x_Clk_Get_Rate(S3X_A1_CLK); //check if the C02 domain is less than the request freq. If so, set the BAUDR to 2. if(ulDomainClk <= hspi->Init.ucFreq) { SPI_MS->BAUDR = 2; } else { SPI_MS->BAUDR = ((ulDomainClk/hspi->Init.ucFreq) & 0x1) ? ((ulDomainClk/hspi->Init.ucFreq) + 1) : (ulDomainClk/hspi->Init.ucFreq); } //slave select enable /* Thsi should come as input param*/ SPI_MS->SER = 0; //Disable SPI master interrupts SPI_MS->IMR = ((SPI_MS->IMR) & ~(ISR_TXEIM_ACTIVE)); //update the spi transfer mode SPI_MS->CTRLR0 = (CTRLR0_TMOD_RX | CTRLR0_DFS_8_BIT | (hspi->Init.ulCLKPolarity << BYTE_IDX_7) | (hspi->Init.ulCLKPhase << BYTE_IDX_6)); //use DMA if the read count is multiple of 4. Else use polling mode to read data if(hspi->usRxXferSize % 4) { //polling mode SPI_MS->CTRLR1 = hspi->usRxXferSize - 1; //Enable SPI SPI_MS->SSIENR = SSIENR_SSI_EN; SPI_FlashRead(hspi); if(HAL_SPI_RxCompCallback) HAL_SPI_RxCompCallback(); unlock_spi1_bus(CTX_TASK); } else { if(HAL_SPI_RxCompCallback)//non blocking callback from ISR hspi->HAL_SPI_TxRxComplCallback = HAL_SPI_RxCompCallback; else//Blocking mode ISR will signal completion hspi->State = HAL_SPI_STATE_RX_BUSY; //DMA mode SPI_MS->CTRLR1 = (hspi->usRxXferSize-1); //set the DMA destination address DMA_SPI_MS->DMA_DEST_ADDR = (UINT32_t) pRxData; //set the DMA transfer count DMA_SPI_MS->DMA_XFER_CNT = hspi->usRxXferSize - 1; //Enable DMA interrupts DMA_SPI_MS->DMA_INTR_MASK = DMA_RX_DATA_AVAIL_INTR_MSK; //Enable the RX FIFO Full interrupt for DMA to run SPI_MS->IMR |= ISR_RXFIM_ACTIVE; /* Tim SPI FIX - WED - 27/mar/19 */ taskENTER_CRITICAL(); //slave select enable if(hspi->Init.ucSSn == SPI_SLAVE_1_SELECT) SPI_MS->SER = SER_SS_0_N_SELECTED; else if(hspi->Init.ucSSn == SPI_SLAVE_2_SELECT) SPI_MS->SER = SER_SS_1_N_SELECTED; else SPI_MS->SER = SER_SS_2_N_SELECTED; //enable DMA for read DMA_SPI_MS->DMA_CTRL = DMA_CTRL_START_BIT; //Enable SPI SPI_MS->SSIENR = SSIENR_SSI_EN; SPI_MS->DR0 = 0; taskEXIT_CRITICAL(); if(hspi->State == HAL_SPI_STATE_RX_BUSY) { if (xSemaphoreTake(xWaitForIntr, portMAX_DELAY) != pdTRUE) { printf("[HAL SPI] : Error unable to take lock to spibus1\n"); unlock_spi1_bus(CTX_TASK); return HAL_TIMEOUT; } hspi->State = HAL_SPI_STATE_READY; unlock_spi1_bus(CTX_TASK); } } return HAL_OK; } /*! * \fn void SPI_DMA_Complete(SPI_HandleTypeDef *hspi) * \brief Callback for SPI Flash Read DMA complete * \param SPI Handle * \return None */ //void SPI_DMA_Complete(SPI_HandleTypeDef *hspi) { void SPI_DMA_Complete(void) { //Disable chip SPI_MS->SSIENR = SSIENR_SSI_DISABLE; //slave select enable SPI_MS->SER = 0; //Disable SPI master interrupts SPI_MS->IMR = ((SPI_MS->IMR) & ~(ISR_TXEIM_ACTIVE)); //Disable DMA interrupts DMA_SPI_MS->DMA_INTR_MASK &= ~(DMA_RX_DATA_AVAIL_INTR_MSK); //Stop DMA DMA_SPI_MS->DMA_CTRL = DMA_CTRL_STOP_BIT; if(SPIHandle->HAL_SPI_TxRxComplCallback) { SPIHandle->HAL_SPI_TxRxComplCallback(); unlock_spi1_bus(CTX_ISR); } if (SPIHandle->State == HAL_SPI_STATE_RX_BUSY) { BaseType_t xHigherPriorityTaskWoken = pdFALSE; if(xWaitForIntr) { if (xSemaphoreGiveFromISR(xWaitForIntr,&xHigherPriorityTaskWoken) == pdTRUE) { portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); } else printf("[HAL SPI] : Error : unable to release lock to spibus1\n"); } } } /*! *\fn void HAL_SPI_IRQHandler(SPI_HandleTypeDef *hspi) *\brief SPI Interrupt handler *\param hspi --- SPI handle */ void HAL_SPI_IRQHandler(void) { BaseType_t xHigherPriorityTaskWoken = pdFALSE; SPI_HandleTypeDef *hspi = SPIHandle; if (hspi->TxISR != NULL) hspi->TxISR(hspi); if (hspi->State == HAL_SPI_STATE_TX_BUSY) { if(xWaitForIntr) { if (xSemaphoreGiveFromISR(xWaitForIntr,&xHigherPriorityTaskWoken) == pdTRUE) { portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); } else printf("[HAL SPI] : Error : unable to release lock to spibus1\n"); } } else if(SPIHandle->HAL_SPI_TxRxComplCallback) { SPIHandle->HAL_SPI_TxRxComplCallback(); unlock_spi1_bus(CTX_ISR); } } /*! * \fn HAL_StatusTypeDef HAL_SPI_Init(SPI_HandleTypeDef *hspi) * \brief Initializes the SPI Master controller * \param hspi --- SPI handle * \return HAL status */ HAL_StatusTypeDef HAL_SPI_Init(SPI_HandleTypeDef *hspi) { UINT32_t ulDomainClk = 0; if (hspi == NULL) return HAL_ERROR; if(xLockSPI1Bus == NULL) { //printf("HAL SPI mutex created\r\n"); xLockSPI1Bus = xSemaphoreCreateBinary(); if( xLockSPI1Bus == NULL ) { //printf("[HAL SPI] : Error : Unable to Create Mutex\n"); return HAL_ERROR; } vQueueAddToRegistry(xLockSPI1Bus, "Spi_Lock" ); xSemaphoreGive(xLockSPI1Bus); } if(xWaitForIntr == NULL) { /* Note:: xSemaphoreTake(xWaitForIntr) causes the calling api to block * until xSemaphoreGiveFromISR(xWaitForIntr,&xHigherPriorityTaskWoken) is * called from ISR. This is used for blocking SPI transcation. */ xWaitForIntr = xSemaphoreCreateBinary(); if( xWaitForIntr == NULL ) { //printf("[HAL SPI] : Error : Unable to Create Mutex\n"); if(xLockSPI1Bus){ vSemaphoreDelete(xLockSPI1Bus); vQueueUnregisterQueue(xLockSPI1Bus); } xLockSPI1Bus = NULL; return HAL_ERROR; } vQueueAddToRegistry( xWaitForIntr, "Spi_WFI" ); } S3x_Clk_Enable(S3X_A1_CLK); //check the parameters assert_param(IS_SPI_DATASIZE(hspi->Init.ulDataSize)); assert_param(IS_SPI_CPOL(hspi->Init.ulCLKPolarity)); assert_param(IS_SPI_CPHA(hspi->Init.ulCLKPhase)); assert_param(IS_SPI_FIRST_BIT(hspi->Init.ulFirstBit)); assert_param(IS_SPI_BIDIR_MODE(hspi->Init.ucSPIInf)); //SPI configuration //Configure PADS for sensor SPI Master lines //SPI_PadConfig(); //part of hw setup //Disable chip SPI_MS->SSIENR = SSIENR_SSI_DISABLE; //clear pending SPI interrupts SPI_MS->ICR |= 0x01; //Configure Ctrl0 register SPI_MS->CTRLR0 |= ((hspi->Init.ulCLKPolarity << BYTE_IDX_7) | (hspi->Init.ulCLKPhase << BYTE_IDX_6)); //Baud rate divider (Pending) (max rate is 20Mhz) ulDomainClk = S3x_Clk_Get_Rate(S3X_A1_CLK); //check if the C02 domain is less than the request freq. If so, set the BAUDR to 2. if(ulDomainClk <= hspi->Init.ucFreq) { SPI_MS->BAUDR = 2; } else { SPI_MS->BAUDR = ((ulDomainClk/hspi->Init.ucFreq) & 0x1) ? ((ulDomainClk/hspi->Init.ucFreq) + 1) : (ulDomainClk/hspi->Init.ucFreq); } //clear the SPI_MS_INTR & CFG_DMA_DONE interrupts INTR_CTRL->OTHER_INTR &= (CFG_DMA_DONE_EN_M4 | SPI_MS_INTR_EN_M4); //Enable cfg dma interrupt INTR_CTRL->OTHER_INTR_EN_M4 |= CFG_DMA_DONE_EN_M4; INTR_CTRL->OTHER_INTR_EN_M4 |= SPI_MS_INTR_EN_M4; NVIC_ClearPendingIRQ(CfgDma_IRQn); NVIC_ClearPendingIRQ(SpiMs_IRQn); NVIC_EnableIRQ(CfgDma_IRQn); NVIC_EnableIRQ(SpiMs_IRQn); /*set spi handle*/ SPIHandle = hspi; S3x_Clk_Disable(S3X_A1_CLK); /* Increment the instance count */ SPI_Instance_count++; return HAL_OK; } /*! * \fn HAL_StatusTypeDef HAL_SPI_DeInit(SPI_HandleTypeDef *hspi) * \param hspi --- SPI Handle * \return HAL status */ HAL_StatusTypeDef HAL_SPI_DeInit(SPI_HandleTypeDef *hspi) { if (hspi == NULL) return HAL_ERROR; assert_param(IS_SPIx_VALID(hspi->ucSPIx)); S3x_Clk_Enable(S3X_A1_CLK); //Disable chip SPI_MS->SSIENR = SSIENR_SSI_DISABLE; SPI_Instance_count--; if(SPI_Instance_count == 0) /* if there are no other instances */ { if(xLockSPI1Bus){ vSemaphoreDelete(xLockSPI1Bus); vQueueUnregisterQueue(xLockSPI1Bus); } if(xWaitForIntr){ vSemaphoreDelete(xWaitForIntr); vQueueUnregisterQueue(xWaitForIntr); } xLockSPI1Bus = NULL; xWaitForIntr = NULL; } /*Clear SPI handle*/ SPIHandle = NULL; S3x_Clk_Disable(S3X_A1_CLK); return HAL_OK; } /*! * \fn static void SPI_FlashRead_Response(SPI_HandleTypeDef *hspi) * \brief Function to read SPI data register during SPI TransmitReceive2 (non-DMA) * \param hspi --- SPI handle */ static void SPI_FlashRead_Response(SPI_HandleTypeDef *hspi) { UINT8_t *rxbuf = (UINT8_t*) (hspi->pRxBuffer); UINT16_t len = hspi->usRxXferSize; int temp = 0; while (len > 0) { //Poll Rx FIFO Not Empty if (SPI_MS->SR & SR_RFNE) { *rxbuf++ = SPI_MS->DR0; len--; temp = 0; //reset the timeout } else { temp++; //Each byte has max 100 SPI Status reads time out //Note: SPI status reads over AHB bus are much slower than M4 bus reads. //So, this will make the bus busy all the time. But OK since no other Task //is working untill this is finished or task switch happens. if(temp > 100) { //Warning: there is no way to convey this error condition //to calling function while(len) { *rxbuf++ = 0; len--; } break; //error condition } } } } HAL_StatusTypeDef HAL_SPI_TransmitReceive2(SPI_HandleTypeDef *hspi, UINT8_t *pTxData, const UINT32_t usTxSize, UINT8_t *pRxData,const UINT32_t usRxSize, void (*HAL_SPI_TxRxComplCallback)(void)) { int iDomainClk = 0; if (pTxData == NULL || pRxData == NULL || usTxSize == 0 || usRxSize == 0) return HAL_ERROR; if (hspi->ucSPIx == SPI1_MASTER_SEL) { lock_spi1_bus(); } assert_param(IS_SPI_SSN_VALID(hspi->Init.ucSSn)); assert_param(IS_SPIx_VALID(hspi->ucSPIx)); SPIHandle = hspi; //Initialize the structure hspi->pTxBuffer = pTxData; hspi->pRxBuffer = pRxData; hspi->usTxXferSize = usTxSize; hspi->usTxXferCount = usTxSize; hspi->usRxXferCount = usRxSize; hspi->usRxXferSize = usRxSize; hspi->TxISR = NULL; hspi->RxISR = NULL; if(HAL_SPI_TxRxComplCallback) { configASSERT(0); } if (hspi->ucSPIx == SPI0_MASTER_SEL) { configASSERT(0); } else if (hspi->ucSPIx == SPI1_MASTER_SEL) { //Invalid parameter check if (hspi->Init.ucCmdType == CMD_NoResponse || hspi->Init.ucCmdType == PROGRAM_CMD) { //QL_LOG_ERR_150K("SPI_TxRx: Inval param CmdType = %d\r\n",hspi->Init.ucCmdType); unlock_spi1_bus(CTX_TASK); return HAL_ERROR; } //poll for TxFifo Empty before pushing new data SPI_PollTxFifoEmptyFlag(); //Disable chip SPI_MS->SSIENR = SSIENR_SSI_DISABLE; iDomainClk = S3x_Clk_Get_Rate(S3X_FB_02_CLK); //check if the C02 domain is less than the request freq. If so, set the BAUDR to 2. if(iDomainClk < hspi->Init.ucFreq) SPI_MS->BAUDR = 2; else SPI_MS->BAUDR = ((iDomainClk/hspi->Init.ucFreq) & 0x1) ? ((iDomainClk/hspi->Init.ucFreq) + 1) : (iDomainClk/hspi->Init.ucFreq); //slave select enable SPI_MS->SER = 0; //Disable SPI master interrupts SPI_MS->IMR = ((SPI_MS->IMR) & ~(ISR_TXEIM_ACTIVE)); //configure the SPI transfer mode if (hspi->Init.ucCmdType == CMD_WithResponse) { SPI_MS->CTRLR0 = (CTRLR0_TMOD_TX_RX | CTRLR0_DFS_8_BIT | (hspi->Init.ulCLKPolarity << BYTE_IDX_7) | (hspi->Init.ulCLKPhase << BYTE_IDX_6)); SPI_MS->CTRLR1 = (hspi->usRxXferSize - 1); } else if (hspi->Init.ucCmdType == READ_CMD) { SPI_MS->CTRLR0 = (CTRLR0_TMOD_TX_RX | CTRLR0_DFS_8_BIT | (hspi->Init.ulCLKPolarity << BYTE_IDX_7) | (hspi->Init.ulCLKPhase << BYTE_IDX_6)); SPI_MS->CTRLR1 = hspi->usRxXferSize - 1; if(HAL_SPI_TxRxComplCallback) { configASSERT(0); } } //Enable SPI SPI_MS->SSIENR = SSIENR_SSI_EN; //poll for TxFifo Empty before pushing new data SPI_PollTxFifoEmptyFlag(); SPI_FiFoWrite(hspi); if (hspi->Init.ucCmdType == READ_CMD) { SPI_FlashRead_Response(hspi); } if (!(hspi->Init.ucCmdType == READ_CMD && HAL_SPI_TxRxComplCallback) || (hspi->Init.ucCmdType == READ_CMD && !(HAL_SPI_TxRxComplCallback))) { unlock_spi1_bus(CTX_TASK); } return HAL_OK; } else { dbg_fatal_error("SPI_TxRx: Nosuprt in SPI1 master\r\n"); } return HAL_OK; } #endif
27.914547
152
0.62981
e96f1a196297daada192fc127b09bae6812fc3a6
1,005
h
C
linux-apps/lucene-r2p2/inc/lucene++/IntBlockPool.h
gsol10/r2p2
6305d2eb31a6ee87c7f873d0caa03b7a7df042b9
[ "MIT" ]
2
2015-09-23T13:25:57.000Z
2015-11-06T11:13:12.000Z
linux-apps/lucene-r2p2/inc/lucene++/IntBlockPool.h
gsol10/r2p2
6305d2eb31a6ee87c7f873d0caa03b7a7df042b9
[ "MIT" ]
1
2015-10-28T16:51:44.000Z
2015-11-06T11:13:03.000Z
linux-apps/lucene-r2p2/inc/lucene++/IntBlockPool.h
gsol10/r2p2
6305d2eb31a6ee87c7f873d0caa03b7a7df042b9
[ "MIT" ]
3
2015-10-12T15:26:56.000Z
2020-01-24T11:40:06.000Z
///////////////////////////////////////////////////////////////////////////// // Copyright (c) 2009-2014 Alan Wright. All rights reserved. // Distributable under the terms of either the Apache License (Version 2.0) // or the GNU Lesser General Public License. ///////////////////////////////////////////////////////////////////////////// #ifndef INTBLOCKPOOL_H #define INTBLOCKPOOL_H #include "LuceneObject.h" namespace Lucene { class IntBlockPool : public LuceneObject { public: IntBlockPool(const DocumentsWriterPtr& docWriter, bool trackAllocations); virtual ~IntBlockPool(); LUCENE_CLASS(IntBlockPool); public: Collection<IntArray> buffers; int32_t bufferUpto; // Which buffer we are upto int32_t intUpto; // Where we are in head buffer IntArray buffer; // Current head buffer int32_t intOffset; // Current head offset bool trackAllocations; protected: DocumentsWriterWeakPtr _docWriter; public: void reset(); void nextBuffer(); }; } #endif
23.928571
77
0.620896
e9db1fd23894618ea4b5c6fa5679c95779b91e78
1,120
h
C
NetFarmCommune/Libs/HJTabViewController/HJTabViewControllerPlugin_Base.h
JKrystalMH/NYN
03b4bd61a244a917cfe9fadf51b0909c607f9046
[ "Apache-2.0" ]
325
2017-03-16T12:06:58.000Z
2022-02-14T05:58:52.000Z
NetFarmCommune/Libs/HJTabViewController/HJTabViewControllerPlugin_Base.h
JKrystalMH/NYN
03b4bd61a244a917cfe9fadf51b0909c607f9046
[ "Apache-2.0" ]
34
2017-03-28T06:14:18.000Z
2020-08-09T11:25:50.000Z
NetFarmCommune/Libs/HJTabViewController/HJTabViewControllerPlugin_Base.h
JKrystalMH/NYN
03b4bd61a244a917cfe9fadf51b0909c607f9046
[ "Apache-2.0" ]
58
2017-03-20T06:39:39.000Z
2022-01-18T08:25:46.000Z
// // HJTabViewControllerPlugin_Base.h // HJTabViewControllerDemo // // Created by haijiao on 2017/3/14. // Copyright © 2017年 olinone. All rights reserved. // #import <UIKit/UIKit.h> #import <Foundation/Foundation.h> @class HJTabViewController; /* Subclasses can implement as necessary. The default is a nop. */ @protocol HJTabViewControllerPlugin <NSObject> - (void)scrollViewVerticalScroll:(CGFloat)contentPercentY; - (void)scrollViewHorizontalScroll:(CGFloat)contentOffsetX; - (void)scrollViewWillScrollFromIndex:(NSInteger)index; - (void)scrollViewDidScrollToIndex:(NSInteger)index; @end //_______________________________________________________________________________________________________________ @interface HJTabViewControllerPlugin_Base : NSObject <HJTabViewControllerPlugin> @property (nonatomic, assign) HJTabViewController *tabViewController; // Called only once when enable. Default does nothing - (void)initPlugin; // Called when tabViewController load. Default does nothing - (void)loadPlugin; // Called before tabViewController reload. Default does nothing - (void)removePlugin; @end
27.317073
113
0.80625
f5f883529681132f791af4ae67df38e86262b1b5
4,349
h
C
src/qt/transactionrecord.h
justthedoctor/PandaCoin2.0.2
519f1be73d96bb5c23c55874f98d6be7e227aea6
[ "MIT" ]
null
null
null
src/qt/transactionrecord.h
justthedoctor/PandaCoin2.0.2
519f1be73d96bb5c23c55874f98d6be7e227aea6
[ "MIT" ]
null
null
null
src/qt/transactionrecord.h
justthedoctor/PandaCoin2.0.2
519f1be73d96bb5c23c55874f98d6be7e227aea6
[ "MIT" ]
1
2019-03-02T16:15:37.000Z
2019-03-02T16:15:37.000Z
#ifndef TRANSACTIONRECORD_H #define TRANSACTIONRECORD_H #include "uint256.h" #include <QList> #ifdef __MINGW32__ #include <stdint.h> #endif #include <map> class CWallet; class CWalletTx; /** UI model for transaction status. The transaction status is the part of a transaction that will change over time. */ class TransactionStatus { public: TransactionStatus(): countsForBalance(false), sortKey(""), matures_in(0), status(Offline), depth(0), open_for(0), cur_num_blocks(-1) { } enum Status { Confirmed, /**< Have 6 or more confirmations (normal tx) or fully mature (mined tx) **/ /// Normal (sent/received) transactions OpenUntilDate, /**< Transaction not yet final, waiting for date */ OpenUntilBlock, /**< Transaction not yet final, waiting for block */ Offline, /**< Not sent to any other nodes **/ Unconfirmed, /**< Not yet mined into a block **/ Confirming, /**< Confirmed, but waiting for the recommended number of confirmations **/ Conflicted, /**< Conflicts with other transaction or mempool **/ /// Generated (mined) transactions Immature, /**< Mined but waiting for maturity */ MaturesWarning, /**< Transaction will likely not mature because no nodes have confirmed */ NotAccepted /**< Mined but not accepted */ }; /// Transaction counts towards available balance bool countsForBalance; /// Sorting key based on status std::string sortKey; /** @name Generated (mined) transactions @{*/ int matures_in; /**@}*/ /** @name Reported status @{*/ Status status; int64_t depth; int64_t open_for; /**< Timestamp if status==OpenUntilDate, otherwise number of blocks */ /**@}*/ /** Current number of blocks (to know whether cached status is still valid) */ int cur_num_blocks; }; /** UI model for a transaction. A core transaction can be represented by multiple UI transactions if it has multiple outputs. */ class TransactionRecord { public: enum Type { Other, Generated, SendToAddress, SendToOther, RecvWithAddress, RecvFromOther, InternalSend, InternalReceive }; /** Number of confirmation recommended for accepting a transaction */ static const int RecommendedNumConfirmations = 10; TransactionRecord() : hash() , time(0) , type(Other) , address("") , debit(0) , credit(0) , idx(0) { } TransactionRecord(uint256 hash, int64_t time) : hash(hash) , time(time) , type(Other) , address("") , debit(0) , credit(0) , idx(0) { } TransactionRecord(uint256 hash, int64_t time, Type type, const std::string &address, int64_t debit, int64_t credit) : hash(hash) , time(time) , type(type) , address(address) , debit(debit) , credit(credit) , idx(0) { } bool operator==(const TransactionRecord& comp) { return hash == comp.hash && time == comp.time && type == comp.type && debit == comp.debit && credit == comp.credit; } /** Decompose CWallet transaction to model transaction records. */ static bool showTransaction(const CWalletTx &wtx); static QList<TransactionRecord> decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx); /** @name Immutable transaction attributes @{*/ uint256 hash; qint64 time; Type type; std::string address; std::string fromAddress; qint64 debit; qint64 credit; /**@}*/ /** Subtransaction index, for sort key */ int idx; /** Status: can change with block chain update */ TransactionStatus status; /** Return the unique identifier for this transaction (part) */ std::string getTxID(); /** Update status from core wallet tx. */ void updateStatus(const CWalletTx &wtx); /** Return whether a status update is needed. */ bool statusUpdateNeeded(); int64_t getCachedBalance(std::string accountAddress) const; void setCachedBalance(std::string accountAddress, int64_t amount); private: std::map<std::string, int64_t> cachedBalance; }; #endif // TRANSACTIONRECORD_H
26.518293
123
0.624971
38ef82c91ec7ff7edc11a86af65b2893400d11b3
2,380
h
C
dev/Code/Tools/SceneAPI/FbxSceneBuilder/FbxSceneSystem.h
brianherrera/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Code/Tools/SceneAPI/FbxSceneBuilder/FbxSceneSystem.h
ArchitectureStudios/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Code/Tools/SceneAPI/FbxSceneBuilder/FbxSceneSystem.h
ArchitectureStudios/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
#pragma once /* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include <AzCore/Math/Transform.h> #include <AzCore/std/smart_ptr/unique_ptr.h> #include <SceneAPI/FbxSceneBuilder/FbxSceneBuilderConfiguration.h> namespace AZ { class Vector3; namespace FbxSDKWrapper { class FbxSceneWrapper; } namespace SceneAPI { class FbxSceneSystem { public: FBX_SCENE_BUILDER_API FbxSceneSystem(); FBX_SCENE_BUILDER_API void Set(const FbxSDKWrapper::FbxSceneWrapper& fbxScene); FBX_SCENE_BUILDER_API void SwapVec3ForUpAxis(Vector3& swapVector) const; FBX_SCENE_BUILDER_API void SwapTransformForUpAxis(Transform& inOutTransform) const; FBX_SCENE_BUILDER_API void ConvertUnit(Vector3& scaleVector) const; FBX_SCENE_BUILDER_API void ConvertUnit(Transform& inOutTransform) const; FBX_SCENE_BUILDER_API void ConvertBoneUnit(Transform& inOutTransform) const; //! Get effect unit size in meters of this Fbx Scene, internally FBX saves it in the following manner //! GlobalSettings: { //! P : "UnitScaleFactor", "double", "Number", "", 2.54 FBX_SCENE_BUILDER_API float GetUnitSizeInMeters() const { return m_unitSizeInMeters; } //! Get original unit size in meters of this Fbx Scene, internally FBX saves it in the following manner //! GlobalSettings: { //! P : "OriginalUnitScaleFactor", "double", "Number", "", 2.54 FBX_SCENE_BUILDER_API float GetOriginalUnitSizeInMeters() const { return m_originalUnitSizeInMeters; } protected: float m_unitSizeInMeters; float m_originalUnitSizeInMeters; AZStd::unique_ptr<Transform> m_adjustTransform; AZStd::unique_ptr<Transform> m_adjustTransformInverse; }; } };
40.338983
115
0.691176
759a2107a4f10e4fd4b6a9d138f81a9b4c83471a
771
h
C
patch_generator/include/VisualVerificator.h
beaupreda/cnn-rgbir
f2011ea72c577953c031164bbf3a866d8a409df6
[ "MIT" ]
3
2020-02-11T06:46:00.000Z
2022-03-21T09:26:32.000Z
patch_generator/include/VisualVerificator.h
beaupreda/cnn-rgbir
f2011ea72c577953c031164bbf3a866d8a409df6
[ "MIT" ]
null
null
null
patch_generator/include/VisualVerificator.h
beaupreda/cnn-rgbir
f2011ea72c577953c031164bbf3a866d8a409df6
[ "MIT" ]
null
null
null
#include <opencv2/opencv.hpp> #include "ImageReader.h" #ifndef PATCHGENERATOR_VISUALVERIFICATOR_H #define PATCHGENERATOR_VISUALVERIFICATOR_H class VisualVerificator { public: enum INFO {FRAME_NUMBER = 0, NUMBER = 1, RGB_CENTER_X = 2, RGB_CENTER_Y = 3, LWIR_CENTER_X = 4}; VisualVerificator(); void showPatches(int halfWidth, int halfRange, const std::vector<float>& patchInfo, const std::string& path, const std::string& extension); void showAllPoints(const std::vector<std::vector<float>>& points, const std::string& path, const std::string& extension); cv::Rect getRectangleFromCenter(int x, int y, int halfWidth, int halfRange, bool isRgb); private: ImageReader imgReader; }; #endif //PATCHGENERATOR_VISUALVERIFICATOR_H
38.55
125
0.7393
0e3341ed0cb276d1624286fb18a15b85c6c7bfcc
3,398
h
C
DataMgr/AbstractDataProvider.h
intel-go/omniscidb
86068a229beddf7b117febcacdbd6b60a0279282
[ "Apache-2.0" ]
2
2020-03-04T12:01:10.000Z
2020-07-24T15:12:55.000Z
DataMgr/AbstractDataProvider.h
intel-go/omniscidb
86068a229beddf7b117febcacdbd6b60a0279282
[ "Apache-2.0" ]
18
2019-11-20T11:11:19.000Z
2020-08-27T13:21:12.000Z
DataMgr/AbstractDataProvider.h
intel-go/omniscidb
86068a229beddf7b117febcacdbd6b60a0279282
[ "Apache-2.0" ]
1
2020-04-04T06:25:32.000Z
2020-04-04T06:25:32.000Z
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "AbstractBufferMgr.h" /** * This calss simply exists to hold all 'UNREACHABLE' definitions of * AbstractBufferMgr. This class should be removed when we have DataProvider * interface introduced. */ class AbstractDataProvider : public Data_Namespace::AbstractBufferMgr { public: AbstractDataProvider() : Data_Namespace::AbstractBufferMgr(0) {} Data_Namespace::AbstractBuffer* createBuffer(const ChunkKey& key, const size_t pageSize = 0, const size_t initialSize = 0) override { UNREACHABLE(); return nullptr; } void deleteBuffer(const ChunkKey& key, const bool purge = true) override { UNREACHABLE(); } void deleteBuffersWithPrefix(const ChunkKey& keyPrefix, const bool purge = true) override { UNREACHABLE(); } Data_Namespace::AbstractBuffer* getBuffer(const ChunkKey& key, const size_t numBytes = 0) override { UNREACHABLE(); return nullptr; } Data_Namespace::AbstractBuffer* putBuffer(const ChunkKey& key, Data_Namespace::AbstractBuffer* srcBuffer, const size_t numBytes = 0) override { UNREACHABLE(); return nullptr; } void getChunkMetadataVecForKeyPrefix(ChunkMetadataVector& chunkMetadataVec, const ChunkKey& keyPrefix) override { UNREACHABLE(); } bool isBufferOnDevice(const ChunkKey& key) override { UNREACHABLE(); return false; } std::string printSlabs() override { UNREACHABLE(); return ""; } size_t getMaxSize() override { UNREACHABLE(); return 0; } size_t getInUseSize() override { UNREACHABLE(); return 0; } size_t getAllocated() override { UNREACHABLE(); return 0; } bool isAllocationCapped() override { UNREACHABLE(); return false; } void checkpoint() override { UNREACHABLE(); } void checkpoint(const int db_id, const int tb_id) override { UNREACHABLE(); } void removeTableRelatedDS(const int db_id, const int table_id) override { UNREACHABLE(); } const DictDescriptor* getDictMetadata(int dict_id, bool load_dict = true) override { UNREACHABLE(); return nullptr; } Data_Namespace::AbstractBuffer* alloc(const size_t numBytes = 0) override { UNREACHABLE(); return nullptr; } void free(Data_Namespace::AbstractBuffer* buffer) override { UNREACHABLE(); } MgrType getMgrType() override { UNREACHABLE(); return static_cast<MgrType>(0); } std::string getStringMgrType() override { UNREACHABLE(); return ""; } size_t getNumChunks() override { UNREACHABLE(); return 0; } };
26.755906
87
0.647734
dbcc79057342e075b48baf406bb9bac21ac2653e
1,374
h
C
src/parser.h
d-kfmnn/teluma
65043166c29ab595db76b24307f4c87348f38914
[ "MIT" ]
null
null
null
src/parser.h
d-kfmnn/teluma
65043166c29ab595db76b24307f4c87348f38914
[ "MIT" ]
null
null
null
src/parser.h
d-kfmnn/teluma
65043166c29ab595db76b24307f4c87348f38914
[ "MIT" ]
null
null
null
/*------------------------------------------------------------------------*/ /*! \file parser.h \brief contains functions necessary to parse the AIG Part of TeluMA : AIG Multiplier Verification Tool. Copyright(C) 2021 Daniela Kaufmann, Johannes Kepler University Linz */ /*------------------------------------------------------------------------*/ #ifndef AMULET2_SRC_PARSER_H_ #define AMULET2_SRC_PARSER_H_ /*------------------------------------------------------------------------*/ #include "aig.h" /*------------------------------------------------------------------------*/ /** Checks whether 'model' contains an aiger node with output lhs and inputs rhs0 and rhs1. @param lhs unsigned integer @param rhs0 unsigned integer @param rhs1 unsigned integer @return True if 'model' contains such an aiger node */ bool match_and(unsigned lhs, unsigned rhs0, unsigned rhs1); /** Identifies whether the input vectors are separated or interleaved. */ void determine_input_order(); /** Checks whether the input AIG fullfills our requirements. */ void init_aiger_with_checks(); /** Reads the input aiger given in the file called input_name to the aiger 'model' using the parserer function of aiger.h @param input_name char * ame of input file */ void parse_aig(const char * input_name); #endif // AMULET2_SRC_PARSER_H_
29.869565
82
0.574236
370d2fb13ad5782bef6ee11f60a3e438f8ef7b9e
1,312
h
C
modules/segmentangling/processors/yixinloader.h
sathishkottravel/minimal-ct
4039c6d0f9fa9f69eb9a97b039f8ba7129420433
[ "BSD-3-Clause" ]
null
null
null
modules/segmentangling/processors/yixinloader.h
sathishkottravel/minimal-ct
4039c6d0f9fa9f69eb9a97b039f8ba7129420433
[ "BSD-3-Clause" ]
null
null
null
modules/segmentangling/processors/yixinloader.h
sathishkottravel/minimal-ct
4039c6d0f9fa9f69eb9a97b039f8ba7129420433
[ "BSD-3-Clause" ]
null
null
null
#ifndef __AB_YIXINLOADER_H__ #define __AB_YIXINLOADER_H__ #include <modules/segmentangling/segmentanglingmoduledefine.h> #include <inviwo/core/processors/processor.h> #include <inviwo/core/processors/progressbarowner.h> #include <inviwo/core/ports/volumeport.h> #include <inviwo/core/properties/ordinalproperty.h> #include <inviwo/core/properties/boolproperty.h> #include <inviwo/core/ports/meshport.h> #include <inviwo/core/datastructures/geometry/simplemesh.h> //#include <modules/segmentangling/util/constraintsstate.h> #include <deformation_constraints.h> #include <inviwo/core/properties/eventproperty.h> #include <inviwo/core/properties/cameraproperty.h> #include <inviwo/core/ports/imageport.h> #include <modules/segmentangling/common.h> #include <mutex> #include <thread> namespace inviwo { class IVW_MODULE_SEGMENTANGLING_API YixinLoader : public Processor { public: YixinLoader(); virtual ~YixinLoader() = default; virtual const ProcessorInfo getProcessorInfo() const override; static const ProcessorInfo processorInfo_; protected: virtual void process() override; void action(); private: VertexOutport _vertexOutport; TetIndexOutport _tetIndexOutport; FileProperty _file; ButtonProperty _action; }; } // namespace #endif // __AB_YIXINLOADER_H__
26.77551
68
0.785823
7765f4133b20aec7ef443f6b57a0e35b5eb7794e
1,062
h
C
generated/ZendEngine_3/optimizers/asin.zep.h
hlooalklampc/tss
23856e1e8244a89ac1bc30ba56b417a4a1c1687f
[ "MIT" ]
1
2022-02-02T16:59:28.000Z
2022-02-02T16:59:28.000Z
generated/ZendEngine_3/optimizers/asin.zep.h
hlooalklampc/tss
23856e1e8244a89ac1bc30ba56b417a4a1c1687f
[ "MIT" ]
null
null
null
generated/ZendEngine_3/optimizers/asin.zep.h
hlooalklampc/tss
23856e1e8244a89ac1bc30ba56b417a4a1c1687f
[ "MIT" ]
null
null
null
extern zend_class_entry *test_optimizers_asin_ce; ZEPHIR_INIT_CLASS(Test_Optimizers_ASin); PHP_METHOD(Test_Optimizers_ASin, testInt); PHP_METHOD(Test_Optimizers_ASin, testVar); PHP_METHOD(Test_Optimizers_ASin, testIntValue1); PHP_METHOD(Test_Optimizers_ASin, testIntParameter); PHP_METHOD(Test_Optimizers_ASin, testVarParameter); ZEND_BEGIN_ARG_INFO_EX(arginfo_test_optimizers_asin_testintparameter, 0, 0, 1) ZEND_ARG_INFO(0, a) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_test_optimizers_asin_testvarparameter, 0, 0, 1) ZEND_ARG_INFO(0, a) ZEND_END_ARG_INFO() ZEPHIR_INIT_FUNCS(test_optimizers_asin_method_entry) { PHP_ME(Test_Optimizers_ASin, testInt, NULL, ZEND_ACC_PUBLIC) PHP_ME(Test_Optimizers_ASin, testVar, NULL, ZEND_ACC_PUBLIC) PHP_ME(Test_Optimizers_ASin, testIntValue1, NULL, ZEND_ACC_PUBLIC) PHP_ME(Test_Optimizers_ASin, testIntParameter, arginfo_test_optimizers_asin_testintparameter, ZEND_ACC_PUBLIC) PHP_ME(Test_Optimizers_ASin, testVarParameter, arginfo_test_optimizers_asin_testvarparameter, ZEND_ACC_PUBLIC) PHP_FE_END };
37.928571
111
0.867232
472f3e7183f7bcb5bd989405bf2011349d55b679
239
c
C
ex05_hostname_get.c
sammtcbn/sccu
cbdb8c971f062b7eaff3a0efdfc25798c77f9f98
[ "MIT" ]
null
null
null
ex05_hostname_get.c
sammtcbn/sccu
cbdb8c971f062b7eaff3a0efdfc25798c77f9f98
[ "MIT" ]
null
null
null
ex05_hostname_get.c
sammtcbn/sccu
cbdb8c971f062b7eaff3a0efdfc25798c77f9f98
[ "MIT" ]
null
null
null
#include <stdio.h> #include "sccu.h" int main (void) { char hostnamebuf [SCCU_HOST_NAME_MAX_LEN + 1]; SCCU_hostname_get (hostnamebuf); printf ("%s\n", hostnamebuf); return 0; } /* Result: $ ./ex05_hostname_get sampc */
13.277778
50
0.65272
c28e6dd64ae126784d8882169dc9a4ad6795c686
3,838
h
C
src/cpp/api.h
donghaoren/lscg-solver
aacb16d362d9ffb6fe1ab20cea96a12d7cc102b0
[ "MIT" ]
13
2018-08-16T00:48:01.000Z
2022-03-14T16:13:43.000Z
src/cpp/api.h
donghaoren/lscg-solver
aacb16d362d9ffb6fe1ab20cea96a12d7cc102b0
[ "MIT" ]
1
2018-10-29T23:59:04.000Z
2018-10-29T23:59:04.000Z
src/cpp/api.h
donghaoren/lscg-solver
aacb16d362d9ffb6fe1ab20cea96a12d7cc102b0
[ "MIT" ]
5
2018-05-16T16:42:05.000Z
2019-03-11T16:26:29.000Z
#ifndef WASMSOLVER_API_H #define WASMSOLVER_API_H typedef double number_t; typedef int length_t; extern "C" { // Memory allocator void *memory_alloc(length_t length); void memory_free(float *pointer); // Linear algebra typedef struct matrix__ *matrix_t; matrix_t linalg_matrix_create(); void linalg_matrix_init(matrix_t matrix, length_t rows, length_t cols, number_t *values); void linalg_matrix_fill(matrix_t matrix, number_t value); void linalg_matrix_destroy(matrix_t matrix); number_t *linalg_matrix_data(matrix_t matrix); length_t linalg_matrix_size(matrix_t matrix); length_t linalg_matrix_rows(matrix_t matrix); length_t linalg_matrix_cols(matrix_t matrix); length_t linalg_matrix_col_stride(matrix_t matrix); length_t linalg_matrix_row_stride(matrix_t matrix); number_t linalg_matrix_norm(matrix_t matrix); number_t linalg_matrix_l1_norm(matrix_t matrix, int p); void linalg_matrix_add(matrix_t dest, matrix_t a, matrix_t b); void linalg_matrix_sub(matrix_t dest, matrix_t a, matrix_t b); void linalg_matrix_scale(matrix_t dest, matrix_t a, number_t scaler); void linalg_matrix_add_scale(matrix_t dest, matrix_t a, number_t a_scale, matrix_t b, number_t b_scale); void linalg_matrix_emul(matrix_t dest, matrix_t a, matrix_t b); void linalg_matrix_ediv(matrix_t dest, matrix_t a, matrix_t b); void linalg_matrix_mmul(matrix_t dest, matrix_t a, matrix_t b); void linalg_solve_linear_system(matrix_t X, matrix_t ker, matrix_t A, matrix_t B); // Constraint solver typedef struct solver__ *solver_t; solver_t solver_create(); void solver_destroy(solver_t solver); const int kSolverStrength_HARD = 0; const int kSolverStrength_STRONG = 1; const int kSolverStrength_MEDIUM = 2; const int kSolverStrength_WEAK = 3; const int kSolverStrength_WEAKER = 4; const int kSolverStrength_DISABLED = 10; const int kSolverAttribute_NUM_ITERATIONS = 1; const int kSolverAttribute_TOLERANCE = 2; const int kSolverAttribute_FLAGS = 3; const int kSolverAttribute_NUM_VARIABLES = 10; const int kSolverAttribute_NUM_CONSTRAINTS = 11; const int kSolverAttribute_MAX_ITERATIONS = 12; const int kSolverAttribute_ERROR = 13; const int kSolverAttribute_HARD_LOSS = 20; const int kSolverAttribute_SOFT_LOSS = 21; const int kSolverAttribute_REGULARIZER_WEIGHT = 30; const int kSolverFlag_DEFAULT = 0; const int kSolverFlag_REDUCE = 1 << 1; const int kSolverFlag_LAGRANGE = 1 << 2; void solver_add_variable(solver_t solver, int variable_name, number_t value, bool edit); void solver_make_constant(solver_t solver, int variable_name); int solver_add_constraint(solver_t solver, int strength, number_t bias, int count, int *variable_names, number_t *weights); void solver_add_constraint_coefficient(solver_t solver, int constraint, int variable_name, number_t weight); void solver_set_constraint_strength(solver_t solver, int constraint, int strength); void solver_set_constraint_bias(solver_t solver, int constraint, number_t bias); void solver_clear_constraint_coefficients(solver_t solver, int constraint); void solver_set_value(solver_t solver, int variable_name, number_t value); number_t solver_get_value(solver_t solver, int variable_name); void solver_set_values(solver_t solver, int count, const int *variable_names, const number_t *values); void solver_get_values(solver_t solver, int count, const int *variable_names, number_t *output); void solver_set_attribute_i(solver_t solver, int attribute, int value); void solver_set_attribute_f(solver_t solver, int attribute, number_t value); int solver_get_attribute_i(solver_t solver, int attribute); number_t solver_get_attribute_f(solver_t solver, int attribute); void solver_solve(solver_t solver); void solver_compute_loss(solver_t solver); } // extern "C" #endif
38
96
0.800677
46c30c1b02321e8e827fff913e813df57e97309c
1,413
c
C
_Books_/C - KNK/08 ARRAYS/Projects/{proj07}row_and_column_sums_of_multidimensional_array.c
JUD210/Study-Note
2add9db3f11d99370f49878f0c19e9caa60d2d02
[ "MIT" ]
null
null
null
_Books_/C - KNK/08 ARRAYS/Projects/{proj07}row_and_column_sums_of_multidimensional_array.c
JUD210/Study-Note
2add9db3f11d99370f49878f0c19e9caa60d2d02
[ "MIT" ]
null
null
null
_Books_/C - KNK/08 ARRAYS/Projects/{proj07}row_and_column_sums_of_multidimensional_array.c
JUD210/Study-Note
2add9db3f11d99370f49878f0c19e9caa60d2d02
[ "MIT" ]
null
null
null
/* Write a program that reads a 5*5 array of integers and then prints the row sums and the column sums: Enter row 1: 8 3 9 0 10 (input) Enter row 2: 3 5 17 1 1 (input) Enter row 3: 2 8 6 23 1 (input) Enter row 4: 15 7 3 2 9 (input) Enter row 5: 6 14 2 6 0 (input) Row totals: 30 27 40 36 28 Column totals: 34 37 37 32 21 */ #include <stdio.h> #define NUM_ROW 5 #define NUM_COLUMN 5 int main() { const int arr[NUM_ROW][NUM_COLUMN]; int sum; for (int row = 0; row < NUM_ROW; row++) { printf("Enter row %d (5 digits): ", row + 1); for (int column = 0; column < NUM_COLUMN; column++) { scanf("%d", &arr[row][column]); } } printf("\nRow totals: "); for (int row = 0; row < NUM_ROW; row++) { sum = 0; for (int column = 0; column < NUM_COLUMN; column++) { sum += arr[row][column]; } printf("%d ", sum); } printf("\nColumn totals: "); for (int column = 0; column < NUM_COLUMN; column++) { sum = 0; for (int row = 0; row < NUM_ROW; row++) { sum += arr[row][column]; } printf("%d ", sum); } return 0; } /* Enter row 1 (5 digits): 8 3 9 0 10 Enter row 2 (5 digits): 3 5 17 1 1 Enter row 3 (5 digits): 2 8 6 23 1 Enter row 4 (5 digits): 15 7 3 2 9 Enter row 5 (5 digits): 6 14 2 6 0 Row totals: 30 27 40 36 28 Column totals: 34 37 37 32 21 */
23.163934
103
0.547771
ee97b18d250f8a6785637ae3c2774453534cb370
1,422
c
C
uls/src/mx_outputX.c
PAXANDDOS/UCODE-Track-C
572f74f52e576d025946bffa5a47ca3b2dad9d5b
[ "MIT" ]
1
2021-11-02T10:25:29.000Z
2021-11-02T10:25:29.000Z
uls/src/mx_outputX.c
PAXANDDOS/UCODE-Track-C
572f74f52e576d025946bffa5a47ca3b2dad9d5b
[ "MIT" ]
null
null
null
uls/src/mx_outputX.c
PAXANDDOS/UCODE-Track-C
572f74f52e576d025946bffa5a47ca3b2dad9d5b
[ "MIT" ]
4
2021-06-02T12:57:01.000Z
2022-01-06T15:21:53.000Z
#include "uls.h" static void printcols_x(t_li **names, int rows, int cols, int maxlen) { int j = 0; int tempcols = cols; for (int i = 0; i < rows; i++, cols += tempcols) { for (; names[j] && j < cols; j++) { mx_printstr(names[j]->name); if (names[j + 1] && (j != cols - 1)) mx_print_tab(mx_strlen(names[j]->name), maxlen); } if (i != rows - 1) mx_printchar('\n'); } } static void print_names(t_li **names, int maxlen, int wincol) { int rows; int cols = (wincol / maxlen) != 0 ? wincol / maxlen : 1; int num = 0; for(;names[num]; num++) { } if (maxlen * cols > wincol && cols != 1) cols--; if (num * maxlen > wincol) { rows = num / cols; if (rows == 0 || num % cols != 0) rows += 1; printcols_x(names, rows, cols, maxlen); } else for (int i = 0; names[i]; i++) { mx_printstr(names[i]->name); if (names[i + 1]) mx_print_tab(mx_strlen(names[i]->name), maxlen); } mx_printchar('\n'); } void mx_output_x(t_li **names) { int maxlen; struct winsize win; if (!names) return; maxlen = max_len_names(names); ioctl(STDOUT_FILENO, TIOCGWINSZ, &win); if (isatty(1)) print_names(names, maxlen, win.ws_col); else print_names(names, maxlen, 80); }
26.333333
71
0.504219
5441148765dc61d461a061ddc53c6a3209bb7b7e
1,056
c
C
libs/utils/src/json_packet_former.c
Vladddd46/uchat
5f197382e498f7a6a0c6fb8c26db698b522c0ce5
[ "MIT" ]
7
2020-06-01T23:42:19.000Z
2020-12-04T08:30:45.000Z
libs/utils/src/json_packet_former.c
Vladddd46/uchat
5f197382e498f7a6a0c6fb8c26db698b522c0ce5
[ "MIT" ]
null
null
null
libs/utils/src/json_packet_former.c
Vladddd46/uchat
5f197382e498f7a6a0c6fb8c26db698b522c0ce5
[ "MIT" ]
4
2020-06-17T02:28:09.000Z
2020-11-25T15:11:03.000Z
#include "utils.h" /* * Creates json string by given values. * Takes undefined number of str. arguments. "key:value". * Returns string in json format: {'key': 'value', ..., 'keyX':'valueX'} */ static int json_error(cJSON *object) { if (object == NULL) { cJSON_Delete(object); return 1; } return 0; } char *json_packet_former(int num, ...) { va_list valist; va_start(valist, num); char *key; char *value; cJSON *packet = cJSON_CreateObject(); char *packet_str = NULL; for (int i = 0; i < num; ++i) { char *str = va_arg(valist, char *); char **arg = mx_strsplit(str, ':'); key = arg[0]; value = arg[1]; cJSON *json_value = cJSON_CreateString(value); cJSON_AddItemToObject(packet, key, json_value); if (json_error(json_value)) return NULL; } packet_str = cJSON_Print(packet); // cJSON_Delete(packet); // ??? after 5 iterations there was malloc error. va_end(valist); return packet_str; }
24
78
0.581439
7b420ac0797ee82abc621a9e3568be10e49244f1
2,567
h
C
include/Phobos/Game/BaseOgreWorld.h
CronosTs/phobos3d
c0336456d946f3a9e62fb9b7815831ad32820da5
[ "Zlib" ]
2
2015-01-14T20:20:51.000Z
2015-09-08T15:49:18.000Z
include/Phobos/Game/BaseOgreWorld.h
CronosTs/phobos3d
c0336456d946f3a9e62fb9b7815831ad32820da5
[ "Zlib" ]
null
null
null
include/Phobos/Game/BaseOgreWorld.h
CronosTs/phobos3d
c0336456d946f3a9e62fb9b7815831ad32820da5
[ "Zlib" ]
1
2015-11-03T13:58:58.000Z
2015-11-03T13:58:58.000Z
/* Phobos 3d May 2012 Copyright (c) 2005-2012 Bruno Sanches http://code.google.com/p/phobos3d 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 PH_GAME_BASE_OGRE_WORLD_H #define PH_GAME_BASE_OGRE_WORLD_H #include "Phobos/Game/World.h" #include <OgrePrerequisites.h> #include <Phobos/String.h> #include <Phobos/OgreEngine/Math/TransformFwd.h> #include "Physics/CollisionTagFwd.h" #include "Physics/RigidBodyFwd.h" #define PH_WORLD_SCENE_MANAGER_NAME "SceneManager" namespace Phobos { namespace Game { class PH_GAME_API BaseOgreWorld: public World { protected: struct StaticObject_s { String_t strParent; Ogre::SceneNode *m_pclSceneNode; Ogre::Entity *m_pclEntity; Ogre::Light *m_pclLight; Physics::RigidBodyPtr_t m_spRigidBody; void Clear(); inline StaticObject_s(): m_pclSceneNode(NULL), m_pclEntity(NULL), m_pclLight(NULL) { //empty } }; struct TempStaticObject_s { Ogre::Entity *m_pclEntity; Ogre::SceneNode *m_pclSceneNode; Ogre::Light *m_pclLight; bool m_fParent; String_t m_strName; TempStaticObject_s(): m_pclEntity(NULL), m_pclSceneNode(NULL), m_pclLight(NULL), m_fParent(false) { } inline void Commit(StaticObject_s &object) { object.m_pclEntity = m_pclEntity; object.m_pclSceneNode = m_pclSceneNode; object.m_pclLight = m_pclLight; m_pclEntity = NULL; m_pclLight = NULL; m_pclSceneNode = NULL; } ~TempStaticObject_s(); }; void CreateStaticObjectRigidBody(StaticObject_s &staticObj, const Engine::Math::Transform &transform, const Ogre::Vector3 &scale, const Physics::CollisionTag &collisionTag) const; }; } } #endif
26.193878
243
0.714453
7b82be995486d3376859edb50c0f98414b18b9c6
6,276
h
C
Includes/Core/SPH/SPHSystemData3.h
utilForever/CubbyFlow-v1
d85c136d8eaa91ecce456c3356c7e578dda5d5bd
[ "MIT" ]
3
2020-04-15T13:41:16.000Z
2020-12-29T11:23:59.000Z
Includes/Core/SPH/SPHSystemData3.h
utilForever/CubbyFlow-v1
d85c136d8eaa91ecce456c3356c7e578dda5d5bd
[ "MIT" ]
null
null
null
Includes/Core/SPH/SPHSystemData3.h
utilForever/CubbyFlow-v1
d85c136d8eaa91ecce456c3356c7e578dda5d5bd
[ "MIT" ]
null
null
null
/************************************************************************* > File Name: SPHSystemData3.h > Project Name: CubbyFlow > Author: Chan-Ho Chris Ohk > Purpose: 3-D SPH particle system data. > Created Time: 2017/05/31 > Copyright (c) 2018, Chan-Ho Chris Ohk *************************************************************************/ #ifndef CUBBYFLOW_SPH_SYSTEM_DATA3_H #define CUBBYFLOW_SPH_SYSTEM_DATA3_H #include <Core/Particle/ParticleSystemData3.h> namespace CubbyFlow { //! //! \brief 3-D SPH particle system data. //! //! This class extends ParticleSystemData3 to specialize the data model for SPH. //! It includes density and pressure array as a default particle attribute, and //! it also contains SPH utilities such as interpolation operator. //! class SPHSystemData3 : public ParticleSystemData3 { public: //! Constructs empty SPH system. SPHSystemData3(); //! Constructs SPH system data with given number of particles. explicit SPHSystemData3(size_t numberOfParticles); //! Copy constructor. SPHSystemData3(const SPHSystemData3& other); //! Destructor. virtual ~SPHSystemData3(); //! //! \brief Sets the radius. //! //! Sets the radius of the particle system. The radius will be interpreted //! as target spacing. //! void SetRadius(double newRadius) override; //! //! \brief Sets the mass of a particle. //! //! Setting the mass of a particle will change the target density. //! //! \param[in] newMass The new mass. //! void SetMass(double newMass) override; //! Returns the density array accessor (immutable). ConstArrayAccessor1<double> GetDensities() const; //! Returns the density array accessor (mutable). ArrayAccessor1<double> GetDensities(); //! Returns the pressure array accessor (immutable). ConstArrayAccessor1<double> GetPressures() const; //! Returns the pressure array accessor (mutable). ArrayAccessor1<double> GetPressures(); //! Updates the density array with the latest particle positions. void UpdateDensities(); //! Sets the target density of this particle system. void SetTargetDensity(double targetDensity); //! Returns the target density of this particle system. double GetTargetDensity() const; //! //! \brief Sets the target particle spacing in meters. //! //! Once this function is called, hash grid and density should be //! updated using UpdateHashGrid() and UpdateDensities). //! void SetTargetSpacing(double spacing); //! Returns the target particle spacing in meters. double GetTargetSpacing() const; //! //! \brief Sets the relative kernel radius. //! //! Sets the relative kernel radius compared to the target particle //! spacing (i.e. kernel radius / target spacing). //! Once this function is called, hash grid and density should //! be updated using UpdateHashGrid() and UpdateDensities). //! void SetRelativeKernelRadius(double relativeRadius); //! //! \brief Returns the relative kernel radius. //! //! Returns the relative kernel radius compared to the target particle //! spacing (i.e. kernel radius / target spacing). //! double GetRelativeKernelRadius() const; //! //! \brief Sets the absolute kernel radius. //! //! Sets the absolute kernel radius compared to the target particle //! spacing (i.e. relative kernel radius * target spacing). //! Once this function is called, hash grid and density should //! be updated using UpdateHashGrid() and UpdateDensities). //! void SetKernelRadius(double kernelRadius); //! Returns the kernel radius in meters unit. double GetKernelRadius() const; //! Returns sum of kernel function evaluation for each nearby particle. double SumOfKernelNearby(const Vector3D& position) const; //! //! \brief Returns interpolated value at given origin point. //! //! Returns interpolated scalar data from the given position using //! standard SPH weighted average. The data array should match the //! particle layout. For example, density or pressure arrays can be //! used. //! double Interpolate(const Vector3D& origin, const ConstArrayAccessor1<double>& values) const; //! //! \brief Returns interpolated vector value at given origin point. //! //! Returns interpolated vector data from the given position using //! standard SPH weighted average. The data array should match the //! particle layout. For example, velocity or acceleration arrays can be //! used. //! Vector3D Interpolate(const Vector3D& origin, const ConstArrayAccessor1<Vector3D>& values) const; //! Returns the gradient of the given values at i-th particle. Vector3D GradientAt(size_t i, const ConstArrayAccessor1<double>& values) const; //! Returns the Laplacian of the given values at i-th particle. double LaplacianAt(size_t i, const ConstArrayAccessor1<double>& values) const; //! Returns the Laplacian of the given values at i-th particle. Vector3D LaplacianAt(size_t i, const ConstArrayAccessor1<Vector3D>& values) const; //! Builds neighbor searcher with kernel radius. void BuildNeighborSearcher(); //! Builds neighbor lists with kernel radius. void BuildNeighborLists(); //! Serializes this SPH system data to the buffer. void Serialize(std::vector<uint8_t>* buffer) const override; //! Deserializes this SPH system data from the buffer. void Deserialize(const std::vector<uint8_t>& buffer) override; //! Copies from other SPH system data. void Set(const SPHSystemData3& other); //! Copies from other SPH system data. SPHSystemData3& operator=(const SPHSystemData3& other); private: //! Target density of this particle system in kg/m^3. double m_targetDensity = WATER_DENSITY; //! Target spacing of this particle system in meters. double m_targetSpacing = 0.1; //! Relative radius of SPH kernel. //! SPH kernel radius divided by target spacing. double m_kernelRadiusOverTargetSpacing = 1.8; //! SPH kernel radius in meters. double m_kernelRadius; size_t m_pressureIdx; size_t m_densityIdx; //! Computes the mass based on the target density and spacing. void ComputeMass(); }; //! Shared pointer for the SPHSystemData3 type. using SPHSystemData3Ptr = std::shared_ptr<SPHSystemData3>; } #endif
32.350515
98
0.707935
7ba1286fa32ce4399639c662768b114d35619137
6,623
h
C
NurAPIBluetooth.xcframework/ios-arm64/NurAPIBluetooth.framework/Headers/NurAPIBootloader.h
NordicID/nur_sample_ios
7ede5938434e1c75d4d33140e9b09d7adc8b471a
[ "MIT" ]
4
2017-01-05T07:55:19.000Z
2019-08-29T00:42:30.000Z
NurAPIBluetooth.xcframework/ios-arm64_x86_64-simulator/NurAPIBluetooth.framework/Headers/NurAPIBootloader.h
NordicID/nur_sample_ios
7ede5938434e1c75d4d33140e9b09d7adc8b471a
[ "MIT" ]
10
2018-04-19T22:11:13.000Z
2021-05-08T05:36:28.000Z
NurAPIBluetooth.xcframework/ios-arm64_x86_64-simulator/NurAPIBluetooth.framework/Headers/NurAPIBootloader.h
NordicID/nur_sample_ios
7ede5938434e1c75d4d33140e9b09d7adc8b471a
[ "MIT" ]
5
2018-04-19T07:13:05.000Z
2021-05-10T02:07:43.000Z
#ifndef _NURAPI_BOOTLOADER_H_ #define _NURAPI_BOOTLOADER_H_ 1 #ifdef __cplusplus extern "C" { #endif /** @defgroup INTERNALAPI NUR Internal API * Internal API for NUR module bootloader * @{ */ #define NUR_MAX_SERIAL_LENGTH (16) #define NUR_MAX_NAME_LENGTH (16) #define NUR_MAX_FCCID_LENGTH (48) #define NUR_MAX_HWVER_LENGTH (8) #define NUR_VARIANT_FLAG_NONE 0 #define NUR_VARIANT_FLAG_USB_TABLE (1<<0) #define NUR_VARIANT_FLAG_ETH_TABLE (1<<1) #define NUR_VARIANT_FLAG_STIX (1<<2) #define _DO_NOT_USE_NUR_VARIANT_FLAG_ONEWATT_ (1<<3) // Removed #define _DO_NOT_USE_NUR_VARIANT_FLAG_GRIDANT_ (1<<4) // Removed #define NUR_VARIANT_FLAG_ONEWATT (1<<5) #define NUR_VARIANT_FLAG_BEAMANT (1<<6) #define NUR_VARIANT_FLAG_MULTIPORT (1<<7) #define NUR_VARIANT_BEAM_READER_EB (1<<8) #define NUR_VARIANT_BEAM_READER_EB2 (1<<9) #define NUR_VARIANT_AR_LOWGAIN (1<<10) #define NUR_VARIANT_4PORT (1<<11) #define NUR_VARIANT_HAS_TEMPSENSOR (1<<12) #define NUR_VARIANT_ZUMTOBEL_READER (1<<13) #define NUR_MAX_SEND_SZ ((2*1024)-1) #define NUR_MAX_RCV_SZ ((32*1024)-1) #define CRYPTO_PERMISSION_LENGTH 32 struct NUR_SCANCHANNEL_INFO { DWORD freq; int rssi; int rawiq; }; struct NUR_REFLECTEDPOWER_INFO { int iPart; int qPart; int div; }; struct NUR_REFLECTEDPOWER_INFO_EX { int iPart; int qPart; int div; DWORD freqKhz; }; struct NUR_VARIANT_INFO { BOOL usbtablereader; TCHAR serial[NUR_MAX_SERIAL_LENGTH]; TCHAR altSerial[NUR_MAX_SERIAL_LENGTH]; TCHAR name[NUR_MAX_NAME_LENGTH]; TCHAR fccId[NUR_MAX_FCCID_LENGTH]; }; struct NUR_VARIANT_INFO2 { BOOL usbtablereader; TCHAR serial[NUR_MAX_SERIAL_LENGTH+1]; // + NULL TCHAR altSerial[NUR_MAX_SERIAL_LENGTH+1]; // + NULL TCHAR name[NUR_MAX_NAME_LENGTH+1]; // + NULL TCHAR fccId[NUR_MAX_FCCID_LENGTH+1]; // + NULL TCHAR hwVer[NUR_MAX_HWVER_LENGTH+1]; // + NULL }; struct NUR_VARIANT_INFO3 { BOOL usbtablereader; TCHAR serial[NUR_MAX_SERIAL_LENGTH+1]; // + NULL TCHAR altSerial[NUR_MAX_SERIAL_LENGTH+1]; // + NULL TCHAR name[NUR_MAX_NAME_LENGTH+1]; // + NULL TCHAR fccId[NUR_MAX_FCCID_LENGTH+1]; // + NULL TCHAR hwVer[NUR_MAX_HWVER_LENGTH+1]; // + NULL BOOL ethtablereader; }; struct NUR_VARIANT_INFO4 { BOOL usbtablereader; TCHAR serial[NUR_MAX_SERIAL_LENGTH+1]; // + NULL TCHAR altSerial[NUR_MAX_SERIAL_LENGTH+1]; // + NULL TCHAR name[NUR_MAX_NAME_LENGTH+1]; // + NULL TCHAR fccId[NUR_MAX_FCCID_LENGTH+1]; // + NULL TCHAR hwVer[NUR_MAX_HWVER_LENGTH+1]; // + NULL BOOL ethtablereader; BOOL onewattreader; BOOL beamreader; }; struct NUR_VARIANT_INFO5 { BOOL usbtablereader; TCHAR serial[NUR_MAX_SERIAL_LENGTH+1]; // + NULL TCHAR altSerial[NUR_MAX_SERIAL_LENGTH+1]; // + NULL TCHAR name[NUR_MAX_NAME_LENGTH+1]; // + NULL TCHAR fccId[NUR_MAX_FCCID_LENGTH+1]; // + NULL TCHAR hwVer[NUR_MAX_HWVER_LENGTH+1]; // + NULL BOOL ethtablereader; BOOL onewattreader; BOOL beamreader; BOOL stixreader; }; struct NUR_VARIANT_INFO6 { BOOL usbtablereader; TCHAR serial[NUR_MAX_SERIAL_LENGTH+1]; // + NULL TCHAR altSerial[NUR_MAX_SERIAL_LENGTH+1]; // + NULL TCHAR name[NUR_MAX_NAME_LENGTH+1]; // + NULL TCHAR fccId[NUR_MAX_FCCID_LENGTH+1]; // + NULL TCHAR hwVer[NUR_MAX_HWVER_LENGTH+1]; // + NULL BOOL ethtablereader; BOOL onewattreader; BOOL beamreader; BOOL stixreader; BOOL multiport; }; struct NUR_VARIANT_INFO7 { BOOL usbtablereader; TCHAR serial[NUR_MAX_SERIAL_LENGTH+1]; // + NULL TCHAR altSerial[NUR_MAX_SERIAL_LENGTH+1]; // + NULL TCHAR name[NUR_MAX_NAME_LENGTH+1]; // + NULL TCHAR fccId[NUR_MAX_FCCID_LENGTH+1]; // + NULL TCHAR hwVer[NUR_MAX_HWVER_LENGTH+1]; // + NULL BOOL ethtablereader; BOOL onewattreader; BOOL beamreader; BOOL stixreader; BOOL multiport; BOOL extrabeam; BOOL extrabeam2; }; /** Read page from NUR module * * @param hApi Handle to valid NurApi object instance * @param pageNum Page number to read * @param pageBuffer Buffer to store data. This must be atleast 256 bytes long. * @param pageAddr Page address is stored here * * @return Zero when succeeded, On error non-zero error code is returned. * @remarks This command is available only in bootloader */ NUR_API int NURAPICONV NurApiPageRead(HANDLE hApi, WORD pageNum, BYTE *pageBuffer, DWORD *pageAddr); /** Program new firmware to NUR module. * @sa NUR_NOTIFICATION_PRGPRGRESS in enum NUR_NOTIFICATION * * @param hApi Handle to valid NurApi object instance * @param buffer Data to program * @param bufferLen Length of data in bytes * * @return Zero when succeeded, On error non-zero error code is returned. * @remarks This command is available only in bootloader */ NUR_API int NURAPICONV NurApiProgramApp(HANDLE hApi, BYTE *buffer, DWORD bufferLen); NUR_API int NURAPICONV NurApiProgramBootloader(HANDLE hApi, BYTE *buffer, DWORD bufferLen); /** Write NUR module serial, name and variant flags. * @param hApi Handle to valid NurApi object instance * @return Zero when succeeded, On error non-zero error code is returned. */ NUR_API int NURAPICONV NurApiSetVariantInfo(HANDLE hApi, DWORD dwCode, struct NUR_VARIANT_INFO *vi); /** Write NUR module serial, name and variant flags. * @param hApi Handle to valid NurApi object instance * @return Zero when succeeded, On error non-zero error code is returned. */ NUR_API int NURAPICONV NurApiSetVariantInfoEx(HANDLE hApi, DWORD dwCode, struct NUR_VARIANT_INFO7 *vi, DWORD viSize); NUR_API int NURAPICONV NurApiSaveFactoryDefaults(HANDLE hApi, DWORD dwCode); /* Internal use */ NUR_API int NURAPICONV NurApiSetFileFormat(HANDLE hApi, BYTE code, BYTE *clean, DWORD length); NUR_API int NURAPICONV NurApiGetRfSettings(HANDLE hApi, BYTE *buffer, DWORD bufferLen); NUR_API int NURAPICONV NurApiSetRfSettings(HANDLE hApi, BYTE *buffer, DWORD bufferLen); NUR_API int NURAPICONV NurApiScanChannels(HANDLE hApi, struct NUR_SCANCHANNEL_INFO *infoArray, DWORD *infoArrayLen); NUR_API int NURAPICONV NurApiGetReflectedPower(HANDLE hApi, struct NUR_REFLECTEDPOWER_INFO *info); NUR_API int NURAPICONV NurApiGetReflectedPowerFreq(HANDLE hApi, DWORD freq, struct NUR_REFLECTEDPOWER_INFO *info); NUR_API int NURAPICONV NurApiWriteReg(HANDLE hApi, BYTE reg, BYTE val); NUR_API int NURAPICONV NurApiReadReg(HANDLE hApi, BYTE reg, BYTE *val); NUR_API int NURAPICONV NurApiConfigBits(HANDLE hApi, DWORD code, DWORD *bits, BOOL set); NUR_API int NURAPICONV NurApiConfirmMCUArch(HANDLE hNurApi, DWORD requiredArch, DWORD *actualArch); /** @} */ // end of INTERNALAPI #ifdef __cplusplus } #endif #endif
28.424893
109
0.753586
567dbdb027cfbe6d061a430bc27e6546fe704710
1,171
c
C
mie creazioni/Informatica/C/Facolta/16_11_2015/esercizio2_16_11_2015/esercizio2_16_11_2015/main.c
andre-bisa/Archive
9599342d684172391d8919714e5494082615efb8
[ "MIT" ]
null
null
null
mie creazioni/Informatica/C/Facolta/16_11_2015/esercizio2_16_11_2015/esercizio2_16_11_2015/main.c
andre-bisa/Archive
9599342d684172391d8919714e5494082615efb8
[ "MIT" ]
null
null
null
mie creazioni/Informatica/C/Facolta/16_11_2015/esercizio2_16_11_2015/esercizio2_16_11_2015/main.c
andre-bisa/Archive
9599342d684172391d8919714e5494082615efb8
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #define DIM 10 int trovaPos(int vett[], int dim_vett, int cosa_cercare) { int i; int ritorno = -1; for (i=0; i<dim_vett && ritorno<0; i++) { if (vett[i] == cosa_cercare) ritorno++; } return ritorno; } int leggi(int vet[], int dim) { int size = 0, num; do { printf("Inserisci un numero: "); scanf("%d", &num); if (num!=0 && size<dim) { vet[size] = num; size++; } } while (num!=0 && size<dim); return size; } int conta_ripetizioni(int v[], int dim, int cosa_cercare) { int conta = 0; int i=0; do { if (trovaPos(&v[i+1], dim-i, cosa_cercare) >= 0) conta++; i++; } while (i<dim && conta>0); return conta; } int main(void) { int v[DIM], dim, i, count, temp_dim, temp_pos, offset; dim = leggi(v, DIM); for (i=0; i<dim; i++) { count = 0; temp_dim = dim; offset = 0; do { temp_pos = trovaPos(&v[offset], temp_dim, v[i]); if (temp_pos >= 0) { count++; temp_dim = temp_dim - temp_pos - 1; offset = offset + temp_pos + 1; } } while (temp_pos>=0 && count<2); if (count == 2) printf("L'elemento %d compare 2 volte\n", v[i]); } system("pause"); return (0); }
19.516667
59
0.572161
487a33618e82cdb69432e2cc308191710f7233f8
2,029
c
C
c/dotjson/test/decode.c
vizee/misc
2946559d496008505656f2fed3596600878733bf
[ "MIT" ]
null
null
null
c/dotjson/test/decode.c
vizee/misc
2946559d496008505656f2fed3596600878733bf
[ "MIT" ]
null
null
null
c/dotjson/test/decode.c
vizee/misc
2946559d496008505656f2fed3596600878733bf
[ "MIT" ]
null
null
null
#include "../dotjson.c" #include "util.h" #include <stdio.h> void test_decode_string() { struct dotj_string *str; puts("===test_decode_string==="); printf("len %lu\n", decode_string("\"\\nabc\\u4F60\\u597D\\u4E16\\u754Cefd\"", (struct dotj_node **)&str)); print_node((struct dotj_node *)str); dotjson_destroy((struct dotj_node *)str); puts("==========end=========="); } void test_decode_number() { struct dotj_number *num; puts("===test_decode_number==="); printf("len %lu\n", decode_number(" 123459.123e10", (struct dotj_node **)&num)); print_node((struct dotj_node *)num); dotjson_destroy((struct dotj_node *)num); puts("==========end=========="); } void test_decode_object() { struct dotj_node *node; const char *json1 = "{}"; const char *json2 = "{\"true\":true,\"false\":false,\"null\":null,\"string\":\"string\",\"number\":123}"; const char *json3 = "{\"a\":[0]}"; puts("===test_decode_object==="); printf("len %lu\n", decode_object(json1, &node)); print_node(node); dotjson_destroy(node); printf("len %lu\n", decode_object(json2, &node)); print_node(node); dotjson_destroy(node); printf("len %lu\n", decode_object(json3, &node)); print_node(node); dotjson_destroy(node); puts("==========end=========="); } void test_decode_array() { struct dotj_node *node; const char *json1 = "[]"; const char *json2 = "[true,false,null,\"string\",123]"; const char *json3 = "[{\"a\":0}]"; puts("===test_decode_array===="); printf("len %lu\n", decode_array(json1, &node)); print_node(node); dotjson_destroy(node); printf("len %lu\n", decode_array(json2, &node)); print_node(node); dotjson_destroy(node); printf("len %lu\n", decode_array(json3, &node)); print_node(node); dotjson_destroy(node); puts("==========end=========="); } int main() { test_decode_string(); test_decode_number(); test_decode_object(); test_decode_array(); return 0; }
27.053333
111
0.595367
219ec47b0da5e7ed0778a1cdfafad45a223bea65
278
c
C
generators/lex/liblex/main.c
aryx/principia-softwarica
4191ace48c70d7e70ef0002b27324c3a766f7672
[ "LPL-1.02" ]
null
null
null
generators/lex/liblex/main.c
aryx/principia-softwarica
4191ace48c70d7e70ef0002b27324c3a766f7672
[ "LPL-1.02" ]
null
null
null
generators/lex/liblex/main.c
aryx/principia-softwarica
4191ace48c70d7e70ef0002b27324c3a766f7672
[ "LPL-1.02" ]
null
null
null
/*s: generators/lex/liblex/main.c */ #include <u.h> #include <libc.h> //#include <stdio.h> int yylex(void); /*s: function main */ void main(int argc, char *argv[]) { USED(argc, argv); yylex(); exits(0); } /*e: function main */ /*e: generators/lex/liblex/main.c */
15.444444
36
0.604317
29559eb75420dac1451d82794eea510a2c5d56aa
1,473
h
C
firmware/coreboot/src/mainboard/google/jecht/variants/jecht/include/variant/thermal.h
fabiojna02/OpenCellular
45b6a202d6b2e2485c89955b9a6da920c4d56ddb
[ "CC-BY-4.0", "BSD-3-Clause" ]
1
2019-11-04T07:11:25.000Z
2019-11-04T07:11:25.000Z
firmware/coreboot/src/mainboard/google/jecht/variants/jecht/include/variant/thermal.h
fabiojna02/OpenCellular
45b6a202d6b2e2485c89955b9a6da920c4d56ddb
[ "CC-BY-4.0", "BSD-3-Clause" ]
13
2018-10-12T21:29:09.000Z
2018-10-25T20:06:51.000Z
firmware/coreboot/src/mainboard/google/jecht/variants/jecht/include/variant/thermal.h
fabiojna02/OpenCellular
45b6a202d6b2e2485c89955b9a6da920c4d56ddb
[ "CC-BY-4.0", "BSD-3-Clause" ]
null
null
null
/* * This file is part of the coreboot project. * * Copyright (C) 2014 Google Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #ifndef THERMAL_H #define THERMAL_H #define TEMPERATURE_SENSOR_ID 0 /* PECI */ /* Fan is at default speed */ #define FAN4_PWM 0x4d /* Fan is at LOW speed */ #define FAN3_THRESHOLD_OFF 50 #define FAN3_THRESHOLD_ON 55 #define FAN3_PWM 0x76 /* Fan is at MEDIUM speed */ #define FAN2_THRESHOLD_OFF 59 #define FAN2_THRESHOLD_ON 65 #define FAN2_PWM 0x98 /* Fan is at HIGH speed */ #define FAN1_THRESHOLD_OFF 68 #define FAN1_THRESHOLD_ON 75 #define FAN1_PWM 0xbf /* Fan is at FULL speed */ #define FAN0_THRESHOLD_OFF 80 #define FAN0_THRESHOLD_ON 86 #define FAN0_PWM 0xdc /* Temperature which OS will shutdown at */ #define CRITICAL_TEMPERATURE 98 /* Temperature which OS will throttle CPU */ #define PASSIVE_TEMPERATURE 95 /* Tj_max value for calculating PECI CPU temperature */ #define MAX_TEMPERATURE 105 #endif
27.277778
71
0.704005
f643f79a4f23aabdc781c9c10d02ec640849f415
8,407
h
C
Engine/sdk/src/lwHeap.h
ruuuubi/corsairs-client
ddbcd293d6ef3f58ff02290c02382cbb7e0939a2
[ "Apache-2.0" ]
1
2021-06-14T09:34:08.000Z
2021-06-14T09:34:08.000Z
Engine/sdk/src/lwHeap.h
ruuuubi/corsairs-client
ddbcd293d6ef3f58ff02290c02382cbb7e0939a2
[ "Apache-2.0" ]
null
null
null
Engine/sdk/src/lwHeap.h
ruuuubi/corsairs-client
ddbcd293d6ef3f58ff02290c02382cbb7e0939a2
[ "Apache-2.0" ]
null
null
null
// #pragma once #include "lwHeader.h" #include "lwInterfaceExt.h" #include "lwStdInc.h" #include "lwDirectX.h" #include "lwClassDecl.h" LW_BEGIN // this is a min-heap class // if you want to get max-heap, pls wrap operator<() of T template<typename T> class lwHeapT { public: typedef T value_type; typedef value_type* value_type_ptr; typedef value_type& value_type_ref; typedef BOOL (*lwHeapTCompareProc)(const T& i, const T& j); typedef void (*lwHeapTFilterProc)(const T& t, DWORD i); enum { DEFAULT_CHUNK_SIZE = 32 }; private: T* _buf; DWORD _buf_size; DWORD _num; lwHeapTCompareProc _comp_proc; lwHeapTFilterProc _filter_proc; private: DWORD _Parent(DWORD i) { return (i - 1) / 2; } DWORD _Left(DWORD i) { return (2 * i + 1); } DWORD _Right(DWORD i) { return (2 * i + 2); } void _Place(DWORD i, const T& t) { _buf[i] = t; if(_filter_proc) { (*_filter_proc)(t, i); } } void _Swap(DWORD i, DWORD j) { T t = _buf[i]; _buf[i] = _buf[j]; _buf[j] = t; } T _Value(DWORD i) { return _buf[i]; } T* _Ptr(DWORD i) { return &_buf[i]; } T& _Ref(DWORD i) { return _buf[i]; } BOOL _Comp(const T& i, const T& j) { return _comp_proc ? (*_comp_proc)(i, j) : (i) <= (j); } BOOL _CheckBufferState() { return (_num < _buf_size); } LW_RESULT _Allocate(DWORD buf_size); LW_RESULT _Free(); DWORD _FilterDown(DWORD i); DWORD _FilterUp(DWORD i); public: lwHeapT() : _buf(0), _buf_size(0), _num(0), _comp_proc(0), _filter_proc(0) {} ~lwHeapT() { Clear(); } LW_RESULT Reserve(DWORD size); LW_RESULT Clear(); LW_RESULT Push(const T& t); LW_RESULT Push(const T* buf, DWORD size); LW_RESULT Pop(); LW_RESULT Top(T* t); LW_RESULT Find(DWORD* id, const T& t); LW_RESULT Update(DWORD id); LW_RESULT Remove(DWORD id); LW_RESULT Copy(lwHeapT* src); void SetCompareProc(lwHeapTCompareProc proc) { _comp_proc = proc; } void SetFilterProc(lwHeapTFilterProc proc) { _filter_proc = proc; } lwHeapTCompareProc GetCompareProc() { return _comp_proc; } lwHeapTFilterProc GetFilterProc() { return _filter_proc; } DWORD GetHeapNum() { return _num; } DWORD GetHeapCapacity() { return _buf_size; } T* GetBuffer() { return _buf; } }; template<typename T> LW_RESULT lwHeapT<T>::_Allocate(DWORD buf_size) { if(buf_size < _buf_size) return LW_RET_FAILED; int size = (buf_size == 0xffffffff) ? DEFAULT_CHUNK_SIZE : (int)buf_size; #if(defined USE_NEW_PLACEMENT) int new_size; // i cannot understand the error by ::new(&_buf[_buf_size+i]) T; ??? if(_buf_size == 0) { _buf = (T*)LW_MALLOC(sizeof(T) * size); } else { while(size <= (int)_buf_size) { size *= 2; } _buf = (T*)LW_REALLOC(_buf, sizeof(T) * size); } new_size = size - _buf_size; for(int i = 0; i < new_size; i++) { ::new(&_buf[_buf_size+i]) T; } _buf_size = size; #else if(_buf_size == 0) { _buf = LW_NEW(T[size]); } else { T* new_buf; while(size <= (int)_buf_size) { size *= 2; } new_buf = LW_NEW(T[size]); for(DWORD i = 0; i < _buf_size; i++) { new_buf[i] = _buf[i]; } LW_DELETE_A(_buf); _buf = new_buf; } _buf_size = size; #endif return LW_RET_OK; } template<typename T> LW_RESULT lwHeapT<T>::_Free() { if(_buf_size > 0) { #if(defined USE_NEW_PLACEMENT) for(DWORD i = 0; i < _buf_size; i++) { _buf[i].~T(); } LW_FREE(_buf); #else LW_DELETE_A(_buf); #endif _buf = 0; _buf_size = 0; _num = 0; } return LW_RET_OK; } template<typename T> DWORD lwHeapT<T>::_FilterDown(DWORD i) { T t = _Value(i); DWORD index = i; DWORD l = _Left(i); DWORD r = _Right(i); DWORD c; while(l < GetHeapNum()) { if(r < GetHeapNum() && _Comp(_Ref(r), _Ref(l))) c = r; else c = l; if(_Comp(t, _Ref(c))) break; _Place(index, _buf[c]); //_buf[index] = _buf[c]; index = c; l = _Left(index); r = _Right(index); } if(index != i) { _Place(index, t); //_buf[index] = t; } return index; } template<typename T> DWORD lwHeapT<T>::_FilterUp(DWORD i) { T t = _Value(i); DWORD index = i; DWORD p = _Parent(i); while((index > 0) && _Comp(t, _Ref(p))) { _Place(index, _buf[p]); //_buf[index] = _buf[p]; index = p; p = _Parent(p); } if(index != i) { _Place(index, t); //_buf[index] = t; } return index; } template<typename T> LW_RESULT lwHeapT<T>::Reserve(DWORD size) { return _Allocate(size); } template<typename T> LW_RESULT lwHeapT<T>::Clear() { return _Free(); } template<typename T> LW_RESULT lwHeapT<T>::Push(const T& t) { if(_num >= _buf_size) { if(LW_FAILED(_Allocate(0xffffffff))) return LW_RET_FAILED; } _Place(_num, t); _FilterUp(_num); _num += 1; return LW_RET_OK; } template<typename T> LW_RESULT lwHeapT<T>::Push(const T* buf, DWORD size) { for(DWORD i = 0; i < size; i++) { Push(buf[i]); } return LW_RET_OK; } template<typename T> LW_RESULT lwHeapT<T>::Pop() { if(_num == 0) return LW_RET_FAILED; _num -= 1; if(_num > 0) { _Place(0, _Value(_num)); _FilterDown(0); } return LW_RET_OK; } template<typename T> LW_RESULT lwHeapT<T>::Top(T* t) { if(_num == 0) return LW_RET_FAILED; *t = _Value(0); return LW_RET_OK; } template<typename T> LW_RESULT lwHeapT<T>::Find(DWORD* id, const T& t) { if(_num == 0) return LW_RET_FAILED; for(DWORD i = 0; i < GetHeapNum(); i++) { if(_buf[i] == t) { *id = i; return LW_RET_OK; } } return LW_RET_FAILED; } template<typename T> LW_RESULT lwHeapT<T>::Update(DWORD id) { if(id >= _num) return LW_RET_FAILED; if((id > 0) && _Comp(_Ref(id), _Ref(_Parent(id)))) { _FilterUp(id); } else { _FilterDown(id); } return LW_RET_OK; } template<typename T> LW_RESULT lwHeapT<T>::Remove(DWORD id) { if(id >= _num) return LW_RET_FAILED; _num -= 1; if(id < _num) { _Place(id, _buf[_num]); return Update(id); } return LW_RET_OK; } template<typename T> LW_RESULT lwHeapT<T>::Copy(lwHeapT* src) { Clear(); _num = src->_num; _buf_size = src->_buf_size; _comp_proc = src->_comp_proc; _filter_proc = src->_filter_proc; _buf = LW_NEW(T[_buf_size]); memcpy(_buf, src->_buf, sizeof(T) * _num); return LW_RET_OK; } // class lwHeap : public lwIHeap { LW_STD_DECLARATION(); typedef lwHeapT<void*> T; private: T _heap; public: LW_RESULT Reserve(DWORD size) { return _heap.Reserve(size); } LW_RESULT Clear() { return _heap.Clear(); } LW_RESULT Push(const void* t) { return _heap.Push((T::value_type_ref)t); } LW_RESULT Push(const void* buf, DWORD size) { return _heap.Push((T::value_type_ptr)buf, size); } LW_RESULT Pop() { return _heap.Pop(); } LW_RESULT Top(void** t) { return _heap.Top(t); } LW_RESULT Find(DWORD* id, const void* t) { return _heap.Find(id, (T::value_type_ref)t); } LW_RESULT Update(DWORD id) { return _heap.Update(id); } LW_RESULT Remove(DWORD id) { return _heap.Remove(id); } void SetCompareProc(lwHeapCompProc proc) { _heap.SetCompareProc((T::lwHeapTCompareProc)proc); } void SetFilterProc(lwHeapFilterProc proc) { _heap.SetFilterProc((T::lwHeapTFilterProc)proc); } lwHeapCompProc GetCompareProc() { return (lwHeapCompProc)_heap.GetCompareProc(); } lwHeapFilterProc GetFilterProc() { return (lwHeapFilterProc)_heap.GetFilterProc(); } DWORD GetHeapNum() { return _heap.GetHeapNum(); } DWORD GetHeapCapacity() { return _heap.GetHeapCapacity(); } void* GetBuffer() { return _heap.GetBuffer(); } LW_RESULT Clone(lwIHeap** out_heap); }; LW_END
20.209135
83
0.571548
f653bb1d94ec711d85fe6e89f35ff80b90684d05
260,289
c
C
source/3rd/cpl-7.1.4/cplcore/cpl_propertylist.c
ray820328/Funra
99c89a7a40798fb41dd401195fcc4711bec2520b
[ "MIT" ]
null
null
null
source/3rd/cpl-7.1.4/cplcore/cpl_propertylist.c
ray820328/Funra
99c89a7a40798fb41dd401195fcc4711bec2520b
[ "MIT" ]
null
null
null
source/3rd/cpl-7.1.4/cplcore/cpl_propertylist.c
ray820328/Funra
99c89a7a40798fb41dd401195fcc4711bec2520b
[ "MIT" ]
null
null
null
/* * This file is part of the ESO Common Pipeline Library * Copyright (C) 2001-2017 European Southern Observatory * * 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 */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <stdio.h> #include <string.h> #include <sys/types.h> #include <regex.h> #include <complex.h> #include <fitsio.h> #include <cxmacros.h> #include <cxmemory.h> #include <cxdeque.h> #include <cxmessages.h> #include <cxstrutils.h> #include <cxutils.h> #include <cxstring.h> #include "cpl_io_fits.h" #include "cpl_errorstate.h" #include "cpl_error_impl.h" #include "cpl_memory.h" #include "cpl_io.h" #include "cpl_propertylist_impl.h" #include "cpl_property_impl.h" #include <math.h> #include <errno.h> #undef CPL_HAVE_LOCALE #ifdef HAVE_LOCALE_H #include <locale.h> #define CPL_HAVE_LOCALE #endif #if defined HAVE_XLOCALE_H #include <xlocale.h> #define CPL_HAVE_LOCALE #endif /** * @defgroup cpl_propertylist Property Lists * * This module implements a container for @em properties (see * @ref cpl_property) which can be used to store auxiliary values related to * another data object, an image or a table for instance. The property values * can be set and retrieved by their associated name and properties can be * added and removed from the list. The property list container is an ordered * sequence of properties. * * @par Synopsis: * @code * #include <cpl_propertylist.h> * @endcode */ /**@{*/ enum { FITS_STDKEY_MAX = 8, FITS_SVALUE_MAX = 68, FITS_CARD_LEN = 80 }; /* * The property list type. */ struct _cpl_propertylist_ { cx_deque *properties; }; /* * Regular expresion filter type */ struct _cpl_regexp_ { regex_t re; cxbool invert; }; typedef struct _cpl_regexp_ cpl_regexp; /* * memcmp() filter type */ typedef struct cpl_memcmp_ { cpl_size nstart; const cpl_cstr ** startkey; cpl_size nexact; const cpl_cstr ** exactkey; cxbool invert; } cpl_memcmp_; /* * FITS keyword type mapping for floating point WCS keywords. */ struct _cpl_wcskeys_ { const cxchar *key; cxint sz; cxchar type; }; typedef struct _cpl_wcskeys_ cpl_wcskeys; /* FITS standard 4.1.2.1: "For indexed keyword names that have a single positive integer index counter appended to the root name, the counter shall not have leading zeros (e.g., NAXIS1, not NAXIS001)." https://fits.gsfc.nasa.gov/standard40/fits_standard40aa-le.pdf */ static cpl_wcskeys FITS_KEYMAP_WCS[] = { {"^CRPIX[0-9]+", -1, 'F'}, {"^CRVAL[0-9]+", -1, 'F'}, {"^CDELT[0-9]+", -1, 'F'}, {"^CRDER[0-9]+", -1, 'F'}, {"^CSYER[0-9]+", -1, 'F'}, {"^PC[0-9]+_[0-9]+", -1, 'F'}, {"^PV[0-9]+_[0-9]+", -1, 'F'}, {"^CD[0-9]+_[0-9]+", -1, 'F'}, {"EQUINOX", 7, 'F'}, {"EPOCH", 5, 'F'}, {"MJD-OBS", 7, 'F'}, {"LONGPOLE", 8, 'F'}, {"LATPOLE", 7, 'F'} }; typedef struct cpl_fits_value { union { long long i; /* Numerical, integer */ double f; /* Numerical, double */ double complex x; /* Numerical, complex */ char l; /* Boolean: 1 for true ('T') or 0 for false ('F') */ const char * c; /* String, any escaped quotes ('') are decoded */ } val; int nmemb; /* For string data: number of bytes in buffer For no-value, undefined value and error: 0 For one of the other values: 1 */ char tcode; /* Type code: FITS code: 'C', 'L', 'F', 'I', 'X', or 'U' (undefined), 'N' (none) or 0 (unparsable card) */ char unquote[FLEN_COMMENT]; /* String buffer for decoded string */ } cpl_fits_value; /* * Private methods */ inline static cxint cpl_fits_key_is_unique(const char **[], const cpl_cstr *, cpl_size) CPL_ATTR_NONNULL; inline static void cpl_fits_key_free_unique(const char **[]) CPL_ATTR_NONNULL; inline static cxint _cpl_propertylist_filter_regexp(cxcptr, cxcptr) CPL_ATTR_NONNULL; inline static cxint _cpl_propertylist_filter_memcmp(cxcptr, cxcptr) CPL_ATTR_NONNULL; inline static const char * cpl_fits_get_key(const char *, int *, int *) CPL_ATTR_NONNULL; inline static char cpl_fits_get_value(cpl_fits_value *, const char *, int, int, const cpl_cstr *, int *) CPL_ATTR_NONNULL; inline static int cpl_fits_get_number(const char *, int, long long *, double *, int *) #ifdef CPL_HAVE_ATTR_NONNULL __attribute__((nonnull(1,4,5))) #endif ; inline static const char * cpl_fits_get_comment(const char *, int, int *) CPL_ATTR_NONNULL; inline static char cpl_property_find_type(const cpl_cstr*, int) CPL_ATTR_NONNULL CPL_ATTR_PURE; inline static cxbool cpl_property_compare_name(const cpl_property *, const cpl_cstr *) CPL_ATTR_NONNULL; inline static cpl_error_code _cpl_propertylist_to_fitsfile(fitsfile *, const cpl_propertylist *, cx_compare_func, cxptr) #ifdef CPL_HAVE_ATTR_NONNULL __attribute__((nonnull(1,2))) #endif ; static cpl_error_code cpl_propertylist_to_fitsfile_locale(fitsfile *, const cpl_propertylist *, cx_compare_func, cxptr) #ifdef CPL_HAVE_ATTR_NONNULL __attribute__((nonnull(1,2))) #endif ; static cpl_error_code cpl_propertylist_fill_from_fits_locale(cpl_propertylist *, fitsfile *, int, cx_compare_func, cxptr) #ifdef CPL_HAVE_ATTR_NONNULL __attribute__((nonnull(1,2))) #endif ; inline static cpl_error_code _cpl_propertylist_fill_from_fits(cpl_propertylist *, fitsfile *, int, cx_compare_func, cxptr) #ifdef CPL_HAVE_ATTR_NONNULL __attribute__((nonnull(1,2))) #endif ; inline static cxint _cpl_wcskeys_find(const cxchar *key, const cpl_wcskeys *keymap, cxint mapsize) { cxint i = 0; cxint pos = mapsize; for (i = 0; i < mapsize; ++i) { if (keymap[i].sz < 0) { cpl_regexp pattern; cxint status = regcomp(&pattern.re, keymap[i].key, REG_EXTENDED | REG_NOSUB); if (status) { return -1; } if (regexec(&pattern.re, key, (size_t)0, NULL, 0) == 0) { pos = i; regfree(&pattern.re); break; } regfree(&pattern.re); } else { if (strncmp(key, keymap[i].key, keymap[i].sz) == 0) { pos = i; break; } } } return pos; } /*----------------------------------------------------------------------------*/ /** @internal @brief Determine whether a given property must be floating point @param key The name w. length of the property, must be non-NULL @param naxis The value of NAXIS of the given header (may be zero) @return The property type: 'I', 'F' @note This internal function has no error checking The function does not validate its input according to the FITS standard, it merely determines whether the given key must be loaded as a floating point type, even if its actual value can be represented as an integer Per this paper coauthored by M. R. Calabretta: https://www.aanda.org/articles/aa/full/2002/45/aah3859/aah3859.html these are numerical keys of a floating point type (where the axis is 1-99): CRPIX[0-9]+ CRVAL[0-9]+ CDELT[0-9]+ CRDER[0-9]+ CSYER[0-9]+ PC[0-9]+_[0-9]+ PV[0-9]+_[0-9]+ CD[0-9]+_[0-9]+ EQUINOX EPOCH MJD-OBS LONGPOLE LATPOLE */ /*----------------------------------------------------------------------------*/ inline static char cpl_property_find_type(const cpl_cstr* key, int naxis) { char type = 'I'; /* Default type */ const cxsize keylen = cx_string_size_(key); const char * keyname = cx_string_get_(key); /* Switch on the length, i.e. the number of characters */ /* First matching the length of the key to the length of the string literal allows for a static-length memcmp() which should be inline-able. */ /* NB: The indentation that aligns the calls to memcmp() helps to ensure that strings of identical length share the correct branch */ switch (keylen) { case 5: if (!memcmp(keyname, "EPOCH", 5)) type = 'F'; else if (keyname[3] == '_' && 0 < naxis && naxis < 10) { char mytype = type; if (!memcmp(keyname, "PC", 2)) mytype = 'F'; else if (!memcmp(keyname, "PV", 2)) mytype = 'F'; else if (!memcmp(keyname, "CD", 2)) mytype = 'F'; if (mytype != type && '0' < keyname[2] && keyname[2] <= '9' && '0' < keyname[4] && keyname[4] <= '9' ) type = mytype; } break; case 6: if (0 < naxis && naxis < 10) { char mytype = type; if (!memcmp(keyname, "CRPIX", 5)) mytype = 'F'; else if (!memcmp(keyname, "CRVAL", 5)) mytype = 'F'; else if (!memcmp(keyname, "CDELT", 5)) mytype = 'F'; else if (!memcmp(keyname, "CRDER", 5)) mytype = 'F'; else if (!memcmp(keyname, "CSYER", 5)) mytype = 'F'; if (mytype != type && '0' < keyname[5] && keyname[5] <= '9') type = mytype; } break; case 7: if (!memcmp(keyname, "EQUINOX", 7)) type = 'F'; else if (!memcmp(keyname, "MJD-OBS", 7)) type = 'F'; else if (!memcmp(keyname, "LATPOLE", 7)) type = 'F'; break; case 8: if (!memcmp(keyname, "LONGPOLE", 8)) type = 'F'; break; default: break; } if (type == 'I' && naxis > 0 && keylen > 5) { char mytype = type; if (!memcmp(keyname, "CRPIX", 5)) mytype = 'F'; else if (!memcmp(keyname, "CRVAL", 5)) mytype = 'F'; else if (!memcmp(keyname, "CDELT", 5)) mytype = 'F'; else if (!memcmp(keyname, "CRDER", 5)) mytype = 'F'; else if (!memcmp(keyname, "CSYER", 5)) mytype = 'F'; else if (!memcmp(keyname, "PC", 2)) mytype = 'F'; else if (!memcmp(keyname, "PV", 2)) mytype = 'F'; else if (!memcmp(keyname, "CD", 2)) mytype = 'F'; if (mytype != type) { /* Cover the many multi-digit cases with regular expressions */ const cxuint nwcs = CX_N_ELEMENTS(FITS_KEYMAP_WCS); cxuint j; j = _cpl_wcskeys_find(keyname, FITS_KEYMAP_WCS, nwcs); if ((j < nwcs) && (type != FITS_KEYMAP_WCS[j].type)) { type = FITS_KEYMAP_WCS[j].type; } #ifdef CPL_PROPERTYLIST_DEBUG if (type != 'I') cpl_msg_warning(cpl_func, "Floating point key(%zd:naxis=%d): " "%s (regexp check)", keylen, naxis, keyname); #endif } } #ifdef CPL_PROPERTYLIST_DEBUG if (type != 'I') { char keystr[FLEN_KEYWORD]; /* Needed for %s */ (void)memcpy(keystr, keyname, keylen); keystr[keylen] = '\0'; cpl_msg_warning(cpl_func, "Floating point key(%zd:naxis=%d): %s", keylen, naxis, keystr); } #endif return type; } inline static cxint _cpl_propertylist_filter_regexp(cxcptr key, cxcptr filter) { const cxchar *_key = cx_string_get_((const cpl_cstr *)key); const cpl_regexp *_filter = (const cpl_regexp *)filter; if (regexec(&_filter->re, _key, (size_t)0, NULL, 0) == REG_NOMATCH) return _filter->invert == TRUE ? TRUE : FALSE; return _filter->invert == TRUE ? FALSE : TRUE; } inline static cxint _cpl_propertylist_filter_memcmp(cxcptr key, cxcptr filter) { const cpl_cstr *_key = (const cpl_cstr *)key; const cpl_memcmp_ *_filter = (const cpl_memcmp_ *)filter; cpl_size i; /* Does the key match the beginning of the provided start-keys ? */ for (i = 0; i < _filter->nstart; i++) { if (cx_string_size_(_key) >= cx_string_size_(_filter->startkey[i]) && !memcmp(cx_string_get_(_key), cx_string_get_(_filter->startkey[i]), cx_string_size_(_filter->startkey[i]))) break; /* Match */ } if (i < _filter->nstart) return _filter->invert ? FALSE : TRUE; /* Does the key exactly match the provided exact-keys ? */ for (i = 0; i < _filter->nexact; i++) { if (cx_string_size_(_key) == cx_string_size_(_filter->exactkey[i]) && !memcmp(cx_string_get_(_key), cx_string_get_(_filter->exactkey[i]), cx_string_size_(_filter->exactkey[i]))) break; /* Match */ } if (i < _filter->nexact) return _filter->invert ? FALSE : TRUE; /* No match */ return _filter->invert ? TRUE : FALSE; } inline static cxbool _cpl_propertylist_compare_start(const cpl_property *property, const char *part_name) { const cxchar *key = cpl_property_get_name(property); if (strstr(key, part_name) == key) return TRUE; return FALSE; } inline static cxbool _cpl_propertylist_compare_regexp(const cpl_property *property, cpl_regexp *re) { const cxchar *key = cpl_property_get_name(property); const cxsize keysz = cpl_property_get_size_name(property); const cpl_cstr *key_; key_ = CXSTR(key, keysz); return _cpl_propertylist_filter_regexp(key_, re); } /** * @internal * @brief * Compare the property name with the given name with its size * * @param self The property to compare * @param key The name to compare * @return true iff the names match * @see memcmp() * */ inline static cxbool cpl_property_compare_name(const cpl_property *self, const cpl_cstr *key) { const size_t namelen = cpl_property_get_size_name(self); return (namelen != cx_string_size_(key) || memcmp(cpl_property_get_name_(self), cx_string_get_(key), namelen)) ? FALSE : TRUE; } inline static cx_deque_iterator _cpl_propertylist_find_(const cpl_propertylist *self, const cpl_cstr *name) { cx_deque_iterator first, last; first = cx_deque_begin(self->properties); last = cx_deque_end(self->properties); while (first != last) { cpl_property *p = cx_deque_get(self->properties, first); if (cpl_property_compare_name(p, name)) break; first = cx_deque_next(self->properties, first); } return first; } inline static cx_deque_iterator _cpl_propertylist_find(const cpl_propertylist *self, const char *name) { const cpl_cstr * cxstr; cxstr = CXSTR(name, name ? strlen(name) : 0); return _cpl_propertylist_find_(self, cxstr); } inline static cpl_property * _cpl_propertylist_get_cx(const cpl_propertylist *self, const cpl_cstr *name) { cx_deque_iterator pos = _cpl_propertylist_find_(self, name); if (pos == cx_deque_end(self->properties)) return NULL; return cx_deque_get(self->properties, pos); } inline static cpl_property * _cpl_propertylist_get(const cpl_propertylist *self, const char *name) { cx_deque_iterator pos = _cpl_propertylist_find(self, name); if (pos == cx_deque_end(self->properties)) return NULL; return cx_deque_get(self->properties, pos); } inline static int _cpl_propertylist_insert(cpl_propertylist *self, const cxchar *where, cxbool after, const cxchar *name, cpl_type type, cxcptr value) { cx_deque_iterator pos; cpl_property *property; /* * Find the position where value should be inserted. */ pos = _cpl_propertylist_find(self, where); if (pos == cx_deque_end(self->properties)) { return 1; } if (after) { pos = cx_deque_next(self->properties, pos); } /* * Create the property for value and fill it. */ property = cpl_property_new(name, type); if (!property) { return 1; } /* * Map property type to the driver function's argument type. */ switch (type) { case CPL_TYPE_CHAR: cpl_property_set_char(property, *((const cxchar *)value)); break; case CPL_TYPE_BOOL: cpl_property_set_bool(property, *((const cxint *)value)); break; case CPL_TYPE_INT: cpl_property_set_int(property, *((const cxint *)value)); break; case CPL_TYPE_LONG: cpl_property_set_long(property, *((const cxlong *)value)); break; case CPL_TYPE_LONG_LONG: cpl_property_set_long_long(property, *((const cxllong *)value)); break; case CPL_TYPE_FLOAT: cpl_property_set_float(property, *((const cxfloat *)value)); break; case CPL_TYPE_DOUBLE: cpl_property_set_double(property, *((const cxdouble *)value)); break; case CPL_TYPE_STRING: cpl_property_set_string(property, ((const cxchar *)value)); break; case CPL_TYPE_FLOAT_COMPLEX: cpl_property_set_float_complex(property, *((const float complex *)value)); break; case CPL_TYPE_DOUBLE_COMPLEX: cpl_property_set_double_complex(property, *((const double complex *)value)); break; default: return 1; break; } /* * Insert it into the deque */ cx_deque_insert(self->properties, pos, property); return 0; } /* * @internal * @brief Insert cards from a FITS CHU into a propertylist * @param self The propertylist to insert * @param file The CFITSIO file object * @param hdumov Absolute extension number to move to first (0 for primary) * @param filter An optional compare function for filtering the properties * @param data An optional regexp w. invert flag for filtering the properties * @return CPL_ERROR_NONE, or the relevant CPL error on failure * @see cpl_propertylist_to_fitsfile * * The function converts the current FITS header referenced by the cfitsio * file pointer to a property list. If the header cannot be accessed, i.e. * the number of keywords cannot be determined, or a keyword cannot be read, * -1 is returned. If the header contains FITS keywords whose type cannot be * determined the function returns 2. If a keyword type is not supported the * return value is 3. */ inline static cpl_error_code _cpl_propertylist_fill_from_fits(cpl_propertylist *self, fitsfile *file, int hdumov, cx_compare_func filter, cxptr data) { char buffer[FLEN_CARD]; char keystr[FLEN_KEYWORD]; /* Needed for regexp filter */ int status = 0; int ncards = 0; int naxis = 0; if (hdumov >= 0 && fits_movabs_hdu(file, 1+hdumov, NULL, &status)) { return cpl_error_set_fits(CPL_ERROR_DATA_NOT_FOUND, status, fits_movabs_hdu, "HDU#=%d", hdumov); } if (fits_get_hdrspace(file, &ncards, NULL, &status)) { /* ffghsp() */ return cpl_error_set_fits(CPL_ERROR_FILE_IO, status, fits_get_hdrspace, "HDU#=%d", hdumov); } if (ncards <= 0) { return cpl_error_set_message_(CPL_ERROR_BAD_FILE_FORMAT, "HDU#=%d: ncards=%d", hdumov, ncards); } /* Seek to beginning of Header */ if (fits_movabs_key(file, 1, &status)) { /* ffmaky() */ return cpl_error_set_fits(CPL_ERROR_BAD_FILE_FORMAT, status, fits_movabs_key, "HDU#=%d", hdumov); } /* Need null-terminator for parsing a card with a numerical value */ buffer[FLEN_CARD - 1] = '\0'; for (int i = 1; i <= ncards; i++) { const char * cardi = buffer; const cpl_cstr * keywlen; cpl_property * property; const char * keymem; const char * commentmem = NULL; cpl_boolean get_comment = CPL_TRUE; cpl_fits_value parseval; int keylen = 0; /* Length excl. terminating null byte */ int valinlen = 0; /* Length to value indicator */ int compos = 0; int comlen; char type; if (ffgnky(file, buffer, &status)) { return cpl_error_set_fits(CPL_ERROR_BAD_FILE_FORMAT, status, ffgnky, "HDU#=%d: Bad card %d/%d", hdumov, i, ncards); } keymem = cpl_fits_get_key(cardi, &keylen, &valinlen); if (keylen+1 >= FLEN_KEYWORD) { return cpl_error_set_message_(CPL_ERROR_BAD_FILE_FORMAT, "HDU#=%d: " "Card %d/%d has bad key (len=%d)", hdumov, i, ncards, keylen); } if (filter != NULL) { /* The filter may require a null-terminated string */ (void)memcpy(keystr, keymem, keylen); keystr[keylen] = '\0'; if (filter(CXSTR(keystr, keylen), data) == FALSE) { /* Card is filtered out */ continue; } } keywlen = CXSTR(keymem, keylen); type = cpl_fits_get_value(&parseval, cardi, valinlen, naxis, keywlen, &compos); /* * Create the property from the parsed FITS card. */ switch (type) { case 'L': property = cpl_property_new_cx(keywlen, CPL_TYPE_BOOL); cpl_property_set_bool(property, parseval.val.l); break; case 'I': if ((long long)((int)parseval.val.i) == parseval.val.i) { /* Using an 'int' since the integer property fits */ property = cpl_property_new_cx(keywlen, CPL_TYPE_INT); cpl_property_set_int(property, (int)parseval.val.i); /* Get a limit on digits in floating point keys */ if (cx_string_equal_(keywlen, CXSTR("NAXIS", 5))) naxis = (int)parseval.val.i; } else { property = cpl_property_new_cx(keywlen, CPL_TYPE_LONG_LONG); cpl_property_set_long_long(property, parseval.val.i); } break; case 'F': property = cpl_property_new_cx(keywlen, CPL_TYPE_DOUBLE); cpl_property_set_double(property, parseval.val.f); break; case 'U': /* Undefined value fall-through to no-value */ case 'N': comlen = FITS_CARD_LEN - compos; /* Skip totally empty records */ if (keylen == 0 && comlen == 0) continue; /* * FITS standard: blank keywords may be followed by * any ASCII text as it is for COMMENT and HISTORY. * * In order to preserve this header record it is * changed into COMMENT record, so that it can be * stored in the property list. */ /* For a value-less card, a string value is made from the comment which becomes empty */ parseval.val.c = cardi + compos; parseval.nmemb = comlen; comlen = 0; get_comment = CPL_FALSE; CPL_ATTR_FALLTRHU; /* fall through */ case 'C': /* For the above fall through, a blank key becomes a comment key */ property = cpl_property_new_cx(keylen == 0 ? CXSTR("COMMENT", 7) : keywlen, CPL_TYPE_STRING); cpl_property_set_string_cx(property, CXSTR(parseval.nmemb > 0 ? parseval.val.c : "", parseval.nmemb)); break; case 'X': property = cpl_property_new_cx(keywlen, CPL_TYPE_DOUBLE_COMPLEX); cpl_property_set_double_complex(property, parseval.val.x); break; default: { /* A card with an invalid value will go here */ const char badchar[2] = {cardi[compos], '\0'}; return cpl_error_set_message_(CPL_ERROR_BAD_FILE_FORMAT, "HDU#=%d: " "Bad value in card %d/%d, key-len=%d " "(valinlen=%d, compos=%d, bad-char=" "0x%02x (\"%s\")", hdumov, i, ncards, keylen, valinlen, compos, (int)*badchar, badchar); } } if (get_comment) { commentmem = cpl_fits_get_comment(cardi, compos, &comlen); } /* While for the cpl_property a NULL comment is the default, here an empty comment is set as such */ cpl_property_set_comment_cx(property, CXSTR(comlen > 0 ? commentmem : "", comlen)); cx_deque_push_back(self->properties, property); } return CPL_ERROR_NONE; } /* * @internal * @brief Insert cards from a FITS CHU into a propertylist, setting the locale * @param self The propertylist to insert * @param file The CFITSIO file object * @param hdumov Absolute extension number to move to first (0 for primary) * @param filter An optional compare function for filtering the properties * @param data An optional regexp w. invert flag for filtering the properties * @return CPL_ERROR_NONE, or the relevant CPL error on failure * @see _cpl_propertylist_fill_from_fits * */ static cpl_error_code cpl_propertylist_fill_from_fits_locale(cpl_propertylist *self, fitsfile *file, int hdumov, cx_compare_func filter, cxptr data) { #ifdef CPL_HAVE_LOCALE /* Need the POSIX locale for parsing FITS via C-functions */ locale_t posix_locale = newlocale(LC_NUMERIC_MASK, "POSIX", (locale_t) 0); /* Set the POSIX locale and keep the old one for subsequent reinstating - should not be able to fail, but check nevertheless */ locale_t old_locale = posix_locale != (locale_t)0 ? uselocale(posix_locale) : (locale_t)0; #endif const cpl_error_code code = _cpl_propertylist_fill_from_fits(self, file, hdumov, filter, data); #ifdef CPL_HAVE_LOCALE if (posix_locale != (locale_t)0) { (void)uselocale(old_locale); /* Restore the previous locale */ freelocale(posix_locale); } #endif return code ? cpl_error_set_where_() : CPL_ERROR_NONE; } /* * @internal * @brief * Save the current property list to FITS via cfitsio, setting the locale * * @param file The CFITSIO file object * @param self The propertylist to be saved * @param filter An optional compare function for filtering the properties * @param data An optional regexp w. invert flag for filtering the properties * * @return * CPL_ERROR_NONE, or the relevant CPL error on failure * * @see _cpl_propertylist_to_fitsfile */ static cpl_error_code cpl_propertylist_to_fitsfile_locale(fitsfile *file, const cpl_propertylist *self, cx_compare_func filter, cxptr data) { #ifdef CPL_HAVE_LOCALE /* Need the POSIX locale for parsing FITS via C-functions */ locale_t posix_locale = newlocale(LC_NUMERIC_MASK, "POSIX", (locale_t) 0); /* Set the POSIX locale and keep the old one for subsequent reinstating - should not be able to fail, but check nevertheless */ locale_t old_locale = posix_locale != (locale_t)0 ? uselocale(posix_locale) : (locale_t)0; #endif const cpl_error_code code = _cpl_propertylist_to_fitsfile(file, self, filter, data); #ifdef CPL_HAVE_LOCALE if (posix_locale != (locale_t)0) { (void)uselocale(old_locale); /* Restore the previous locale */ freelocale(posix_locale); } #endif return code ? cpl_error_set_where_() : CPL_ERROR_NONE; } /* * @internal * @brief * Save the current property list to a FITS file using cfitsio. * * @param file The CFITSIO file object * @param self The propertylist to be saved * @param filter An optional compare function for filtering the properties * @param data An optional regexp w. invert flag for filtering the properties * * @return * CPL_ERROR_NONE, or the relevant CPL error on failure * * @note * It will not save keys that match a regular expression given in filter. * * FITS standard 4.1.2.1: * * The mandatory FITS keywords defined in this Standard * must not appear more than once within a header. All other key- * words that have a value should not appear more than once. If a * keyword does appear multiple times with different values, then * the value is indeterminate. * * https://fits.gsfc.nasa.gov/standard40/fits_standard40aa-le.pdf * @see cpl_propertylist_to_fitsfile */ inline static cpl_error_code _cpl_propertylist_to_fitsfile(fitsfile *file, const cpl_propertylist *self, cx_compare_func filter, cxptr data) { const char **putkey[FLEN_KEYWORD] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}; cx_deque_iterator first, last; const cpl_boolean do_filter = filter != NULL && data != NULL; const cpl_size nsize = cx_deque_size(self->properties); cpl_size ntocheck = nsize; #ifdef CPL_USE_LONGSTRN /* Used for the OGIP Long String Keyword Convention: http://heasarc.gsfc.nasa.gov/docs/heasarc/ofwg/docs/ofwg_recomm/r13.html */ cpl_boolean has_longstr = CPL_FALSE; #endif first = cx_deque_begin(self->properties); last = cx_deque_end(self->properties); while (first != last) { const cpl_property *p = cx_deque_get(self->properties, first); const cxchar *name = cpl_property_get_name_(p); const cxchar *comment = cpl_property_get_comment_(p); const cpl_cstr *name_; const cxsize namelen = cpl_property_get_size_name(p); const cpl_type type = cpl_property_get_type(p); cpl_boolean is_unique; cxint error = 0; name_ = CXSTR(name, namelen); ntocheck--; if (do_filter && filter(name_, data) == TRUE) { first = cx_deque_next(self->properties, first); continue; } /* For N properties fits_update_key() has complexity O(N^2) in FITS card parsing calls (ffgcrd() w. ffgknm() + ffgnky()) so try something less inefficient. */ is_unique = cpl_fits_key_is_unique(putkey, name_, ntocheck) > 0 ? CPL_FALSE : CPL_TRUE; #ifndef CX_DISABLE_ASSERT if (!is_unique) { cpl_msg_warning(cpl_func, "Non-unique FITS key(len=%d): %s (%d/%d)", (int)namelen, name, (int)(nsize - ntocheck), (int)nsize); } #endif switch (type) { /* For each type call the relevant CFITSIO key writing function. */ case CPL_TYPE_CHAR: { const cxchar c = cpl_property_get_char(p); /* * Character properties should be represented as a single * character string, not as its numerical equivalent. */ const cxchar value[2] = {c, '\0'}; /* ffpkys() / ffukys() */ (void)(is_unique ? fits_write_key_str : fits_update_key_str) (file, name, value, comment, &error); } break; case CPL_TYPE_BOOL: { const cxint b = cpl_property_get_bool(p); const cxint value = b == TRUE ? 1 : 0; /* ffpkyl()/ ffukyl() */ (void)(is_unique ? fits_write_key_log : fits_update_key_log) (file, name, value, comment, &error); } break; case CPL_TYPE_INT: { const cxint value = cpl_property_get_int(p); /* ffpkyj() / ffukyj() */ (void)(is_unique ? fits_write_key_lng : fits_update_key_lng) (file, name, value, comment, &error); } break; case CPL_TYPE_LONG: { const cxlong value = cpl_property_get_long(p); /* ffpkyj() / ffukyj() */ (void)(is_unique ? fits_write_key_lng : fits_update_key_lng) (file, name, value, comment, &error); } break; case CPL_TYPE_LONG_LONG: { const long long value = cpl_property_get_long_long(p); /* ffpkyj() / ffukyj() */ (void)(is_unique ? fits_write_key_lng : fits_update_key_lng) (file, name, value, comment, &error); } break; case CPL_TYPE_FLOAT: { const cxfloat value = cpl_property_get_float(p); const int ff_fp = -7; /* Default CFITSIO float precision */ /* ffpkye() / ffukye() */ (void)(is_unique ? fits_write_key_flt : fits_update_key_flt) (file, name, value, ff_fp, comment, &error); } break; case CPL_TYPE_DOUBLE: { const cxdouble value = cpl_property_get_double(p); const int ff_dp = -15; /* Default CFITSIO double precision */ /* ffpkyd() / ffukyd() */ (void)(is_unique ? fits_write_key_dbl : fits_update_key_dbl) (file, name, value, ff_dp, comment, &error); } break; case CPL_TYPE_STRING: if (cx_string_equal_(CXSTR("COMMENT", 7), name_)) { /* The size is the string length incl. the null-byte */ const cxsize valuesize = cpl_property_get_size_(p); const cxchar * value = valuesize <= 1 ? " " : cpl_property_get_string_(p); if (fits_write_comment(file, value, &error)) { /* ffpcom() */ cpl_fits_key_free_unique(putkey); return cpl_error_set_fits(CPL_ERROR_ILLEGAL_INPUT, error, fits_write_comment, "name='%s', type=%d ('%s'), " "comment='%s'", name, type, cpl_type_get_name(type), comment); } } else if (cx_string_equal_(CXSTR("HISTORY", 7), name_)) { /* The size is the string length incl. the null-byte */ const cxsize valuesize = cpl_property_get_size_(p); const cxchar * value = valuesize <= 1 ? " " : cpl_property_get_string_(p); if (fits_write_history(file, value, &error)) { /* ffphis() */ cpl_fits_key_free_unique(putkey); return cpl_error_set_fits(CPL_ERROR_ILLEGAL_INPUT, error, fits_write_history, "name='%s', type=%d ('%s'), " "comment='%s'", name, type, cpl_type_get_name(type), comment); } } else { const cxchar * value = cpl_property_get_string_(p); #ifdef CPL_USE_LONGSTRN /* In v. 3.24 fits_update_key_longstr() has a buffer overflow triggered by a long comment. :-(((((((((((( */ /* Try to work around this by using a truncated comment. */ cxchar shortcomment[FLEN_COMMENT]; if (comment != NULL) { (void)strncpy(shortcomment, comment, FLEN_COMMENT-1); shortcomment[FLEN_COMMENT-1] = '\0'; } if (!has_longstr) { has_longstr = CPL_TRUE; if (fits_write_key_longwarn(file, &error)) { cpl_fits_key_free_unique(putkey); return cpl_error_set_fits(CPL_ERROR_FILE_IO, error, fits_write_key_longwarn, " "); } } if (fits_update_key_longstr(file, name, value, comment != NULL ? shortcomment : NULL, &error)) { cpl_fits_key_free_unique(putkey); return cpl_error_set_fits(CPL_ERROR_ILLEGAL_INPUT, error,fits_update_key_longstr, "name='%s', value='%s', " "comment='%s'", name, value, comment); } #else /* ffpkys() / ffukys() */ if ((is_unique ? fits_write_key_str : fits_update_key_str) (file, name, value, comment, &error)) { cpl_fits_key_free_unique(putkey); return cpl_error_set_fits(CPL_ERROR_ILLEGAL_INPUT, error, fits_update_key_str, "name='%s', value='%s', " "comment='%s'", name, value, comment); } #endif } break; case CPL_TYPE_FLOAT_COMPLEX: { /* After v. 3.31 const correctness is incomplete only for the value pointer, which is taken as void *, but which ideally should be const void *. */ const float complex value = cpl_property_get_float_complex(p); float value_[2] = {crealf(value), cimagf(value)}; const int ff_fp = -7; /* Default CFITSIO float precision */ /* ffpkyc() / ffukyc() */ (void)(is_unique ? fits_write_key_cmp : fits_update_key_cmp) (file, name, value_, ff_fp, comment, &error); } break; case CPL_TYPE_DOUBLE_COMPLEX: { /* After v. 3.31 const correctness is incomplete only for the value pointer, which is taken as void *, but which ideally should be const void *. */ const double complex value = cpl_property_get_double_complex(p); double value_[2] = {creal(value), cimag(value)}; const int ff_fp = -15; /* Default CFITSIO float precision */ /* ffpkym() / ffukym() */ (void) (is_unique ? fits_write_key_dblcmp : fits_update_key_dblcmp) (file, name, value_, ff_fp, comment, &error); } break; default: cpl_fits_key_free_unique(putkey); return cpl_error_set_message_(CPL_ERROR_UNSUPPORTED_MODE, "name='%s', type=%d ('%s'), " "comment='%s'", name, type, cpl_type_get_name(type), comment); } if (error) { cpl_fits_key_free_unique(putkey); return cpl_error_set_fits(CPL_ERROR_ILLEGAL_INPUT, error, fits_update_key, "name='%s', " "type=%d ('%s'), comment='%s'", name, type, cpl_type_get_name(type), comment); } first = cx_deque_next(self->properties, first); } cpl_fits_key_free_unique(putkey); return CPL_ERROR_NONE; } /* * Public methods */ /** * @brief * Create an empty property list. * * @return * The newly created property list. * * The function creates a new property list and returns a handle for it. * To destroy the returned property list object use the property list * destructor @b cpl_propertylist_delete(). * * @see cpl_propertylist_delete() */ cpl_propertylist * cpl_propertylist_new(void) { cpl_propertylist *self = cx_malloc(sizeof *self); self->properties = cx_deque_new(); return self; } /** * @brief * Create a copy of the given property list. * * @param self The property list to be copied. * * @return * The created copy or @c NULL in case an error occurred. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> is a <tt>NULL</tt> pointer. * </td> * </tr> * </table> * @enderror * * The function creates a deep copy of the given property list @em self, * i.e the created copy and the original property list do not share any * resources. */ cpl_propertylist * cpl_propertylist_duplicate(const cpl_propertylist *self) { cx_deque_iterator first, last; cpl_propertylist *copy = NULL; if (self == NULL) { cpl_error_set_(CPL_ERROR_NULL_INPUT); return NULL; } cx_assert(self->properties != NULL); copy = cpl_propertylist_new(); first = cx_deque_begin(self->properties); last = cx_deque_end(self->properties); while (first != last) { cpl_property *tmp = cx_deque_get(self->properties, first); cx_deque_push_back(copy->properties, cpl_property_duplicate(tmp)); first = cx_deque_next(self->properties, first); } return copy; } /** * @brief * Destroy a property list. * * @param self The property list to . * * @return * Nothing. * * The function destroys the property list @em self and its whole * contents. If @em self is @c NULL, nothing is done and no error is set. */ void cpl_propertylist_delete(cpl_propertylist *self) { if (self) { cx_deque_destroy(self->properties, (cx_free_func)cpl_property_delete); cx_free(self); } return; } /** * @brief * Get the current size of a property list. * * @param self A property list. * * @return * The property list's current size, or 0 if the list is empty. If an * error occurs the function returns 0 and sets an appropriate error * code. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> is a <tt>NULL</tt> pointer. * </td> * </tr> * </table> * @enderror * * The function reports the current number of elements stored in the property * list @em self. */ cpl_size cpl_propertylist_get_size(const cpl_propertylist *self) { if (self == NULL) { cpl_error_set_(CPL_ERROR_NULL_INPUT); return 0L; } return (cpl_size) cx_deque_size(self->properties); } /** * @brief * Check whether a property list is empty. * * @param self A property list. * * @return * The function returns 1 if the list is empty, and 0 otherwise. * In case an error occurs the function returns -1 and sets an * appropriate error code. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> is a <tt>NULL</tt> pointer. * </td> * </tr> * </table> * @enderror * * The function checks if @em self contains any properties. */ int cpl_propertylist_is_empty(const cpl_propertylist *self) { if (self == NULL) { cpl_error_set_(CPL_ERROR_NULL_INPUT); return -1; } return cx_deque_empty(self->properties); } /** * @internal * @brief * Get the the type of a property list entry. * * @param self A property list. * @param name The property name to look up. * * @return * The type of the stored value. If an error occurs the function returns * @c CPL_TYPE_INVALID and sets an appropriate error code. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_DATA_NOT_FOUND</td> * <td class="ecr"> * The property list <i>self</i> does not contain a property with * the name <i>name</i>. * </td> * </tr> * </table> * @enderror * * The function returns the type of the value stored in @em self with the * name @em name. If there is more than one property with the same @em name, * it takes the first one from the list. */ inline cpl_type cpl_propertylist_get_type_cx(const cpl_propertylist *self, const cpl_cstr *name) { cpl_property *property = _cpl_propertylist_get_cx(self, name); if (property == NULL) { cpl_error_set_message_(CPL_ERROR_DATA_NOT_FOUND, "%s", name->data); return CPL_TYPE_INVALID; } return cpl_property_get_type(property); } /** * @brief * Get the the type of a property list entry. * * @param self A property list. * @param name The property name to look up. * * @return * The type of the stored value. If an error occurs the function returns * @c CPL_TYPE_INVALID and sets an appropriate error code. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_DATA_NOT_FOUND</td> * <td class="ecr"> * The property list <i>self</i> does not contain a property with * the name <i>name</i>. * </td> * </tr> * </table> * @enderror * * The function returns the type of the value stored in @em self with the * name @em name. If there is more than one property with the same @em name, * it takes the first one from the list. */ cpl_type cpl_propertylist_get_type(const cpl_propertylist *self, const char *name) { cpl_property *property; if (self == NULL || name == NULL) { cpl_error_set_(CPL_ERROR_NULL_INPUT); return CPL_TYPE_INVALID; } property = _cpl_propertylist_get(self, name); if (property == NULL) { cpl_error_set_message_(CPL_ERROR_DATA_NOT_FOUND, "%s", name); return CPL_TYPE_INVALID; } return cpl_property_get_type(property); } /** * @internal * @brief * Check whether a property is present in a property list. * * @param self A property list. * @param name The property name to look up. * * @return * The function returns 1 if the property is present, or 0 otherwise. * If an error occurs the function returns 0 and sets an appropriate * error code. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * </table> * @enderror * * The function searches the property list @em self for a property with * the name @em name and reports whether it was found or not. */ inline int cpl_propertylist_has_cx(const cpl_propertylist *self, const cpl_cstr *name) { return _cpl_propertylist_get_cx(self, name) != NULL ? 1 : 0; } /** * @brief * Check whether a property is present in a property list. * * @param self A property list. * @param name The property name to look up. * * @return * The function returns 1 if the property is present, or 0 otherwise. * If an error occurs the function returns 0 and sets an appropriate * error code. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * </table> * @enderror * * The function searches the property list @em self for a property with * the name @em name and reports whether it was found or not. */ int cpl_propertylist_has(const cpl_propertylist *self, const char *name) { if (self == NULL || name == NULL) { cpl_error_set_(CPL_ERROR_NULL_INPUT); return 0; } return _cpl_propertylist_get(self, name) != NULL ? 1 : 0; } /** * @brief * Modify the comment field of the given property list entry. * * @param self A property list. * @param name The property name to look up. * @param comment New comment string. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error code * otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_DATA_NOT_FOUND</td> * <td class="ecr"> * The property list <i>self</i> does not contain a property with * the name <i>name</i>. * </td> * </tr> * </table> * @enderror * * The function searches the property list @em self for a property named * @em name. If it is present in the list, its comment is replaced by * the string @em comment. The provided comment string may be @c NULL. * In this case an already existing comment is deleted. If there is more * than one property with the same @em name, it takes the first one from the * list. */ cpl_error_code cpl_propertylist_set_comment(cpl_propertylist *self, const char *name, const char *comment) { cpl_property *property; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = _cpl_propertylist_get(self, name); if (property == NULL) { return cpl_error_set_message_(CPL_ERROR_DATA_NOT_FOUND, "%s", name); } cpl_property_set_comment(property, comment); return CPL_ERROR_NONE; } /** * @internal * @brief * Modify the comment field of the given property list entry. * * @param self A property list. * @param name The property name w. length to look up. * @param comment New comment string. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error code * otherwise. * * @see cpl_propertylist_set_comment() * @note No NULL input in this internal function * */ inline cpl_error_code cpl_propertylist_set_comment_cx(cpl_propertylist *self, const cpl_cstr *name, const cpl_cstr *comment) { cpl_property *property = _cpl_propertylist_get_cx(self, name); if (property == NULL) { return cpl_error_set_message_(CPL_ERROR_DATA_NOT_FOUND, "%s", name->data); } cpl_property_set_comment_cx(property, comment); return CPL_ERROR_NONE; } /** * @brief * Set the value of the given character property list entry. * * @param self A property list. * @param name The property name to look up. * @param value New character value. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error code * otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_DATA_NOT_FOUND</td> * <td class="ecr"> * The property list <i>self</i> does not contain a property with * the name <i>name</i>. * </td> * </tr> * </table> * @enderror * * The function searches the property list @em self for a property named * @em name. If it is present in the list, its character value is replaced * with the character @em value. If there is more than one property with * the same @em name, it takes the first one from the list. */ cpl_error_code cpl_propertylist_set_char(cpl_propertylist *self, const char *name, char value) { cpl_property *property; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = _cpl_propertylist_get(self, name); if (property == NULL) { return cpl_error_set_message_(CPL_ERROR_DATA_NOT_FOUND, "%s", name); } return cpl_property_set_char(property, value); } /** * @brief * Set the value of the given boolean property list entry. * * @param self A property list. * @param name The property name to look up. * @param value New boolean value. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error code * otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_DATA_NOT_FOUND</td> * <td class="ecr"> * The property list <i>self</i> does not contain a property with * the name <i>name</i>. * </td> * </tr> * </table> * @enderror * * The function searches the property list @em self for a property named * @em name. If it is present in the list, its boolean value is replaced * with the boolean @em value. If there is more than one property with * the same @em name, it takes the first one from the list. */ cpl_error_code cpl_propertylist_set_bool(cpl_propertylist *self, const char *name, int value) { cpl_property *property; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = _cpl_propertylist_get(self, name); if (property == NULL) { return cpl_error_set_message_(CPL_ERROR_DATA_NOT_FOUND, "%s", name); } return cpl_property_set_bool(property, value); } /** * @brief * Set the value of the given integer property list entry. * * @param self A property list. * @param name The property name to look up. * @param value New integer value. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error code * otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_DATA_NOT_FOUND</td> * <td class="ecr"> * The property list <i>self</i> does not contain a property with * the name <i>name</i>. * </td> * </tr> * </table> * @enderror * * The function searches the property list @em self for a property named * @em name. If it is present in the list, its integer value is replaced * with the integer @em value. If there is more than one property with * the same @em name, it takes the first one from the list. */ cpl_error_code cpl_propertylist_set_int(cpl_propertylist *self, const char *name, int value) { cpl_property *property; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = _cpl_propertylist_get(self, name); if (property == NULL) { return cpl_error_set_message_(CPL_ERROR_DATA_NOT_FOUND, "%s", name); } return cpl_property_set_int(property, value); } /** * @brief * Set the value of the given long property list entry. * * @param self A property list. * @param name The property name to look up. * @param value New long value. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error code * otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_DATA_NOT_FOUND</td> * <td class="ecr"> * The property list <i>self</i> does not contain a property with * the name <i>name</i>. * </td> * </tr> * </table> * @enderror * * The function searches the property list @em self for a property named * @em name. If it is present in the list, its long value is replaced with * the long @em value. If there is more than one property with * the same @em name, it takes the first one from the list. */ cpl_error_code cpl_propertylist_set_long(cpl_propertylist *self, const char *name, long value) { cpl_property *property; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = _cpl_propertylist_get(self, name); if (property == NULL) { return cpl_error_set_message_(CPL_ERROR_DATA_NOT_FOUND, "%s", name); } return cpl_property_set_long(property, value); } /** * @brief * Set the value of the given long long property list entry. * * @param self A property list. * @param name The property name to look up. * @param value New long long value. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error code * otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_DATA_NOT_FOUND</td> * <td class="ecr"> * The property list <i>self</i> does not contain a property with * the name <i>name</i>. * </td> * </tr> * </table> * @enderror * * The function searches the property list @em self for a property named * @em name. If it is present in the list, its long long value is replaced * with @em value. If there is more than one property with the same @em name, * it takes the first one from the list. */ cpl_error_code cpl_propertylist_set_long_long(cpl_propertylist *self, const char *name, long long value) { cpl_property *property; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = _cpl_propertylist_get(self, name); if (property == NULL) { return cpl_error_set_message_(CPL_ERROR_DATA_NOT_FOUND, "%s", name); } return cpl_property_set_long_long(property, value); } /** * @brief * Set the value of the given float property list entry. * * @param self A property list. * @param name The property name to look up. * @param value New float value. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error code * otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_DATA_NOT_FOUND</td> * <td class="ecr"> * The property list <i>self</i> does not contain a property with * the name <i>name</i>. * </td> * </tr> * </table> * @enderror * * The function searches the property list @em self for a property named * @em name. If it is present in the list, its float value is replaced with * the float @em value. If there is more than one property with * the same @em name, it takes the first one from the list. */ cpl_error_code cpl_propertylist_set_float(cpl_propertylist *self, const char *name, float value) { cpl_property *property; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = _cpl_propertylist_get(self, name); if (property == NULL) { return cpl_error_set_message_(CPL_ERROR_DATA_NOT_FOUND, "%s", name); } return cpl_property_set_float(property, value); } /** * @brief * Set the value of the given double property list entry. * * @param self A property list. * @param name The property name to look up. * @param value New double value. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error code * otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_DATA_NOT_FOUND</td> * <td class="ecr"> * The property list <i>self</i> does not contain a property with * the name <i>name</i>. * </td> * </tr> * </table> * @enderror * * The function searches the property list @em self for a property named * @em name. If it is present in the list, its double value is replaced with * the double @em value. If there is more than one property with * the same @em name, it takes the first one from the list. */ cpl_error_code cpl_propertylist_set_double(cpl_propertylist *self, const char *name, double value) { cpl_property *property; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = _cpl_propertylist_get(self, name); if (property == NULL) { return cpl_error_set_message_(CPL_ERROR_DATA_NOT_FOUND, "%s", name); } return cpl_property_set_double(property, value); } /** * @brief * Set the value of the given string property list entry. * * @param self A property list. * @param name The property name to look up. * @param value New string value. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error code * otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i>, <i>name</i> or <i>value</i> is a * <tt>NULL</tt> pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_DATA_NOT_FOUND</td> * <td class="ecr"> * The property list <i>self</i> does not contain a property with * the name <i>name</i>. * </td> * </tr> * </table> * @enderror * * The function searches the property list @em self for a property named * @em name. If it is present in the list, its string value is replaced with * the string @em value. If there is more than one property with * the same @em name, it takes the first one from the list. */ cpl_error_code cpl_propertylist_set_string(cpl_propertylist *self, const char *name, const char *value) { cpl_property *property; if (self == NULL || name == NULL || value == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = _cpl_propertylist_get(self, name); if (property == NULL) { return cpl_error_set_message_(CPL_ERROR_DATA_NOT_FOUND, "%s", name); } return cpl_property_set_string(property, value); } /** * @brief * Set the value of the given float complex property list entry. * * @param self A property list. * @param name The property name to look up. * @param value New float complex value. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error code * otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_DATA_NOT_FOUND</td> * <td class="ecr"> * The property list <i>self</i> does not contain a property with * the name <i>name</i>. * </td> * </tr> * </table> * @enderror * * The function searches the property list @em self for a property named * @em name. If it is present in the list, its float complex value is replaced * with the float complex @em value. If there is more than one property with * the same @em name, it takes the first one from the list. */ cpl_error_code cpl_propertylist_set_float_complex(cpl_propertylist *self, const char *name, float complex value) { cpl_property *property; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = _cpl_propertylist_get(self, name); if (property == NULL) { return cpl_error_set_message_(CPL_ERROR_DATA_NOT_FOUND, "%s", name); } return cpl_property_set_float_complex(property, value) ? cpl_error_set_where_() : CPL_ERROR_NONE; } /** * @brief * Set the value of the given double complex property list entry. * * @param self A property list. * @param name The property name to look up. * @param value New double complex value. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error code * otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_DATA_NOT_FOUND</td> * <td class="ecr"> * The property list <i>self</i> does not contain a property with * the name <i>name</i>. * </td> * </tr> * </table> * @enderror * * The function searches the property list @em self for a property named * @em name. If it is present in the list, its double complex value is replaced * with the double complex @em value. If there is more than one property with * the same @em name, it takes the first one from the list. */ cpl_error_code cpl_propertylist_set_double_complex(cpl_propertylist *self, const char *name, double complex value) { cpl_property *property; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = _cpl_propertylist_get(self, name); if (property == NULL) { return cpl_error_set_message_(CPL_ERROR_DATA_NOT_FOUND, "%s", name); } return cpl_property_set_double_complex(property, value) ? cpl_error_set_where_() : CPL_ERROR_NONE; } /** * @brief * Access property list elements by index. * * @param self The property list to query. * @param position Index of the element to retrieve. * * @return * The function returns the property with index @em position, or @c NULL * if @em position is out of range. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> is a <tt>NULL</tt> pointer. * </td> * </tr> * </table> * @enderror * * The function returns a handle for the property list element, the property, * with the index @em position. Numbering of property list elements extends from * 0 to @b cpl_propertylist_get_size() - 1. If @em position is less than 0 or * greater equal than @b cpl_propertylist_get_size() the function returns * @c NULL. */ const cpl_property * cpl_propertylist_get_const(const cpl_propertylist *self, long position) { #ifdef CPL_PROPERTYLIST_ENABLE_LOOP_CHECK cxsize i = 0; #endif cx_deque_iterator first, last; if (self == NULL) { cpl_error_set_(CPL_ERROR_NULL_INPUT); return NULL; } if (position < 0) { return NULL; } first = cx_deque_begin(self->properties); last = cx_deque_end(self->properties); #ifdef CPL_PROPERTYLIST_ENABLE_LOOP_CHECK /* FIXME: Except from never stopping in a unit test, what does this do? */ while (i < (cxsize)position && first != last) { first = cx_deque_next(self->properties, first); i++; } #endif if (first == last) { return NULL; } if ((cx_deque_const_iterator)position >= last) { return NULL; } return cx_deque_get(self->properties, (cx_deque_const_iterator)position); } /** * @brief * Access property list elements by index. * * @param self The property list to query. * @param position Index of the element to retrieve. * * @return * The function returns the property with index @em position, or @c NULL * if @em position is out of range. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> is a <tt>NULL</tt> pointer. * </td> * </tr> * </table> * @enderror * * The function returns a handle for the property list element, the property, * with the index @em position. Numbering of property list elements extends from * 0 to @b cpl_propertylist_get_size() - 1. If @em position is less than 0 or * greater equal than @b cpl_propertylist_get_size() the function returns * @c NULL. */ cpl_property * cpl_propertylist_get(cpl_propertylist *self, long position) { cpl_errorstate prestate = cpl_errorstate_get(); cpl_property *property; CPL_DIAG_PRAGMA_PUSH_IGN(-Wcast-qual); property = (cpl_property *)cpl_propertylist_get_const(self, position); CPL_DIAG_PRAGMA_POP; if (!cpl_errorstate_is_equal(prestate)) (void)cpl_error_set_where_(); return property; } /** * @brief * Get the comment of the given property list entry. * * @param self A property list. * @param name The property name to look up. * * @return * The comment of the property list entry, or @c NULL. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_DATA_NOT_FOUND</td> * <td class="ecr"> * The property list <i>self</i> does not contain a property with * the name <i>name</i>. * </td> * </tr> * </table> * @enderror * * The function searches the property list @em self for a property named * @em name. If it is present in the list, its comment string is returned. * If an entry with the name @em name is not found, or if the entry has * no comment the function returns @c NULL. If there is more than one property * with the same @em name, it takes the first one from the list. */ const char * cpl_propertylist_get_comment(const cpl_propertylist *self, const char *name) { cpl_property *property; if (self == NULL || name == NULL) { cpl_error_set_(CPL_ERROR_NULL_INPUT); return NULL; } property = _cpl_propertylist_get(self, name); if (!property) { cpl_error_set_message_(CPL_ERROR_DATA_NOT_FOUND, "%s", name); return NULL; } return cpl_property_get_comment(property); } /** * @brief * Get the character value of the given property list entry. * * @param self A property list. * @param name The property name to look up. * * @return * The character value stored in the list entry. The function returns '\\0' * if an error occurs and an appropriate error code is set. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_DATA_NOT_FOUND</td> * <td class="ecr"> * The property list <i>self</i> does not contain a property with * the name <i>name</i>. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_TYPE_MISMATCH</td> * <td class="ecr"> * The sought-after property <i>name</i> is not of type * @c CPL_TYPE_CHAR. * </td> * </tr> * </table> * @enderror * * The function searches the property list @em self for a property named * @em name. If it is present in the list, its character value is returned. * If there is more than one property with the same @em name, it takes the * first one from the list. */ char cpl_propertylist_get_char(const cpl_propertylist *self, const char *name) { cxchar result; cpl_property *property; cpl_errorstate prevstate; if (self == NULL || name == NULL) { cpl_error_set_(CPL_ERROR_NULL_INPUT); return '\0'; } property = _cpl_propertylist_get(self, name); if (!property) { cpl_error_set_message_(CPL_ERROR_DATA_NOT_FOUND, "%s", name); return '\0'; } prevstate = cpl_errorstate_get(); result = cpl_property_get_char(property); /* * If an error occurred change any possible set location to this * function. */ if (!cpl_errorstate_is_equal(prevstate)) { cpl_error_set_where_(); return '\0'; } return result; } /** * @brief * Get the boolean value of the given property list entry. * * @param self A property list. * @param name The property name to look up. * * @return * The integer representation of the boolean value stored in * the list entry. @c TRUE is represented as non-zero value while * 0 indicates @c FALSE. The function returns 0 if an error occurs * and an appropriate error code is set. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_DATA_NOT_FOUND</td> * <td class="ecr"> * The property list <i>self</i> does not contain a property with * the name <i>name</i>. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_TYPE_MISMATCH</td> * <td class="ecr"> * The sought-after property <i>name</i> is not of type * @c CPL_TYPE_BOOL. * </td> * </tr> * </table> * @enderror * * The function searches the property list @em self for a property named * @em name. If it is present in the list, its boolean value is returned. * If there is more than one property with the same @em name, it takes the * first one from the list. */ int cpl_propertylist_get_bool(const cpl_propertylist *self, const char *name) { cxbool result; cpl_property *property; cpl_errorstate prevstate; if (self == NULL || name == NULL) { cpl_error_set_(CPL_ERROR_NULL_INPUT); return 0; } property = _cpl_propertylist_get(self, name); if (!property) { cpl_error_set_message_(CPL_ERROR_DATA_NOT_FOUND, "%s", name); return 0; } prevstate = cpl_errorstate_get(); result = cpl_property_get_bool(property); /* * If an error occurred change any possibly set location to this * function. */ if (!cpl_errorstate_is_equal(prevstate)) { cpl_error_set_where_(); return 0; } return result == TRUE ? 1 : 0; } /** * @brief * Get the integer value of the given property list entry. * * @param self A property list. * @param name The property name to look up. * * @return * The integer value stored in the list entry. The function returns 0 if * an error occurs and an appropriate error code is set. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_DATA_NOT_FOUND</td> * <td class="ecr"> * The property list <i>self</i> does not contain a property with * the name <i>name</i>. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_TYPE_MISMATCH</td> * <td class="ecr"> * The sought-after property <i>name</i> is not of type * @c CPL_TYPE_INT. * </td> * </tr> * </table> * @enderror * * The function searches the property list @em self for a property named * @em name. If it is present in the list, its integer value is returned. * If there is more than one property with the same @em name, it takes the * first one from the list. */ int cpl_propertylist_get_int(const cpl_propertylist *self, const char *name) { cxint result; cpl_property *property; cpl_errorstate prevstate; if (self == NULL || name == NULL) { cpl_error_set_(CPL_ERROR_NULL_INPUT); return 0; } property = _cpl_propertylist_get(self, name); if (!property) { cpl_error_set_message_(CPL_ERROR_DATA_NOT_FOUND, "%s", name); return 0; } prevstate = cpl_errorstate_get(); result = cpl_property_get_int(property); /* * If an error occurred change any possibly set location to this * function. */ if (!cpl_errorstate_is_equal(prevstate)) { cpl_error_set_where_(); return 0; } return result; } /** * @brief * Get the long value of the given property list entry. * * @param self A property list. * @param name The property name to look up. * * @return * The long value stored in the list entry. The function returns 0 if * an error occurs and an appropriate error code is set. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_DATA_NOT_FOUND</td> * <td class="ecr"> * The property list <i>self</i> does not contain a property with * the name <i>name</i>. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_TYPE_MISMATCH</td> * <td class="ecr"> * The sought-after property <i>name</i> is not of type * <tt>CPL_TYPE_LONG</tt> or <tt>CPL_TYPE_INT</tt>. * </td> * </tr> * </table> * @enderror * * The function searches the property list @em self for a property named * @em name. If it is present in the list, its long value is returned. * If there is more than one property with the same @em name, it takes the * first one from the list. * * The function may be used to access the value of all integer type properties * whose integer value has a rank less or equal to the functions return type. * If the value of a compatible property is retrieved, it is promoted to * the return type of the function. */ long cpl_propertylist_get_long(const cpl_propertylist *self, const char *name) { cxlong result; cpl_property *property; cpl_errorstate prevstate; if (self == NULL || name == NULL) { cpl_error_set_(CPL_ERROR_NULL_INPUT); return 0; } property = _cpl_propertylist_get(self, name); if (!property) { cpl_error_set_message_(CPL_ERROR_DATA_NOT_FOUND, "%s", name); return 0; } prevstate = cpl_errorstate_get(); result = cpl_property_get_long(property); /* * If an error occurred change any possibly set location to this * function. */ if (!cpl_errorstate_is_equal(prevstate)) { cpl_error_set_where_(); return 0; } return result; } /** * @brief * Get the long long value of the given property list entry. * * @param self A property list. * @param name The property name to look up. * * @return * The long value stored in the list entry. The function returns 0 if * an error occurs and an appropriate error code is set. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_DATA_NOT_FOUND</td> * <td class="ecr"> * The property list <i>self</i> does not contain a property with * the name <i>name</i>. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_TYPE_MISMATCH</td> * <td class="ecr"> * The sought-after property <i>name</i> is not of type * <tt>CPL_TYPE_LONG_LONG</tt>, <tt>CPL_TYPE_LONG</tt>, or * <tt>CPL_TYPE_INT</tt> * </td> * </tr> * </table> * @enderror * * The function searches the property list @em self for a property named * @em name. If it is present in the list, its long long value is returned. * If there is more than one property with the same @em name, it takes the * first one from the list. * * The function may be used to access the value of all integer type properties * whose integer value has a rank less or equal to the functions return type. * If the value of a compatible property is retrieved, it is promoted to * the return type of the function. */ long long cpl_propertylist_get_long_long(const cpl_propertylist *self, const char *name) { cxllong result; cpl_property *property; cpl_errorstate prevstate; if (self == NULL || name == NULL) { cpl_error_set_(CPL_ERROR_NULL_INPUT); return 0; } property = _cpl_propertylist_get(self, name); if (!property) { cpl_error_set_message_(CPL_ERROR_DATA_NOT_FOUND, "%s", name); return 0; } prevstate = cpl_errorstate_get(); result = cpl_property_get_long_long(property); /* * If an error occurred change any possibly set location to this * function. */ if (!cpl_errorstate_is_equal(prevstate)) { cpl_error_set_where_(); return 0; } return result; } /** * @brief * Get the float value of the given property list entry. * * @param self A property list. * @param name The property name to look up. * * @return * The float value stored in the list entry. The function returns 0 if * an error occurs and an appropriate error code is set. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_DATA_NOT_FOUND</td> * <td class="ecr"> * The property list <i>self</i> does not contain a property with * the name <i>name</i>. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_TYPE_MISMATCH</td> * <td class="ecr"> * The sought-after property <i>name</i> is not of type * @c CPL_TYPE_FLOAT or @c CPL_TYPE_DOUBLE. * </td> * </tr> * </table> * @enderror * * The function searches the property list @em self for a property named * @em name. If it is present in the list, its float value is returned. * If there is more than one property with the same @em name, it takes the * first one from the list. If the value is of type double, the function * casts it to float before returning it. */ float cpl_propertylist_get_float(const cpl_propertylist *self, const char *name) { cxfloat result; cpl_property *property; cpl_errorstate prevstate; if (self == NULL || name == NULL) { cpl_error_set_(CPL_ERROR_NULL_INPUT); return 0; } property = _cpl_propertylist_get(self, name); if (!property) { cpl_error_set_message_(CPL_ERROR_DATA_NOT_FOUND, "%s", name); return 0; } prevstate = cpl_errorstate_get(); result = cpl_property_get_float(property); /* * If an error occurred change any possibly set location to this * function. */ if (!cpl_errorstate_is_equal(prevstate)) { cpl_error_set_where_(); return 0; } return result; } /** * @brief * Get the double value of the given property list entry. * * @param self A property list. * @param name The property name to look up. * * @return * The double value stored in the list entry. The function returns 0 if * an error occurs and an appropriate error code is set. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_DATA_NOT_FOUND</td> * <td class="ecr"> * The property list <i>self</i> does not contain a property with * the name <i>name</i>. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_TYPE_MISMATCH</td> * <td class="ecr"> * The sought-after property <i>name</i> is not of type * <tt>CPL_TYPE_DOUBLE</tt> or <tt>CPL_TYPE_FLOAT</tt>. * </td> * </tr> * </table> * @enderror * * The function searches the property list @em self for a property named * @em name. If it is present in the list, its double value is returned. * If there is more than one property with the same @em name, it takes the * first one from the list. If the value is of type float, the function * casts it to double before returning it. * * The function may be used to access the value of all floating-point type * properties whose floating-point value has a rank less or equal to the * functions return type. If the value of a compatible property is retrieved, * it is promoted to the return type of the function. */ double cpl_propertylist_get_double(const cpl_propertylist *self, const char *name) { cxdouble result; cpl_property *property; cpl_errorstate prevstate; if (self == NULL || name == NULL) { cpl_error_set_(CPL_ERROR_NULL_INPUT); return 0; } property = _cpl_propertylist_get(self, name); if (!property) { cpl_error_set_message_(CPL_ERROR_DATA_NOT_FOUND, "%s", name); return 0; } prevstate = cpl_errorstate_get(); result = cpl_property_get_double(property); /* * If an error occurred change any possibly set location to this * function. */ if (!cpl_errorstate_is_equal(prevstate)) { cpl_error_set_where_(); return 0; } return result; } /** * @brief * Get the string value of the given property list entry. * * @param self A property list. * @param name The property name to look up. * * @return * A handle to the string value stored in the list entry. The * function returns @c NULL if an error occurs and an appropriate * error code is set. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_DATA_NOT_FOUND</td> * <td class="ecr"> * The property list <i>self</i> does not contain a property with * the name <i>name</i>. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_TYPE_MISMATCH</td> * <td class="ecr"> * The sought-after property <i>name</i> is not of type * @c CPL_TYPE_STRING. * </td> * </tr> * </table> * @enderror * * The function searches the property list @em self for a property named * @em name. If it is present in the list, a handle to its string value * is returned. If there is more than one property with the same @em name, * it takes the first one from the list. */ const char * cpl_propertylist_get_string(const cpl_propertylist *self, const char *name) { const cxchar *result; cpl_property *property; cpl_errorstate prevstate; if (self == NULL || name == NULL) { cpl_error_set_(CPL_ERROR_NULL_INPUT); return NULL; } property = _cpl_propertylist_get(self, name); if (!property) { cpl_error_set_message_(CPL_ERROR_DATA_NOT_FOUND, "%s", name); return NULL; } prevstate = cpl_errorstate_get(); result = cpl_property_get_string(property); /* * If an error occurred change any possibly set location to this * function. */ if (!cpl_errorstate_is_equal(prevstate)) { cpl_error_set_where_(); return NULL; } return result; } /** * @brief * Get the float complex value of the given property list entry. * * @param self A property list. * @param name The property name to look up. * * @return * The float complex value stored in the list entry. The function returns 0 if * an error occurs and an appropriate error code is set. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_DATA_NOT_FOUND</td> * <td class="ecr"> * The property list <i>self</i> does not contain a property with * the name <i>name</i>. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_TYPE_MISMATCH</td> * <td class="ecr"> * The sought-after property <i>name</i> is not of type * @c CPL_TYPE_FLOAT_COMPLEX or @c CPL_TYPE_DOUBLE_COMPLEX. * </td> * </tr> * </table> * @enderror * * The function searches the property list @em self for a property named * @em name. If it is present in the list, its float complex value is returned. * If there is more than one property with the same @em name, it takes the * first one from the list. If the value is of type double, the function * casts it to float complex before returning it. */ float complex cpl_propertylist_get_float_complex(const cpl_propertylist *self, const char *name) { float complex result; cpl_property *property; cpl_errorstate prevstate; if (self == NULL || name == NULL) { (void)cpl_error_set_(CPL_ERROR_NULL_INPUT); return 0.0; } property = _cpl_propertylist_get(self, name); if (!property) { (void)cpl_error_set_message_(CPL_ERROR_DATA_NOT_FOUND, "%s", name); return 0.0; } prevstate = cpl_errorstate_get(); result = cpl_property_get_float_complex(property); /* * If an error occurred change any possibly set location to this * function. */ if (!cpl_errorstate_is_equal(prevstate)) { (void)cpl_error_set_where_(); return 0.0; } return result; } /** * @brief * Get the double complex value of the given property list entry. * * @param self A property list. * @param name The property name to look up. * * @return * The double complex value stored in the list entry. The function returns 0 if * an error occurs and an appropriate error code is set. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_DATA_NOT_FOUND</td> * <td class="ecr"> * The property list <i>self</i> does not contain a property with * the name <i>name</i>. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_TYPE_MISMATCH</td> * <td class="ecr"> * The sought-after property <i>name</i> is not of type * @c CPL_TYPE_DOUBLE_COMPLEX or @c CPL_TYPE_FLOAT_COMPLEX. * </td> * </tr> * </table> * @enderror * * The function searches the property list @em self for a property named * @em name. If it is present in the list, its double complex value is returned. * If there is more than one property with the same @em name, it takes the * first one from the list. If the value is of type float, the function * casts it to double complex before returning it. * * The function may be used to access the value of all complex type * properties whose complex value has a rank less or equal to the * functions return type. If the value of a compatible property is retrieved, * it is promoted to the return type of the function. */ double complex cpl_propertylist_get_double_complex(const cpl_propertylist *self, const char *name) { double complex result; cpl_property *property; cpl_errorstate prevstate; if (self == NULL || name == NULL) { (void)cpl_error_set_(CPL_ERROR_NULL_INPUT); return 0.0; } property = _cpl_propertylist_get(self, name); if (!property) { (void)cpl_error_set_message_(CPL_ERROR_DATA_NOT_FOUND, "%s", name); return 0.0; } prevstate = cpl_errorstate_get(); result = cpl_property_get_double_complex(property); /* * If an error occurred change any possibly set location to this * function. */ if (!cpl_errorstate_is_equal(prevstate)) { (void)cpl_error_set_where_(); return 0.0; } return result; } /** * @brief * Insert a character value into a property list at the given position. * * @param self A property list. * @param here Name indicating the position at which the value is inserted. * @param name The property name to be assigned to the value. * @param value The character value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i>, <i>here</i> or <i>name</i> is a * <tt>NULL</tt> pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_UNSPECIFIED</td> * <td class="ecr"> * A property with the name <i>name</i> could not be inserted * into <i>self</i>. * </td> * </tr> * </table> * @enderror * * The function creates a new character property with name @em name and * value @em value. The property is inserted into the property list * @em self at the position of the property named @em here. */ cpl_error_code cpl_propertylist_insert_char(cpl_propertylist *self, const char *here, const char *name, char value) { cxint status = 0; if (self == NULL || here == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } status = _cpl_propertylist_insert(self, here, FALSE, name, CPL_TYPE_CHAR, (cxcptr)&value); if (status) { return cpl_error_set_(CPL_ERROR_UNSPECIFIED); } return CPL_ERROR_NONE; } /** * @brief * Insert a boolean value into a property list at the given position. * * @param self A property list. * @param here Name indicating the position at which the value is inserted. * @param name The property name to be assigned to the value. * @param value The boolean value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i>, <i>here</i> or <i>name</i> is a * <tt>NULL</tt> pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_UNSPECIFIED</td> * <td class="ecr"> * A property with the name <i>name</i> could not be inserted * into <i>self</i>. * </td> * </tr> * </table> * @enderror * * The function creates a new boolean property with name @em name and * value @em value. The property is inserted into the property list * @em self at the position of the property named @em here. */ cpl_error_code cpl_propertylist_insert_bool(cpl_propertylist *self, const char *here, const char *name, int value) { cxint status = 0; if (self == NULL || here == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } status = _cpl_propertylist_insert(self, here, FALSE, name, CPL_TYPE_BOOL, (cxcptr)&value); if (status) { return cpl_error_set_(CPL_ERROR_UNSPECIFIED); } return CPL_ERROR_NONE; } /** * @brief * Insert a integer value into a property list at the given position. * * @param self A property list. * @param here Name indicating the position at which the value is inserted. * @param name The property name to be assigned to the value. * @param value The integer value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i>, <i>here</i> or <i>name</i> is a * <tt>NULL</tt> pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_UNSPECIFIED</td> * <td class="ecr"> * A property with the name <i>name</i> could not be inserted * into <i>self</i>. * </td> * </tr> * </table> * @enderror * * The function creates a new integer property with name @em name and * value @em value. The property is inserted into the property list * @em self at the position of the property named @em here. */ cpl_error_code cpl_propertylist_insert_int(cpl_propertylist *self, const char *here, const char *name, int value) { cxint status = 0; if (self == NULL || here == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } status = _cpl_propertylist_insert(self, here, FALSE, name, CPL_TYPE_INT, (cxcptr)&value); if (status) { return cpl_error_set_(CPL_ERROR_UNSPECIFIED); } return CPL_ERROR_NONE; } /** * @brief * Insert a long value into a property list at the given position. * * @param self A property list. * @param here Name indicating the position at which the value is inserted. * @param name The property name to be assigned to the value. * @param value The long value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i>, <i>here</i> or <i>name</i> is a * <tt>NULL</tt> pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_UNSPECIFIED</td> * <td class="ecr"> * A property with the name <i>name</i> could not be inserted * into <i>self</i>. * </td> * </tr> * </table> * @enderror * * The function creates a new long property with name @em name and * value @em value. The property is inserted into the property list * @em self at the position of the property named @em here. */ cpl_error_code cpl_propertylist_insert_long(cpl_propertylist *self, const char *here, const char *name, long value) { cxint status = 0; if (self == NULL || here == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } status = _cpl_propertylist_insert(self, here, FALSE, name, CPL_TYPE_LONG, (cxcptr)&value); if (status) { return cpl_error_set_(CPL_ERROR_UNSPECIFIED); } return CPL_ERROR_NONE; } /** * @brief * Insert a long long value into a property list at the given position. * * @param self A property list. * @param here Name indicating the position at which the value is inserted. * @param name The property name to be assigned to the value. * @param value The long long value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i>, <i>here</i> or <i>name</i> is a * <tt>NULL</tt> pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_UNSPECIFIED</td> * <td class="ecr"> * A property with the name <i>name</i> could not be inserted * into <i>self</i>. * </td> * </tr> * </table> * @enderror * * The function creates a new long long property with name @em name and * value @em value. The property is inserted into the property list * @em self at the position of the property named @em here. */ cpl_error_code cpl_propertylist_insert_long_long(cpl_propertylist *self, const char *here, const char *name, long long value) { cxint status = 0; if (self == NULL || here == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } status = _cpl_propertylist_insert(self, here, FALSE, name, CPL_TYPE_LONG_LONG, (cxcptr)&value); if (status) { return cpl_error_set_(CPL_ERROR_UNSPECIFIED); } return CPL_ERROR_NONE; } /** * @brief * Insert a float value into a property list at the given position. * * @param self A property list. * @param here Name indicating the position at which the value is inserted. * @param name The property name to be assigned to the value. * @param value The float value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i>, <i>here</i> or <i>name</i> is a * <tt>NULL</tt> pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_UNSPECIFIED</td> * <td class="ecr"> * A property with the name <i>name</i> could not be inserted * into <i>self</i>. * </td> * </tr> * </table> * @enderror * * The function creates a new float property with name @em name and * value @em value. The property is inserted into the property list * @em self at the position of the property named @em here. */ cpl_error_code cpl_propertylist_insert_float(cpl_propertylist *self, const char *here, const char *name, float value) { cxint status = 0; if (self == NULL || here == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } status = _cpl_propertylist_insert(self, here, FALSE, name, CPL_TYPE_FLOAT, (cxcptr)&value); if (status) { return cpl_error_set_(CPL_ERROR_UNSPECIFIED); } return CPL_ERROR_NONE; } /** * @brief * Insert a double value into a property list at the given position. * * @param self A property list. * @param here Name indicating the position at which the value is inserted. * @param name The property name to be assigned to the value. * @param value The double value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i>, <i>here</i> or <i>name</i> is a * <tt>NULL</tt> pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_UNSPECIFIED</td> * <td class="ecr"> * A property with the name <i>name</i> could not be inserted * into <i>self</i>. * </td> * </tr> * </table> * @enderror * * The function creates a new double property with name @em name and * value @em value. The property is inserted into the property list * @em self at the position of the property named @em here. */ cpl_error_code cpl_propertylist_insert_double(cpl_propertylist *self, const char *here, const char *name, double value) { cxint status = 0; if (self == NULL || here == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } status = _cpl_propertylist_insert(self, here, FALSE, name, CPL_TYPE_DOUBLE, (cxcptr)&value); if (status) { return cpl_error_set_(CPL_ERROR_UNSPECIFIED); } return CPL_ERROR_NONE; } /** * @brief * Insert a string value into a property list at the given position. * * @param self A property list. * @param here Name indicating the position at which the value is inserted. * @param name The property name to be assigned to the value. * @param value The string value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i>, <i>here</i>, <i>name</i> or <i>value</i> * or <i>name</i> is a <tt>NULL</tt> pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_UNSPECIFIED</td> * <td class="ecr"> * A property with the name <i>name</i> could not be inserted * into <i>self</i>. * </td> * </tr> * </table> * @enderror * * The function creates a new string property with name @em name and * value @em value. The property is inserted into the property list * @em self at the position of the property named @em here. */ cpl_error_code cpl_propertylist_insert_string(cpl_propertylist *self, const char *here, const char *name, const char *value) { cxint status = 0; if (self == NULL || here == NULL || name == NULL || value == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } status = _cpl_propertylist_insert(self, here, FALSE, name, CPL_TYPE_STRING, (cxcptr)value); if (status) { return cpl_error_set_(CPL_ERROR_UNSPECIFIED); } return CPL_ERROR_NONE; } /** * @brief * Insert a float complex value into a property list at the given position. * * @param self A property list. * @param here Name indicating the position at which the value is inserted. * @param name The property name to be assigned to the value. * @param value The float complex value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i>, <i>here</i> or <i>name</i> is a * <tt>NULL</tt> pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_UNSPECIFIED</td> * <td class="ecr"> * A property with the name <i>name</i> could not be inserted * into <i>self</i>. * </td> * </tr> * </table> * @enderror * * The function creates a new float complex property with name @em name and * value @em value. The property is inserted into the property list * @em self at the position of the property named @em here. */ cpl_error_code cpl_propertylist_insert_float_complex(cpl_propertylist *self, const char *here, const char *name, float complex value) { if (self == NULL || here == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } return _cpl_propertylist_insert(self, here, FALSE, name, CPL_TYPE_FLOAT_COMPLEX, (cxcptr)&value) ? cpl_error_set_(CPL_ERROR_UNSPECIFIED) : CPL_ERROR_NONE; } /** * @brief * Insert a double complex value into a property list at the given position. * * @param self A property list. * @param here Name indicating the position at which the value is inserted. * @param name The property name to be assigned to the value. * @param value The double complex value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i>, <i>here</i> or <i>name</i> is a * <tt>NULL</tt> pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_UNSPECIFIED</td> * <td class="ecr"> * A property with the name <i>name</i> could not be inserted * into <i>self</i>. * </td> * </tr> * </table> * @enderror * * The function creates a new double complex property with name @em name and * value @em value. The property is inserted into the property list * @em self at the position of the property named @em here. */ cpl_error_code cpl_propertylist_insert_double_complex(cpl_propertylist *self, const char *here, const char *name, double complex value) { if (self == NULL || here == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } return _cpl_propertylist_insert(self, here, FALSE, name, CPL_TYPE_DOUBLE_COMPLEX, (cxcptr)&value) ? cpl_error_set_(CPL_ERROR_UNSPECIFIED) : CPL_ERROR_NONE; } /** * @brief * Insert a character value into a property list after the given position. * * @param self A property list. * @param after Name of the property after which the value is inserted. * @param name The property name to be assigned to the value. * @param value The character value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i>, <i>after</i> or <i>name</i> is a * <tt>NULL</tt> pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_UNSPECIFIED</td> * <td class="ecr"> * A property with the name <i>name</i> could not be inserted * into <i>self</i>. * </td> * </tr> * </table> * @enderror * * The function creates a new character property with name @em name and * value @em value. The property is inserted into the property list * @em self after the property named @em after. */ cpl_error_code cpl_propertylist_insert_after_char(cpl_propertylist *self, const char *after, const char *name, char value) { cxint status = 0; if (self == NULL || after == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } status = _cpl_propertylist_insert(self, after, TRUE, name, CPL_TYPE_CHAR, (cxcptr)&value); if (status) { return cpl_error_set_(CPL_ERROR_UNSPECIFIED); } return CPL_ERROR_NONE; } /** * @brief * Insert a boolean value into a property list after the given position. * * @param self A property list. * @param after Name of the property after which the value is inserted. * @param name The property name to be assigned to the value. * @param value The boolean value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i>, <i>after</i> or <i>name</i> is a * <tt>NULL</tt> pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_UNSPECIFIED</td> * <td class="ecr"> * A property with the name <i>name</i> could not be inserted * into <i>self</i>. * </td> * </tr> * </table> * @enderror * * The function creates a new boolean property with name @em name and * value @em value. The property is inserted into the property list * @em self after the property named @em after. */ cpl_error_code cpl_propertylist_insert_after_bool(cpl_propertylist *self, const char *after, const char *name, int value) { cxint status = 0; if (self == NULL || after == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } status = _cpl_propertylist_insert(self, after, TRUE, name, CPL_TYPE_BOOL, (cxcptr)&value); if (status) { return cpl_error_set_(CPL_ERROR_UNSPECIFIED); } return CPL_ERROR_NONE; } /** * @brief * Insert a integer value into a property list after the given position. * * @param self A property list. * @param after Name of the property after which the value is inserted. * @param name The property name to be assigned to the value. * @param value The integer value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i>, <i>after</i> or <i>name</i> is a * <tt>NULL</tt> pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_UNSPECIFIED</td> * <td class="ecr"> * A property with the name <i>name</i> could not be inserted * into <i>self</i>. * </td> * </tr> * </table> * @enderror * * The function creates a new integer property with name @em name and * value @em value. The property is inserted into the property list * @em self after the property named @em after. */ cpl_error_code cpl_propertylist_insert_after_int(cpl_propertylist *self, const char *after, const char *name, int value) { cxint status = 0; if (self == NULL || after == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } status = _cpl_propertylist_insert(self, after, TRUE, name, CPL_TYPE_INT, (cxcptr)&value); if (status) { return cpl_error_set_(CPL_ERROR_UNSPECIFIED); } return CPL_ERROR_NONE; } /** * @brief * Insert a long value into a property list after the given position. * * @param self A property list. * @param after Name of the property after which the value is inserted. * @param name The property name to be assigned to the value. * @param value The long value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i>, <i>after</i> or <i>name</i> is a * <tt>NULL</tt> pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_UNSPECIFIED</td> * <td class="ecr"> * A property with the name <i>name</i> could not be inserted * into <i>self</i>. * </td> * </tr> * </table> * @enderror * * The function creates a new long property with name @em name and * value @em value. The property is inserted into the property list * @em self after the property named @em after. */ cpl_error_code cpl_propertylist_insert_after_long(cpl_propertylist *self, const char *after, const char *name, long value) { cxint status = 0; if (self == NULL || after == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } status = _cpl_propertylist_insert(self, after, TRUE, name, CPL_TYPE_LONG, (cxcptr)&value); if (status) { return cpl_error_set_(CPL_ERROR_UNSPECIFIED); } return CPL_ERROR_NONE; } /** * @brief * Insert a long long value into a property list after the given position. * * @param self A property list. * @param after Name of the property after which the value is inserted. * @param name The property name to be assigned to the value. * @param value The long long value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i>, <i>after</i> or <i>name</i> is a * <tt>NULL</tt> pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_UNSPECIFIED</td> * <td class="ecr"> * A property with the name <i>name</i> could not be inserted * into <i>self</i>. * </td> * </tr> * </table> * @enderror * * The function creates a new long long property with name @em name and * value @em value. The property is inserted into the property list * @em self after the property named @em after. */ cpl_error_code cpl_propertylist_insert_after_long_long(cpl_propertylist *self, const char *after, const char *name, long long value) { cxint status = 0; if (self == NULL || after == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } status = _cpl_propertylist_insert(self, after, TRUE, name, CPL_TYPE_LONG_LONG, (cxcptr)&value); if (status) { return cpl_error_set_(CPL_ERROR_UNSPECIFIED); } return CPL_ERROR_NONE; } /** * @brief * Insert a float value into a property list after the given position. * * @param self A property list. * @param after Name of the property after which the value is inserted. * @param name The property name to be assigned to the value. * @param value The float value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i>, <i>after</i> or <i>name</i> is a * <tt>NULL</tt> pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_UNSPECIFIED</td> * <td class="ecr"> * A property with the name <i>name</i> could not be inserted * into <i>self</i>. * </td> * </tr> * </table> * @enderror * * The function creates a new float property with name @em name and * value @em value. The property is inserted into the property list * @em self after the property named @em after. */ cpl_error_code cpl_propertylist_insert_after_float(cpl_propertylist *self, const char *after, const char *name, float value) { cxint status = 0; if (self == NULL || after == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } status = _cpl_propertylist_insert(self, after, TRUE, name, CPL_TYPE_FLOAT, (cxcptr)&value); if (status) { return cpl_error_set_(CPL_ERROR_UNSPECIFIED); } return CPL_ERROR_NONE; } /** * @brief * Insert a double value into a property list after the given position. * * @param self A property list. * @param after Name of the property after which the value is inserted. * @param name The property name to be assigned to the value. * @param value The double value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i>, <i>after</i> or <i>name</i> is a * <tt>NULL</tt> pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_UNSPECIFIED</td> * <td class="ecr"> * A property with the name <i>name</i> could not be inserted * into <i>self</i>. * </td> * </tr> * </table> * @enderror * * The function creates a new double property with name @em name and * value @em value. The property is inserted into the property list * @em self after the property named @em after. */ cpl_error_code cpl_propertylist_insert_after_double(cpl_propertylist *self, const char *after, const char *name, double value) { cxint status = 0; if (self == NULL || after == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } status = _cpl_propertylist_insert(self, after, TRUE, name, CPL_TYPE_DOUBLE, (cxcptr)&value); if (status) { return cpl_error_set_(CPL_ERROR_UNSPECIFIED); } return CPL_ERROR_NONE; } /** * @brief * Insert a string value into a property list after the given position. * * @param self A property list. * @param after Name of the property after which the value is inserted. * @param name The property name to be assigned to the value. * @param value The string value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i>, <i>after</i>, <i>name</i> or <i>value</i> * or <i>name</i> is a <tt>NULL</tt> pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_UNSPECIFIED</td> * <td class="ecr"> * A property with the name <i>name</i> could not be inserted * into <i>self</i>. * </td> * </tr> * </table> * @enderror * * The function creates a new string property with name @em name and * value @em value. The property is inserted into the property list * @em self after the property named @em after. */ cpl_error_code cpl_propertylist_insert_after_string(cpl_propertylist *self, const char *after, const char *name, const char *value) { cxint status = 0; if (self == NULL || after == NULL || name == NULL || value == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } status = _cpl_propertylist_insert(self, after, TRUE, name, CPL_TYPE_STRING, (cxcptr)value); if (status) { return cpl_error_set_(CPL_ERROR_UNSPECIFIED); } return CPL_ERROR_NONE; } /** * @brief * Insert a float complex value into a property list after the given position. * * @param self A property list. * @param after Name of the property after which the value is inserted. * @param name The property name to be assigned to the value. * @param value The float complex value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i>, <i>after</i> or <i>name</i> is a * <tt>NULL</tt> pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_UNSPECIFIED</td> * <td class="ecr"> * A property with the name <i>name</i> could not be inserted * into <i>self</i>. * </td> * </tr> * </table> * @enderror * * The function creates a new float complex property with name @em name and * value @em value. The property is inserted into the property list * @em self after the property named @em after. */ cpl_error_code cpl_propertylist_insert_after_float_complex(cpl_propertylist *self, const char *after, const char *name, float complex value) { if (self == NULL || after == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } return _cpl_propertylist_insert(self, after, TRUE, name, CPL_TYPE_FLOAT_COMPLEX, (cxcptr)&value) ? cpl_error_set_(CPL_ERROR_UNSPECIFIED) : CPL_ERROR_NONE; } /** * @brief * Insert a double complex value into a property list after the given position. * * @param self A property list. * @param after Name of the property after which the value is inserted. * @param name The property name to be assigned to the value. * @param value The double complex value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i>, <i>after</i> or <i>name</i> is a * <tt>NULL</tt> pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_UNSPECIFIED</td> * <td class="ecr"> * A property with the name <i>name</i> could not be inserted * into <i>self</i>. * </td> * </tr> * </table> * @enderror * * The function creates a new double complex property with name @em name and * value @em value. The property is inserted into the property list * @em self after the property named @em after. */ cpl_error_code cpl_propertylist_insert_after_double_complex(cpl_propertylist *self, const char *after, const char *name, double complex value) { if (self == NULL || after == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } return _cpl_propertylist_insert(self, after, TRUE, name, CPL_TYPE_DOUBLE_COMPLEX, (cxcptr)&value) ? cpl_error_set_(CPL_ERROR_UNSPECIFIED) : CPL_ERROR_NONE; } /** * @brief * Prepend a character value to a property list. * * @param self A property list. * @param name The property name to be assigned to the value. * @param value The character value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * </table> * @enderror * * The function creates a new character property with name @em name and * value @em value. The property is prepended to the property list @em self. */ cpl_error_code cpl_propertylist_prepend_char(cpl_propertylist *self, const char *name, char value) { cpl_property *property = NULL; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = cpl_property_new(name, CPL_TYPE_CHAR); cx_assert(property != NULL); cpl_property_set_char(property, value); cx_deque_push_front(self->properties, property); return CPL_ERROR_NONE; } /** * @brief * Prepend a boolean value to a property list. * * @param self A property list. * @param name The property name to be assigned to the value. * @param value The boolean value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * </table> * @enderror * * The function creates a new boolean property with name @em name and * value @em value. The property is prepended to the property list @em self. */ cpl_error_code cpl_propertylist_prepend_bool(cpl_propertylist *self, const char *name, int value) { cpl_property *property = NULL; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = cpl_property_new(name, CPL_TYPE_BOOL); cx_assert(property != NULL); cpl_property_set_bool(property, value); cx_deque_push_front(self->properties, property); return CPL_ERROR_NONE; } /** * @brief * Prepend a integer value to a property list. * * @param self A property list. * @param name The property name to be assigned to the value. * @param value The integer value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * </table> * @enderror * * The function creates a new integer property with name @em name and * value @em value. The property is prepended to the property list @em self. */ cpl_error_code cpl_propertylist_prepend_int(cpl_propertylist *self, const char *name, int value) { cpl_property *property = NULL; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = cpl_property_new(name, CPL_TYPE_INT); cx_assert(property != NULL); cpl_property_set_int(property, value); cx_deque_push_front(self->properties, property); return CPL_ERROR_NONE; } /** * @brief * Prepend a long value to a property list. * * @param self A property list. * @param name The property name to be assigned to the value. * @param value The long value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * </table> * @enderror * * The function creates a new long property with name @em name and * value @em value. The property is prepended to the property list @em self. */ cpl_error_code cpl_propertylist_prepend_long(cpl_propertylist *self, const char *name, long value) { cpl_property *property = NULL; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = cpl_property_new(name, CPL_TYPE_LONG); cx_assert(property != NULL); cpl_property_set_long(property, value); cx_deque_push_front(self->properties, property); return CPL_ERROR_NONE; } /** * @brief * Prepend a long long value to a property list. * * @param self A property list. * @param name The property name to be assigned to the value. * @param value The long long value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * </table> * @enderror * * The function creates a new long long property with name @em name and * value @em value. The property is prepended to the property list @em self. */ cpl_error_code cpl_propertylist_prepend_long_long(cpl_propertylist *self, const char *name, long long value) { cpl_property *property = NULL; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = cpl_property_new(name, CPL_TYPE_LONG_LONG); cx_assert(property != NULL); cpl_property_set_long_long(property, value); cx_deque_push_front(self->properties, property); return CPL_ERROR_NONE; } /** * @brief * Prepend a float value to a property list. * * @param self A property list. * @param name The property name to be assigned to the value. * @param value The float value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * </table> * @enderror * * The function creates a new float property with name @em name and * value @em value. The property is prepended to the property list @em self. */ cpl_error_code cpl_propertylist_prepend_float(cpl_propertylist *self, const char *name, float value) { cpl_property *property = NULL; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = cpl_property_new(name, CPL_TYPE_FLOAT); cx_assert(property != NULL); cpl_property_set_float(property, value); cx_deque_push_front(self->properties, property); return CPL_ERROR_NONE; } /** * @brief * Prepend a double value to a property list. * * @param self A property list. * @param name The property name to be assigned to the value. * @param value The double value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * </table> * @enderror * * The function creates a new double property with name @em name and * value @em value. The property is prepended to the property list @em self. */ cpl_error_code cpl_propertylist_prepend_double(cpl_propertylist *self, const char *name, double value) { cpl_property *property = NULL; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = cpl_property_new(name, CPL_TYPE_DOUBLE); cx_assert(property != NULL); cpl_property_set_double(property, value); cx_deque_push_front(self->properties, property); return CPL_ERROR_NONE; } /** * @brief * Prepend a string value to a property list. * * @param self A property list. * @param name The property name to be assigned to the value. * @param value The string value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i>, <i>name</i> or <i>value</i> is a * <tt>NULL</tt> pointer. * </td> * </tr> * </table> * @enderror * * The function creates a new string property with name @em name and * value @em value. The property is prepended to the property list @em self. */ cpl_error_code cpl_propertylist_prepend_string(cpl_propertylist *self, const char *name, const char *value) { cpl_property *property = NULL; if (self == NULL || name == NULL || value == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = cpl_property_new(name, CPL_TYPE_STRING); cx_assert(property != NULL); cpl_property_set_string(property, value); cx_deque_push_front(self->properties, property); return CPL_ERROR_NONE; } /** * @brief * Prepend a float complex value to a property list. * * @param self A property list. * @param name The property name to be assigned to the value. * @param value The float complex value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * </table> * @enderror * * The function creates a new float complex property with name @em name and * value @em value. The property is prepended to the property list @em self. */ cpl_error_code cpl_propertylist_prepend_float_complex(cpl_propertylist *self, const char *name, float complex value) { cpl_property *property = NULL; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = cpl_property_new(name, CPL_TYPE_FLOAT_COMPLEX); cx_assert(property != NULL); cpl_property_set_float_complex(property, value); cx_deque_push_front(self->properties, property); return CPL_ERROR_NONE; } /** * @brief * Prepend a double complex value to a property list. * * @param self A property list. * @param name The property name to be assigned to the value. * @param value The double complex value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * </table> * @enderror * * The function creates a new double complex property with name @em name and * value @em value. The property is prepended to the property list @em self. */ cpl_error_code cpl_propertylist_prepend_double_complex(cpl_propertylist *self, const char *name, double complex value) { cpl_property *property = NULL; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = cpl_property_new(name, CPL_TYPE_DOUBLE_COMPLEX); cx_assert(property != NULL); cpl_property_set_double_complex(property, value); cx_deque_push_front(self->properties, property); return CPL_ERROR_NONE; } /** * @brief * Append a character value to a property list. * * @param self A property list. * @param name The property name to be assigned to the value. * @param value The character value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * </table> * @enderror * * The function creates a new character property with name @em name and * value @em value. The property is appended to the property list @em self. */ cpl_error_code cpl_propertylist_append_char(cpl_propertylist *self, const char *name, char value) { cpl_property *property = NULL; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = cpl_property_new(name, CPL_TYPE_CHAR); cx_assert(property != NULL); cpl_property_set_char(property, value); cx_deque_push_back(self->properties, property); return CPL_ERROR_NONE; } /** * @brief * Append a boolean value to a property list. * * @param self A property list. * @param name The property name to be assigned to the value. * @param value The boolean value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * </table> * @enderror * * The function creates a new boolean property with name @em name and * value @em value. The property is appended to the property list @em self. */ cpl_error_code cpl_propertylist_append_bool(cpl_propertylist *self, const char *name, int value) { cpl_property *property = NULL; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = cpl_property_new(name, CPL_TYPE_BOOL); cx_assert(property != NULL); cpl_property_set_bool(property, value); cx_deque_push_back(self->properties, property); return CPL_ERROR_NONE; } /** * @brief * Append an integer value to a property list. * * @param self A property list. * @param name The property name to be assigned to the value. * @param value The integer value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * </table> * @enderror * * The function creates a new integer property with name @em name and * value @em value. The property is appended to the property list @em self. */ cpl_error_code cpl_propertylist_append_int(cpl_propertylist *self, const char *name, int value) { cpl_property *property = NULL; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = cpl_property_new(name, CPL_TYPE_INT); cx_assert(property != NULL); cpl_property_set_int(property, value); cx_deque_push_back(self->properties, property); return CPL_ERROR_NONE; } /** * @brief * Append a long value to a property list. * * @param self A property list. * @param name The property name to be assigned to the value. * @param value The long value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * </table> * @enderror * * The function creates a new long property with name @em name and * value @em value. The property is appended to the property list @em self. */ cpl_error_code cpl_propertylist_append_long(cpl_propertylist *self, const char *name, long value) { cpl_property *property = NULL; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = cpl_property_new(name, CPL_TYPE_LONG); cx_assert(property != NULL); cpl_property_set_long(property, value); cx_deque_push_back(self->properties, property); return CPL_ERROR_NONE; } /** * @brief * Append a long long value to a property list. * * @param self A property list. * @param name The property name to be assigned to the value. * @param value The long long value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * </table> * @enderror * * The function creates a new long long property with name @em name and * value @em value. The property is appended to the property list @em self. */ cpl_error_code cpl_propertylist_append_long_long(cpl_propertylist *self, const char *name, long long value) { cpl_property *property = NULL; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = cpl_property_new(name, CPL_TYPE_LONG_LONG); cx_assert(property != NULL); cpl_property_set_long_long(property, value); cx_deque_push_back(self->properties, property); return CPL_ERROR_NONE; } /** * @brief * Append a float value to a property list. * * @param self A property list. * @param name The property name to be assigned to the value. * @param value The float value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * </table> * @enderror * * The function creates a new float property with name @em name and * value @em value. The property is appended to the property list @em self. */ cpl_error_code cpl_propertylist_append_float(cpl_propertylist *self, const char *name, float value) { cpl_property *property = NULL; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = cpl_property_new(name, CPL_TYPE_FLOAT); cx_assert(property != NULL); cpl_property_set_float(property, value); cx_deque_push_back(self->properties, property); return CPL_ERROR_NONE; } /** * @brief * Append a double value to a property list. * * @param self A property list. * @param name The property name to be assigned to the value. * @param value The double value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * </table> * @enderror * * The function creates a new double property with name @em name and * value @em value. The property is appended to the property list @em self. */ cpl_error_code cpl_propertylist_append_double(cpl_propertylist *self, const char *name, double value) { cpl_property *property = NULL; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = cpl_property_new(name, CPL_TYPE_DOUBLE); cx_assert(property != NULL); cpl_property_set_double(property, value); cx_deque_push_back(self->properties, property); return CPL_ERROR_NONE; } /** * @brief * Append a string value to a property list. * * @param self A property list. * @param name The property name to be assigned to the value. * @param value The string value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i>, <i>name</i> or <i>value</i> is a * <tt>NULL</tt> pointer. * </td> * </tr> * </table> * @enderror * * The function creates a new string property with name @em name and * value @em value. The property is appended to the property list @em self. */ cpl_error_code cpl_propertylist_append_string(cpl_propertylist *self, const char *name, const char *value) { cpl_property *property = NULL; if (self == NULL || name == NULL || value == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = cpl_property_new(name, CPL_TYPE_STRING); cx_assert(property != NULL); cpl_property_set_string(property, value); cx_deque_push_back(self->properties, property); return CPL_ERROR_NONE; } /** * @brief * Append a float complex value to a property list. * * @param self A property list. * @param name The property name to be assigned to the value. * @param value The float complex value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * </table> * @enderror * * The function creates a new float complex property with name @em name and * value @em value. The property is appended to the property list @em self. */ cpl_error_code cpl_propertylist_append_float_complex(cpl_propertylist *self, const char *name, float complex value) { cpl_property *property = NULL; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = cpl_property_new(name, CPL_TYPE_FLOAT_COMPLEX); cx_assert(property != NULL); cpl_property_set_float_complex(property, value); cx_deque_push_back(self->properties, property); return CPL_ERROR_NONE; } /** * @brief * Append a double complex value to a property list. * * @param self A property list. * @param name The property name to be assigned to the value. * @param value The double complex value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * </table> * @enderror * * The function creates a new double complex property with name @em name and * value @em value. The property is appended to the property list @em self. */ cpl_error_code cpl_propertylist_append_double_complex(cpl_propertylist *self, const char *name, double complex value) { cpl_property *property = NULL; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } property = cpl_property_new(name, CPL_TYPE_DOUBLE_COMPLEX); cx_assert(property != NULL); cpl_property_set_double_complex(property, value); cx_deque_push_back(self->properties, property); return CPL_ERROR_NONE; } /** * @brief * Append a property list.. * * @param self A property list. * @param other The property list to append. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> is a <tt>NULL</tt> pointer. * </td> * </tr> * </table> * @enderror * * The function appends the property list @em other to the property list * @em self. */ cpl_error_code cpl_propertylist_append(cpl_propertylist *self, const cpl_propertylist *other) { if (self == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } if (other != NULL) { cx_deque_const_iterator pos = cx_deque_begin(other->properties); while (pos != cx_deque_end(other->properties)) { const cpl_property *p = cx_deque_get(other->properties, pos); cx_deque_push_back(self->properties, cpl_property_duplicate(p)); pos = cx_deque_next(other->properties, pos); } } return CPL_ERROR_NONE; } /** * @internal * @brief * Erase the given property from a property list. * * @param self A property list. * @param name Name of the property to erase. * * @return * On success the function returns the number of erased entries. If * an error occurs the function returns 0 and an appropriate error * code is set. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * </table> * @enderror * * The function searches the property with the name @em name in the property * list @em self and removes it. The property is destroyed. If @em self * contains multiple duplicates of a property named @em name, only the * first one is erased. */ inline int cpl_propertylist_erase_cx(cpl_propertylist *self, const cpl_cstr *name) { cx_deque_iterator pos = _cpl_propertylist_find_(self, name); if (pos == cx_deque_end(self->properties)) { return 0; } cx_deque_erase(self->properties, pos, (cx_free_func)cpl_property_delete); return 1; } /** * @brief * Erase the given property from a property list. * * @param self A property list. * @param name Name of the property to erase. * * @return * On success the function returns the number of erased entries. If * an error occurs the function returns 0 and an appropriate error * code is set. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * </table> * @enderror * * The function searches the property with the name @em name in the property * list @em self and removes it. The property is destroyed. If @em self * contains multiple duplicates of a property named @em name, only the * first one is erased. */ int cpl_propertylist_erase(cpl_propertylist *self, const char *name) { cx_deque_iterator pos; if (self == NULL || name == NULL) { cpl_error_set_(CPL_ERROR_NULL_INPUT); return 0; } pos = _cpl_propertylist_find(self, name); if (pos == cx_deque_end(self->properties)) { return 0; } cx_deque_erase(self->properties, pos, (cx_free_func)cpl_property_delete); return 1; } /** * @brief * Erase all properties with name matching a given regular expression. * * @param self A property list. * @param regexp Regular expression. * @param invert Flag inverting the sense of matching. * * @return * On success the function returns the number of erased entries or 0 if * no entries are erased. If an error occurs the function returns -1 and an * appropriate error code is set. In CPL versions earlier than 5.0, the * return value in case of error is 0. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>regexp</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_ILLEGAL_INPUT</td> * <td class="ecr"> * The parameter <i>regexp</i> is the empty string. * </td> * </tr> * </table> * @enderror * * The function searches for all the properties matching in the list * @em self and removes them. Whether a property matches or not depends on * the given regular expression @em regexp, and the flag @em invert. If * @em invert is @c 0, all properties matching @em regexp are removed from * the list. If @em invert is set to a non-zero value, all properties which * do not match @em regexp are erased. The removed properties are destroyed. * * The function expects POSIX 1003.2 compliant extended regular expressions. */ int cpl_propertylist_erase_regexp(cpl_propertylist *self, const char *regexp, int invert) { cxint status = 0; cxint count = 0; cx_deque_iterator first; cpl_regexp filter; if (self == NULL || regexp == NULL) { cpl_error_set_(CPL_ERROR_NULL_INPUT); return -1; } if (regexp[0] == '\0') { cpl_error_set_(CPL_ERROR_ILLEGAL_INPUT); return -1; } status = regcomp(&filter.re, regexp, REG_EXTENDED | REG_NOSUB); if (status) { (void)cpl_error_set_regex(CPL_ERROR_ILLEGAL_INPUT, status, &filter.re, "regexp='%s', invert=%d", regexp, invert); return -1; } filter.invert = invert == 0 ? FALSE : TRUE; first = cx_deque_begin(self->properties); while (first < cx_deque_end(self->properties)) { cx_deque_iterator pos = first; cpl_property *p = cx_deque_get(self->properties, pos); if (_cpl_propertylist_compare_regexp(p, &filter) == TRUE) { cx_deque_erase(self->properties, pos, (cx_free_func)cpl_property_delete); count++; } else { first = cx_deque_next(self->properties, first); } } regfree(&filter.re); return count; } /** * @brief * Remove all properties from a property list. * * @param self A property list. * * @return Nothing. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> is a <tt>NULL</tt> pointer. * </td> * </tr> * </table> * @enderror * * The function removes all properties from @em self. Each property * is properly deallocated. After calling this function @em self is * empty. */ void cpl_propertylist_empty(cpl_propertylist *self) { cx_deque_iterator first; if (self == NULL) { cpl_error_set_(CPL_ERROR_NULL_INPUT); return; } first = cx_deque_begin(self->properties); /* cx_deque_end changes its value everytime cx_deque_erase() * is called. The elements are shifted from end to begin every * time an element is erased, therefore we always erase element * first with a value of 0. */ while (first < cx_deque_end(self->properties)) { cx_deque_iterator pos = first; cx_deque_erase(self->properties, pos, (cx_free_func)cpl_property_delete); } return; } /** * @brief * Update a property list with a character value. * * @param self A property list. * @param name The property name to be assigned to the value. * @param value The character value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_TYPE_MISMATCH</td> * <td class="ecr"> * The property list <i>self</i> contains a property with the * name <i>name</i> which is not of type <tt>CPL_TYPE_CHAR</tt>. * </td> * </tr> * </table> * @enderror * * The function updates the property list @em self with the character value * @em value. This means, if a property with the name @em name exists already * its value is updated, otherwise a property with the name @em name is * created and added to @em self. The update will fail if a property with * the name @em name exists already which is not of type @c CPL_TYPE_CHAR. */ cpl_error_code cpl_propertylist_update_char(cpl_propertylist *self, const char *name, char value) { cx_deque_iterator pos; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } pos = _cpl_propertylist_find(self, name); if (pos == cx_deque_end(self->properties)) { cpl_property *property = cpl_property_new(name, CPL_TYPE_CHAR); cx_assert(property != NULL); cpl_property_set_char(property, value); cx_deque_push_back(self->properties, property); } else { cpl_property *property = cx_deque_get(self->properties, pos); cx_assert(property != NULL); if (cpl_property_get_type(property) != CPL_TYPE_CHAR) { return cpl_error_set_(CPL_ERROR_TYPE_MISMATCH); } cpl_property_set_char(property, value); } return CPL_ERROR_NONE; } /** * @brief * Update a property list with a boolean value. * * @param self A property list. * @param name The property name to be assigned to the value. * @param value The boolean value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_TYPE_MISMATCH</td> * <td class="ecr"> * The property list <i>self</i> contains a property with the * name <i>name</i> which is not of type <tt>CPL_TYPE_BOOL</tt>. * </td> * </tr> * </table> * @enderror * * The function updates the property list @em self with the boolean value * @em value. This means, if a property with the name @em name exists already * its value is updated, otherwise a property with the name @em name is * created and added to @em self. The update will fail if a property with * the name @em name exists already which is not of type @c CPL_TYPE_BOOL. */ cpl_error_code cpl_propertylist_update_bool(cpl_propertylist *self, const char *name, int value) { cx_deque_iterator pos; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } pos = _cpl_propertylist_find(self, name); if (pos == cx_deque_end(self->properties)) { cpl_property *property = cpl_property_new(name, CPL_TYPE_BOOL); cx_assert(property != NULL); cpl_property_set_bool(property, value); cx_deque_push_back(self->properties, property); } else { cpl_property *property = cx_deque_get(self->properties, pos); cx_assert(property != NULL); if (cpl_property_get_type(property) != CPL_TYPE_BOOL) { return cpl_error_set_(CPL_ERROR_TYPE_MISMATCH); } cpl_property_set_bool(property, value); } return CPL_ERROR_NONE; } /** * @brief * Update a property list with a integer value. * * @param self A property list. * @param name The property name to be assigned to the value. * @param value The integer value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_TYPE_MISMATCH</td> * <td class="ecr"> * The property list <i>self</i> contains a property with the * name <i>name</i> which is not of type <tt>CPL_TYPE_INT</tt>. * </td> * </tr> * </table> * @enderror * * The function updates the property list @em self with the integer value * @em value. This means, if a property with the name @em name exists already * its value is updated, otherwise a property with the name @em name is * created and added to @em self. The update will fail if a property with * the name @em name exists already which is not of type @c CPL_TYPE_INT. */ cpl_error_code cpl_propertylist_update_int(cpl_propertylist *self, const char *name, int value) { cx_deque_iterator pos; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } pos = _cpl_propertylist_find(self, name); if (pos == cx_deque_end(self->properties)) { cpl_property *property = cpl_property_new(name, CPL_TYPE_INT); cx_assert(property != NULL); cpl_property_set_int(property, value); cx_deque_push_back(self->properties, property); } else { cpl_property *property = cx_deque_get(self->properties, pos); cx_assert(property != NULL); if (cpl_property_get_type(property) != CPL_TYPE_INT) { return cpl_error_set_(CPL_ERROR_TYPE_MISMATCH); } cpl_property_set_int(property, value); } return CPL_ERROR_NONE; } /** * @brief * Update a property list with a long value. * * @param self A property list. * @param name The property name to be assigned to the value. * @param value The long value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_TYPE_MISMATCH</td> * <td class="ecr"> * The property list <i>self</i> contains a property with the * name <i>name</i> which is not of type <tt>CPL_TYPE_LONG</tt>. * </td> * </tr> * </table> * @enderror * * The function updates the property list @em self with the long value * @em value. This means, if a property with the name @em name exists already * its value is updated, otherwise a property with the name @em name is * created and added to @em self. The update will fail if a property with * the name @em name exists already which is not of type @c CPL_TYPE_LONG. */ cpl_error_code cpl_propertylist_update_long(cpl_propertylist *self, const char *name, long value) { cx_deque_iterator pos; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } pos = _cpl_propertylist_find(self, name); if (pos == cx_deque_end(self->properties)) { cpl_property *property = cpl_property_new(name, CPL_TYPE_LONG); cx_assert(property != NULL); cpl_property_set_long(property, value); cx_deque_push_back(self->properties, property); } else { cpl_property *property = cx_deque_get(self->properties, pos); cx_assert(property != NULL); if (cpl_property_get_type(property) != CPL_TYPE_LONG) { return cpl_error_set_(CPL_ERROR_TYPE_MISMATCH); } cpl_property_set_long(property, value); } return CPL_ERROR_NONE; } /** * @brief * Update a property list with a long long value. * * @param self A property list. * @param name The property name to be assigned to the value. * @param value The long long value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_TYPE_MISMATCH</td> * <td class="ecr"> * The property list <i>self</i> contains a property with the * name <i>name</i> which is not of type <tt>CPL_TYPE_LONG_LONG</tt>. * </td> * </tr> * </table> * @enderror * * The function updates the property list @em self with the long long value * @em value. This means, if a property with the name @em name exists already * its value is updated, otherwise a property with the name @em name is * created and added to @em self. The update will fail if a property with * the name @em name exists already which is not of type @c CPL_TYPE_LONG_LONG. */ cpl_error_code cpl_propertylist_update_long_long(cpl_propertylist *self, const char *name, long long value) { cx_deque_iterator pos; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } pos = _cpl_propertylist_find(self, name); if (pos == cx_deque_end(self->properties)) { cpl_property *property = cpl_property_new(name, CPL_TYPE_LONG_LONG); cx_assert(property != NULL); cpl_property_set_long_long(property, value); cx_deque_push_back(self->properties, property); } else { cpl_property *property = cx_deque_get(self->properties, pos); cx_assert(property != NULL); if (cpl_property_get_type(property) != CPL_TYPE_LONG_LONG) { return cpl_error_set_(CPL_ERROR_TYPE_MISMATCH); } cpl_property_set_long_long(property, value); } return CPL_ERROR_NONE; } /** * @brief * Update a property list with a float value. * * @param self A property list. * @param name The property name to be assigned to the value. * @param value The float value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_TYPE_MISMATCH</td> * <td class="ecr"> * The property list <i>self</i> contains a property with the * name <i>name</i> which is not of type <tt>CPL_TYPE_FLOAT</tt>. * </td> * </tr> * </table> * @enderror * * The function updates the property list @em self with the float value * @em value. This means, if a property with the name @em name exists already * its value is updated, otherwise a property with the name @em name is * created and added to @em self. The update will fail if a property with * the name @em name exists already which is not of type @c CPL_TYPE_FLOAT. */ cpl_error_code cpl_propertylist_update_float(cpl_propertylist *self, const char *name, float value) { cx_deque_iterator pos; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } pos = _cpl_propertylist_find(self, name); if (pos == cx_deque_end(self->properties)) { cpl_property *property = cpl_property_new(name, CPL_TYPE_FLOAT); cx_assert(property != NULL); cpl_property_set_float(property, value); cx_deque_push_back(self->properties, property); } else { cpl_property *property = cx_deque_get(self->properties, pos); cx_assert(property != NULL); if (cpl_property_get_type(property) != CPL_TYPE_FLOAT) { return cpl_error_set_(CPL_ERROR_TYPE_MISMATCH); } cpl_property_set_float(property, value); } return CPL_ERROR_NONE; } /** * @brief * Update a property list with a double value. * * @param self A property list. * @param name The property name to be assigned to the value. * @param value The double value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_TYPE_MISMATCH</td> * <td class="ecr"> * The property list <i>self</i> contains a property with the * name <i>name</i> which is not of type <tt>CPL_TYPE_DOUBLE</tt>. * </td> * </tr> * </table> * @enderror * * The function updates the property list @em self with the double value * @em value. This means, if a property with the name @em name exists already * its value is updated, otherwise a property with the name @em name is * created and added to @em self. The update will fail if a property with * the name @em name exists already which is not of type @c CPL_TYPE_DOUBLE. */ cpl_error_code cpl_propertylist_update_double(cpl_propertylist *self, const char *name, double value) { cx_deque_iterator pos; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } pos = _cpl_propertylist_find(self, name); if (pos == cx_deque_end(self->properties)) { cpl_property *property = cpl_property_new(name, CPL_TYPE_DOUBLE); cx_assert(property != NULL); cpl_property_set_double(property, value); cx_deque_push_back(self->properties, property); } else { cpl_property *property = cx_deque_get(self->properties, pos); cx_assert(property != NULL); if (cpl_property_get_type(property) != CPL_TYPE_DOUBLE) { return cpl_error_set_(CPL_ERROR_TYPE_MISMATCH); } cpl_property_set_double(property, value); } return CPL_ERROR_NONE; } /** * @brief * Update a property list with a string value. * * @param self A property list. * @param name The property name to be assigned to the value. * @param value The string value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i>, <i>name</i> or <i>value</i> is a * <tt>NULL</tt> pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_TYPE_MISMATCH</td> * <td class="ecr"> * The property list <i>self</i> contains a property with the * name <i>name</i> which is not of type <tt>CPL_TYPE_STRING</tt>. * </td> * </tr> * </table> * @enderror * * The function updates the property list @em self with the string value * @em value. This means, if a property with the name @em name exists already * its value is updated, otherwise a property with the name @em name is * created and added to @em self. The update will fail if a property with * the name @em name exists already which is not of type @c CPL_TYPE_STRING. */ cpl_error_code cpl_propertylist_update_string(cpl_propertylist *self, const char *name, const char *value) { cx_deque_iterator pos; if (self == NULL || name == NULL || value == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } pos = _cpl_propertylist_find(self, name); if (pos == cx_deque_end(self->properties)) { cpl_property *property = cpl_property_new(name, CPL_TYPE_STRING); cx_assert(property != NULL); cpl_property_set_string(property, value); cx_deque_push_back(self->properties, property); } else { cpl_property *property = cx_deque_get(self->properties, pos); cx_assert(property != NULL); if (cpl_property_get_type(property) != CPL_TYPE_STRING) { return cpl_error_set_(CPL_ERROR_TYPE_MISMATCH); } cpl_property_set_string(property, value); } return CPL_ERROR_NONE; } /** * @brief * Update a property list with a float complex value. * * @param self A property list. * @param name The property name to be assigned to the value. * @param value The float complex value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_TYPE_MISMATCH</td> * <td class="ecr"> * The property list <i>self</i> contains a property with the * name <i>name</i> which is not of type <tt>CPL_TYPE_FLOAT_COMPLEX</tt>. * </td> * </tr> * </table> * @enderror * * The function updates the property list @em self with the float complex value * @em value. This means, if a property with the name @em name exists already * its value is updated, otherwise a property with the name @em name is * created and added to @em self. The update will fail if a property with * the name @em name exists already which is not of type * @c CPL_TYPE_FLOAT_COMPLEX. */ cpl_error_code cpl_propertylist_update_float_complex(cpl_propertylist *self, const char *name, float complex value) { cx_deque_iterator pos; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } pos = _cpl_propertylist_find(self, name); if (pos == cx_deque_end(self->properties)) { cpl_property *property = cpl_property_new(name, CPL_TYPE_FLOAT_COMPLEX); cx_assert(property != NULL); cpl_property_set_float_complex(property, value); cx_deque_push_back(self->properties, property); } else { cpl_property *property = cx_deque_get(self->properties, pos); cx_assert(property != NULL); if (cpl_property_set_float_complex(property, value)) { return cpl_error_set_where_(); } } return CPL_ERROR_NONE; } /** * @brief * Update a property list with a double complex value. * * @param self A property list. * @param name The property name to be assigned to the value. * @param value The double complex value to store. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>name</i> is a <tt>NULL</tt> * pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_TYPE_MISMATCH</td> * <td class="ecr"> * The property list <i>self</i> contains a property with the * name <i>name</i> which is not of type * <tt>CPL_TYPE_DOUBLE_COMPLEX</tt>. * </td> * </tr> * </table> * @enderror * * The function updates the property list @em self with the double complex value * @em value. This means, if a property with the name @em name exists already * its value is updated, otherwise a property with the name @em name is * created and added to @em self. The update will fail if a property with * the name @em name exists already which is not of type * @c CPL_TYPE_DOUBLE_COMPLEX. */ cpl_error_code cpl_propertylist_update_double_complex(cpl_propertylist *self, const char *name, double complex value) { cx_deque_iterator pos; if (self == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } pos = _cpl_propertylist_find(self, name); if (pos == cx_deque_end(self->properties)) { cpl_property *property = cpl_property_new(name, CPL_TYPE_DOUBLE_COMPLEX); cx_assert(property != NULL); cpl_property_set_double_complex(property, value); cx_deque_push_back(self->properties, property); } else { cpl_property *property = cx_deque_get(self->properties, pos); cx_assert(property != NULL); if (cpl_property_set_double_complex(property, value)) { cpl_error_set_where_(); } } return CPL_ERROR_NONE; } /** * @brief * Copy a property from another property list. * * @param self A property list. * @param other The property list from which a property is copied. * @param name The name of the property to copy. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i>, <i>other</i> or <i>name</i> is a * <tt>NULL</tt> pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_DATA_NOT_FOUND</td> * <td class="ecr"> * The property list <i>other</i> does not contain a property with the * name <i>name</i>. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_TYPE_MISMATCH</td> * <td class="ecr"> * The property list <i>self</i> contains a property with the * name <i>name</i> which is not of the same type as the property * which should be copied from <i>other</i>. * </td> * </tr> * </table> * @enderror * * The function copies the property @em name from the property list * @em other to the property list @em self. If the property list @em self * does not already contain a property @em name the property is appended * to @em self. If a property @em name exists already in @em self the * function overwrites the contents of this property if and only if this * property is of the same type as the property to be copied from @em other. */ cpl_error_code cpl_propertylist_copy_property(cpl_propertylist *self, const cpl_propertylist *other, const char *name) { cx_deque_iterator spos; cx_deque_iterator tpos; if (self == NULL || other == NULL || name == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } spos = _cpl_propertylist_find(other, name); if (spos == cx_deque_end(other->properties)) { return cpl_error_set_message_(CPL_ERROR_DATA_NOT_FOUND, "%s", name); } tpos = _cpl_propertylist_find(self, name); if (tpos == cx_deque_end(self->properties)) { cpl_property *p = cpl_property_duplicate(cx_deque_get(other->properties, spos)); cx_deque_push_back(self->properties, p); } else { cpl_property *p = cx_deque_get(self->properties, tpos); cpl_property *_p = cx_deque_get(other->properties, spos); if (cpl_property_get_type(p) != cpl_property_get_type(_p)) { return cpl_error_set_(CPL_ERROR_TYPE_MISMATCH); } switch (cpl_property_get_type(_p)) { case CPL_TYPE_CHAR: cpl_property_set_char(p, cpl_property_get_char(_p)); break; case CPL_TYPE_BOOL: cpl_property_set_bool(p, cpl_property_get_bool(_p)); break; case CPL_TYPE_INT: cpl_property_set_int(p, cpl_property_get_int(_p)); break; case CPL_TYPE_LONG: cpl_property_set_long(p, cpl_property_get_long(_p)); break; case CPL_TYPE_FLOAT: cpl_property_set_float(p, cpl_property_get_float(_p)); break; case CPL_TYPE_DOUBLE: cpl_property_set_double(p, cpl_property_get_double(_p)); break; case CPL_TYPE_STRING: cpl_property_set_string(p, cpl_property_get_string(_p)); break; case CPL_TYPE_FLOAT_COMPLEX: cpl_property_set_float_complex(p, cpl_property_get_float_complex(_p)); break; case CPL_TYPE_DOUBLE_COMPLEX: cpl_property_set_double_complex(p, cpl_property_get_double_complex(_p)); break; default: /* This point should never be reached */ return cpl_error_set_(CPL_ERROR_UNSUPPORTED_MODE); break; } cpl_property_set_comment(p, cpl_property_get_comment(_p)); } return CPL_ERROR_NONE; } /** * @brief * Copy matching properties from another property list. * * @param self A property list. * @param other The property list from which a property is copied. * @param regexp The regular expression used to select properties. * @param invert Flag inverting the sense of matching. * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i>, <i>other</i> or <i>regexp</i> is a * <tt>NULL</tt> pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_ILLEGAL_INPUT</td> * <td class="ecr"> * The parameter <i>regexp</i> is an invalid regular expression, * including the empty stringr. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_TYPE_MISMATCH</td> * <td class="ecr"> * The property list <i>self</i> contains a property with the * name <i>name</i> which is not of the same type as the property * which should be copied from <i>other</i>. * </td> * </tr> * </table> * @enderror * * The function copies all properties with matching names from the property * list @em other to the property list @em self. If the flag @em invert is * zero, all properties whose names match the regular expression @em regexp * are copied. If @em invert is set to a non-zero value, all properties with * names not matching @em regexp are copied rather. The function expects * POSIX 1003.2 compliant extended regular expressions. * * If the property list @em self does not already contain one of the * properties to be copied this property is appended to @em self. If a * property to be copied exists already in @em self the function overwrites * the contents of this property. * * Before properties are copied from the property list @em other to @em self * the types of the properties are checked and if any type mismatch is * detected the function stops processing immediately. The property list * @em self is not at all modified in this case. * * @see cpl_propertylist_copy_property(), cpl_propertylist_append() */ cpl_error_code cpl_propertylist_copy_property_regexp(cpl_propertylist *self, const cpl_propertylist *other, const char *regexp, int invert) { cxint status; cxsize i; cxsize count = 0; cx_deque_const_iterator first, last; typedef struct _property_pair_ { cpl_property *s; cpl_property *t; } property_pair; property_pair *pairs = NULL; cpl_regexp filter; if (self == NULL || other == NULL || regexp == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } if (regexp[0] == '\0') { return cpl_error_set_(CPL_ERROR_ILLEGAL_INPUT); } status = regcomp(&filter.re, regexp, REG_EXTENDED | REG_NOSUB); if (status) { (void)cpl_error_set_regex(CPL_ERROR_ILLEGAL_INPUT, status, &filter.re, "regexp='%s', invert=%d", regexp, invert); return CPL_ERROR_ILLEGAL_INPUT; } filter.invert = invert == 0 ? FALSE : TRUE; count = cx_deque_size(other->properties); if (count == 0) { regfree(&filter.re); return CPL_ERROR_NONE; } pairs = cx_malloc(count * sizeof(property_pair)); cx_assert(pairs != NULL); count = 0; first = cx_deque_begin(other->properties); last = cx_deque_end(other->properties); while (first != last) { cpl_property *p = cx_deque_get(other->properties, first); if (_cpl_propertylist_compare_regexp(p, &filter) == TRUE) { const cxchar *name = cpl_property_get_name(p); /* name size, i.e. including terminating null byte */ const size_t namelen= cpl_property_get_size_name(p); cpl_property *_p = NULL; cx_deque_const_iterator pos; const cpl_cstr * cxstr; cxstr = CXSTR(name, namelen); pos = _cpl_propertylist_find_(self, cxstr); if (pos != cx_deque_end(self->properties)) { _p = cx_deque_get(self->properties, pos); if (cpl_property_get_type(p) != cpl_property_get_type(_p)) { regfree(&filter.re); cx_free(pairs); pairs = NULL; return cpl_error_set_(CPL_ERROR_TYPE_MISMATCH); } } pairs[count].s = p; pairs[count].t = _p; ++count; } first = cx_deque_next(other->properties, first); } regfree(&filter.re); for (i = 0; i < count; i++) { if (pairs[i].t == NULL) { cpl_property *p = cpl_property_duplicate(pairs[i].s); cx_deque_push_back(self->properties, p); } else { switch (cpl_property_get_type(pairs[i].s)) { case CPL_TYPE_CHAR: cpl_property_set_char(pairs[i].t, cpl_property_get_char(pairs[i].s)); break; case CPL_TYPE_BOOL: cpl_property_set_bool(pairs[i].t, cpl_property_get_bool(pairs[i].s)); break; case CPL_TYPE_INT: cpl_property_set_int(pairs[i].t, cpl_property_get_int(pairs[i].s)); break; case CPL_TYPE_LONG: cpl_property_set_long(pairs[i].t, cpl_property_get_long(pairs[i].s)); break; case CPL_TYPE_FLOAT: cpl_property_set_float(pairs[i].t, cpl_property_get_float(pairs[i].s)); break; case CPL_TYPE_DOUBLE: cpl_property_set_double(pairs[i].t, cpl_property_get_double(pairs[i].s)); break; case CPL_TYPE_STRING: cpl_property_set_string(pairs[i].t, cpl_property_get_string(pairs[i].s)); break; case CPL_TYPE_FLOAT_COMPLEX: cpl_property_set_float_complex(pairs[i].t, cpl_property_get_float_complex(pairs[i].s)); break; case CPL_TYPE_DOUBLE_COMPLEX: cpl_property_set_double_complex(pairs[i].t, cpl_property_get_double_complex(pairs[i].s)); break; default: /* This point should never be reached */ cx_free(pairs); return cpl_error_set_(CPL_ERROR_UNSUPPORTED_MODE); break; } cpl_property_set_comment(pairs[i].t, cpl_property_get_comment(pairs[i].s)); } } cx_free(pairs); return CPL_ERROR_NONE; } /** * @brief * Sort a property list. * * @param self The property list to sort. * @param compare The function used to compare two properties. * * @return * The function returns @c CPL_ERROR_NONE on success, or a CPL error code * otherwise. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> is a <tt>NULL</tt> pointer. * </td> * </tr> * </table> * @enderror * * The function sorts the property list @em self in place, using the function * @em compare to determine whether a property is less, equal or greater than * another one. * * The function @em compare must be of the type cpl_propertylist_compare_func. * * @see * cpl_propertylist_compare_func */ /*cpl_error_code cpl_propertylist_sort(cpl_propertylist* self, int (*compare)(const void*, const void*))*/ cpl_error_code cpl_propertylist_sort(cpl_propertylist* self, cpl_propertylist_compare_func compare) { cx_compare_func _compare = (cx_compare_func)compare; if (self == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } cx_deque_sort(self->properties, _compare); return CPL_ERROR_NONE; } /** * @brief * Create a property list from a file. * * @param name Name of the input file. * @param position Index of the data set to read. * * @return * The function returns the newly created property list or @c NULL if an * error occurred. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>name</i> is a <tt>NULL</tt> pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_ILLEGAL_INPUT</td> * <td class="ecr"> * The <i>position</i> is less than 0 or the properties cannot be * read from the file <i>name</i>. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_FILE_IO</td> * <td class="ecr"> * The file <i>name</i> does not exist. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_BAD_FILE_FORMAT</td> * <td class="ecr"> * The file <i>name</i> is not a valid FITS file. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_DATA_NOT_FOUND</td> * <td class="ecr"> * The requested data set at index <i>position</i> does not exist. * </td> * </tr> * </table> * @enderror * * The function reads the properties of the data set with index @em position * from the file @em name. * * Currently only the FITS file format is supported. The property list is * created by reading the FITS keywords from extension @em position. The * numbering of the data sections starts from 0. * When creating the property list from a FITS header, any keyword without * a value such as undefined keywords, are not transformed into * a property. In the case of float or double (complex) keywords, there is no * way to identify the type returned by CFITSIO, therefore this function will * always load them as double (complex). * * @see cpl_propertylist_load_regexp() */ cpl_propertylist * cpl_propertylist_load(const char *name, cpl_size position) { cxint status = 0; cpl_propertylist *self; cpl_error_code code; fitsfile *file = NULL; if (name == NULL) { cpl_error_set_(CPL_ERROR_NULL_INPUT); return NULL; } if ((position < 0) || (position > CX_MAXINT)) { cpl_error_set_(CPL_ERROR_ILLEGAL_INPUT); return NULL; } if (cpl_io_fits_open_diskfile(&file, name, READONLY, &status)) { (void)cpl_error_set_fits(status == FILE_NOT_OPENED ? CPL_ERROR_FILE_IO : CPL_ERROR_BAD_FILE_FORMAT, status, fits_open_diskfile, "filename='%s', " "position=%d", name, (cxint)position); return NULL; } self = cpl_propertylist_new(); code = cpl_propertylist_fill_from_fits_locale(self, file, (cxint)position, NULL, NULL); if (cpl_io_fits_close_file(file, &status)) { code = cpl_error_set_fits(CPL_ERROR_BAD_FILE_FORMAT, status, fits_close_file, "filename='%s', " "position=%d", name, (cxint)position); } else if (code) { /* * Propagate error */ cpl_error_set_message_(code, "Position %d in file: %s", (int)position, name); } if (code) { cpl_propertylist_delete(self); self = NULL; } return self; } /** * @brief * Create a filtered property list from a file. * * @param name Name of the input file. * @param position Index of the data set to read. * @param regexp Regular expression used to filter properties. * @param invert Flag inverting the sense of matching property names. * * @return * The function returns the newly created property list or @c NULL if an * error occurred. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>name</i> or the parameter <i>regexp</i> is a * <tt>NULL</tt> pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_ILLEGAL_INPUT</td> * <td class="ecr"> * The <i>position</i> is less than 0, the properties cannot be * read from the file <i>name</i>, or <i>regexp</i> is not a valid * extended regular expression, including the empty string.. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_FILE_IO</td> * <td class="ecr"> * The file <i>name</i> does not exist. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_BAD_FILE_FORMAT</td> * <td class="ecr"> * The file <i>name</i> is not a valid FITS file. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_DATA_NOT_FOUND</td> * <td class="ecr"> * The requested data set at index <i>position</i> does not exist. * </td> * </tr> * </table> * @enderror * * The function reads all properties of the data set with index @em position * with matching names from the file @em name. If the flag @em invert is zero, * all properties whose names match the regular expression @em regexp are * read. If @em invert is set to a non-zero value, all properties with * names not matching @em regexp are read rather. The function expects * POSIX 1003.2 compliant extended regular expressions. * * Currently only the FITS file format is supported. The property list is * created by reading the FITS keywords from extension @em position. * The numbering of the data sections starts from 0. * * When creating the property list from a FITS header, any keyword without * a value such as undefined keywords, are not transformed into * a property. In the case of float or double (complex) keywords, there is no * way to identify the type returned by CFITSIO, therefore this function will * always load them as double (complex). * * FITS format specific keyword prefixes (e.g. @c HIERARCH) must * not be part of the given pattern string @em regexp, but only the actual * FITS keyword name may be given. * * @see cpl_propertylist_load() */ cpl_propertylist * cpl_propertylist_load_regexp(const char *name, cpl_size position, const char *regexp, int invert) { cxint status = 0; cpl_propertylist *self; cpl_regexp filter; cpl_error_code code; fitsfile *file = NULL; if (name == NULL) { cpl_error_set_(CPL_ERROR_NULL_INPUT); return NULL; } if ((position < 0) || (position > CX_MAXINT)) { cpl_error_set_(CPL_ERROR_ILLEGAL_INPUT); return NULL; } if (regexp == NULL) { cpl_error_set_(CPL_ERROR_NULL_INPUT); return NULL; } if (regexp[0] == '\0') { cpl_error_set_(CPL_ERROR_ILLEGAL_INPUT); return NULL; } /* * Set up the regular expression filter */ status = regcomp(&filter.re, regexp, REG_EXTENDED | REG_NOSUB); if (status) { (void)cpl_error_set_regex(CPL_ERROR_ILLEGAL_INPUT, status, &filter.re, "regexp='%s', invert=%d", regexp, invert); return NULL; } filter.invert = invert == 0 ? FALSE : TRUE; if (cpl_io_fits_open_diskfile(&file, name, READONLY, &status)) { (void)cpl_error_set_fits(status == FILE_NOT_OPENED ? CPL_ERROR_FILE_IO : CPL_ERROR_BAD_FILE_FORMAT, status, fits_open_diskfile, "filename='%s', " "position=%d, regexp='%s'", name, (cxint)position, regexp); status = 0; cpl_io_fits_close_file(file, &status); regfree(&filter.re); return NULL; } self = cpl_propertylist_new(); code = cpl_propertylist_fill_from_fits_locale(self, file, (cxint)position, _cpl_propertylist_filter_regexp, &filter); regfree(&filter.re); if (cpl_io_fits_close_file(file, &status)) { code = cpl_error_set_fits(CPL_ERROR_BAD_FILE_FORMAT, status, fits_close_file, "filename='%s', position=" "%d, regexp='%s'", name, (cxint)position, regexp); } else if (code) { /* * Propagate error */ cpl_error_set_message_(code, "Position %d in file: %s. Invert=%d of %s", (int)position, name, invert, regexp); } if (code) { cpl_propertylist_delete(self); self = NULL; } return self; } /** * @internal * @brief * Create a property list from named FITS card(s) in a file * * @param name Name of the input file. * @param position Index of the data set to read. * @param nstart Number of start keys to select against * @param startkey Keys starting with this name are loaded * @param nexact Number of exact keys to select against * @param exactkey Keys with this exact name are loaded * @param invert Flag inverting the sense of matching property names. * * @return * The function returns the newly created property list or @c NULL if an * error occurred. * * @see cpl_propertylist_load_regexp(() * * @note No input validation in this internal function * * When suitable, the filter used by this function is an order of magnitude * faster than the regular expression engine of cpl_propertylist_load_regexp(). * */ cpl_propertylist * cpl_propertylist_load_name_(const char * name, cpl_size position, cpl_size nstart, const cpl_cstr * startkey[], cpl_size nexact, const cpl_cstr * exactkey[], int invert) { cxint status = 0; cpl_propertylist *self; cpl_memcmp_ filter; cpl_error_code code; fitsfile *file = NULL; if (cpl_io_fits_open_diskfile(&file, name, READONLY, &status)) { (void)cpl_error_set_fits(status == FILE_NOT_OPENED ? CPL_ERROR_FILE_IO : CPL_ERROR_BAD_FILE_FORMAT, status, fits_open_diskfile, "filename='%s', " "position=%d, nstartkey=%d, nexactkey=%d", name, (cxint)position, (int)nstart, (int)nexact); status = 0; cpl_io_fits_close_file(file, &status); return NULL; } self = cpl_propertylist_new(); /* * Set up the filter */ filter.nstart = nstart; filter.startkey = startkey; filter.nexact = nexact; filter.exactkey = exactkey; filter.invert = invert; code = cpl_propertylist_fill_from_fits_locale(self, file, (cxint)position, _cpl_propertylist_filter_memcmp, &filter); if (cpl_io_fits_close_file(file, &status)) { code = cpl_error_set_fits(CPL_ERROR_BAD_FILE_FORMAT, status, fits_close_file, "filename='%s', position=" "%d, nstartkey=%d, nexactkey=%d", name, (cxint)position, (int)nstart, (int)nexact); } else if (code) { /* * Propagate error */ cpl_error_set_message_(code, "Position %d in file: %s. Invert=%d", (int)position, name, invert); } if (code) { cpl_propertylist_delete(self); self = NULL; } return self; } /** * @internal * @brief * Write a property list to a FITS file. * * @param file The FITS file to write to. * @param properties The property list to write to the file. * @param to_rm The regular expression used to filter properties * * @return * The function returns @c CPL_ERROR_NONE on success, or an appropriate * error code otherwise. * * This function takes a sorted property list and appends it to the * provided FITS file. All properties with names matching the regular expression * @c to_rm will not be copied to the output. The function expects * POSIX 1003.2 compliant extended regular expressions. */ cpl_error_code cpl_propertylist_to_fitsfile(fitsfile *file, const cpl_propertylist *self, const char *to_rm) { cpl_regexp filter; cpl_error_code error; if (file == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } if (self == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } if (to_rm != NULL) { /* A regular expression must be applied */ const cxint rstatus = regcomp(&filter.re, to_rm, REG_EXTENDED | REG_NOSUB); if (rstatus) { return cpl_error_set_regex(CPL_ERROR_ILLEGAL_INPUT, rstatus, &filter.re, "to_rm='%s'", to_rm); } filter.invert = 0; } error = cpl_propertylist_to_fitsfile_locale(file, self, _cpl_propertylist_filter_regexp, to_rm ? &filter : NULL); if (to_rm != NULL) { regfree(&filter.re); } return error ? cpl_error_set_where_() : CPL_ERROR_NONE; } /** * @internal * @brief * Create a property list from a cfitsio FITS file. * * @param file FITS file pointing to the header to convert. * * @return The function returns the created property list, or @c NULL * in case of an error. * * The function converts the FITS keywords from the current HDU of the FITS * file @em file into properties and puts them into a property list. * * The special FITS keyword END indicating the end of a FITS header is not * transformed into a property, but simply ignored. * * In case of an error, an appropriate error code is set. If a FITS header * card cannot be parsed the error code is set to @c CPL_ERROR_ILLEGAL_INPUT * or to @c CPL_ERROR_INVALID_TYPE if a FITS keyword type is not supported. * If @em file is @c NULL the error code is set to @c CPL_ERROR_NULL_INPUT. */ cpl_propertylist * cpl_propertylist_from_fitsfile(fitsfile *file) { cpl_propertylist *self; cpl_ensure(file != NULL, CPL_ERROR_NULL_INPUT, NULL); self = cpl_propertylist_new(); if (cpl_propertylist_fill_from_fits_locale(self, file, 0, NULL, NULL)) { cpl_propertylist_delete(self); self = NULL; cpl_error_set_where_(); } return self; } /** * @brief * Access property list elements by property name. * * @param self The property list to query. * @param name The name of the property to retrieve. * * @return * The function returns the property with name @em name, or @c NULL * if it does not exist. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or the <i>name</i> is a <tt>NULL</tt> pointer. * </td> * </tr> * </table> * @enderror * * The function returns a handle to the property list element, the property, * with the name @em name. If more than one property exist with the same * @em name, then the first one found will be returned. */ const cpl_property * cpl_propertylist_get_property_const(const cpl_propertylist *self, const char *name) { cx_deque_iterator pos; if (self == NULL) { cpl_error_set_(CPL_ERROR_NULL_INPUT); return NULL; } if (name == NULL) { cpl_error_set_(CPL_ERROR_NULL_INPUT); return NULL; } pos = _cpl_propertylist_find(self, name); if (pos == cx_deque_end(self->properties)) return NULL; return cx_deque_get(self->properties, pos); } /** * @brief * Access property list elements by property name. * * @param self The property list to query. * @param name The name of the property to retrieve. * * @return * The function returns the property with name @em name, or @c NULL * if it does not exist. * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or the <i>name</i> is a <tt>NULL</tt> pointer. * </td> * </tr> * </table> * @enderror * * The function returns a handle to the property list element, the property, * with the name @em name. If more than one property exist with the same * @em name, then the first one found will be returned. */ cpl_property * cpl_propertylist_get_property(cpl_propertylist *self, const char *name) { cpl_errorstate prestate = cpl_errorstate_get(); cpl_property *property; CPL_DIAG_PRAGMA_PUSH_IGN(-Wcast-qual); property = (cpl_property *)cpl_propertylist_get_property_const(self, name); CPL_DIAG_PRAGMA_POP; if (!cpl_errorstate_is_equal(prestate)) (void)cpl_error_set_where_(); return property; } /** * @brief * Save a property list to a FITS file * * @param self The property list to save or NULL if empty * @param filename Name of the file to write * @param mode The desired output options (combined with bitwise or) * * @return * CPL_ERROR_NONE or the relevant #_cpl_error_code_ on error * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The <i>filename</i> is a <tt>NULL</tt> pointer. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_ILLEGAL_INPUT</td> * <td class="ecr"> * The parameter <i>mode</i> is invalid. * </td> * </tr> * <tr> * <td class="ecl">CPL_ERROR_FILE_IO</td> * <td class="ecr"> * The file cannot be written or accessed. * </td> * </tr> * </table> * @enderror * * This function saves a property list to a FITS file, using cfitsio. * The data unit is empty. * * Supported output modes are CPL_IO_CREATE (create a new file) and * CPL_IO_EXTEND (append to an existing file) */ cpl_error_code cpl_propertylist_save(const cpl_propertylist *self, const char *filename, unsigned mode) { const cxchar *badkeys = (mode & CPL_IO_EXTEND) ? CPL_FITS_BADKEYS_EXT "|" CPL_FITS_COMPRKEYS : CPL_FITS_BADKEYS_PRIM "|" CPL_FITS_COMPRKEYS; cxint error = 0; cpl_error_code code = CPL_ERROR_NONE; fitsfile *fptr; /* * Check entries */ cpl_ensure_code(filename, CPL_ERROR_NULL_INPUT); cpl_ensure_code(mode == CPL_IO_CREATE || mode == CPL_IO_EXTEND, CPL_ERROR_ILLEGAL_INPUT); /* Switch on the mode */ if (mode == CPL_IO_EXTEND) { /* Append */ /* Open the file */ if (cpl_io_fits_open_diskfile(&fptr, filename, READWRITE, &error)) { return cpl_error_set_fits(CPL_ERROR_FILE_IO, error, fits_open_diskfile, "filename='%s', " "mode=%u", filename, mode); } } else { /* Main HDU */ /* Create the file */ cxchar *sval = cpl_sprintf("!%s", filename); cpl_io_fits_create_file(&fptr, sval, &error); cpl_free(sval); if (error != 0) { return cpl_error_set_fits(CPL_ERROR_FILE_IO, error, fits_create_file, "filename='%s', " "mode=%u", filename, mode); } } /* Create empty header */ if (fits_create_img(fptr, BYTE_IMG, 0, NULL, &error)) { cxint error2 = 0; cpl_io_fits_close_file(fptr, &error2); return cpl_error_set_fits(CPL_ERROR_FILE_IO, error, fits_create_img, "filename='%s', mode=%u", filename, mode); } /* Add DATE */ if (mode != CPL_IO_EXTEND && fits_write_date(fptr, &error)) { cxint error2 = 0; cpl_io_fits_close_file(fptr, &error2); return cpl_error_set_fits(CPL_ERROR_FILE_IO, error, fits_write_date, "filename='%s', mode=%u", filename, mode); } /* Add the property list */ if (cpl_fits_add_properties(fptr, self, badkeys)) { code = cpl_error_set_where_(); } /* Close (and write to disk) */ if (cpl_io_fits_close_file(fptr, &error)) { return cpl_error_set_fits(CPL_ERROR_FILE_IO, error, fits_close_file, "filename='%s', mode=%u", filename, mode); } return code; } /** * @brief * Print a property list. * * @param self Pointer to property list * @param stream The output stream * * @return Nothing. * * This function is mainly intended for debug purposes. * If the specified stream is @c NULL, it is set to @em stdout. * The function used for printing is the standard C @c fprintf(). */ void cpl_propertylist_dump(const cpl_propertylist *self, FILE *stream) { cxchar c = '\0'; cpl_size i = 0; cpl_size sz = cpl_propertylist_get_size(self); if (stream == NULL) stream = stdout; if (self == NULL) { fprintf(stream, "NULL property list\n\n"); return; } fprintf(stream, "Property list at address %p:\n", (cxcptr)self); for (i = 0; i < sz; i++) { const cpl_property *p = cpl_propertylist_get_const(self, i); const cxchar *name = cpl_property_get_name(p); const cxchar *comment = cpl_property_get_comment(p); cpl_size size = cpl_property_get_size(p); cpl_type type = cpl_property_get_type(p); const cxchar *typestr = cpl_type_get_name(type); fprintf(stream, "Property at address %p\n", (cxcptr)p); fprintf(stream, "\tname : %p '%s'\n", name, name); fprintf(stream, "\tcomment: %p '%s'\n", comment, comment); fprintf(stream, "\ttype : %#09x '%s'\n", type, typestr); fprintf(stream, "\tsize : %" CPL_SIZE_FORMAT "\n", size); fprintf(stream, "\tvalue : "); switch (type) { case CPL_TYPE_CHAR: c = cpl_property_get_char(p); if (!c) fprintf(stream, "''"); else fprintf(stream, "'%c'", c); break; case CPL_TYPE_BOOL: fprintf(stream, "%d", cpl_property_get_bool(p)); break; case CPL_TYPE_INT: fprintf(stream, "%d", cpl_property_get_int(p)); break; case CPL_TYPE_LONG: fprintf(stream, "%ld", cpl_property_get_long(p)); break; case CPL_TYPE_LONG_LONG: fprintf(stream, "%lld", cpl_property_get_long_long(p)); break; case CPL_TYPE_FLOAT: fprintf(stream, "%.7g", cpl_property_get_float(p)); break; case CPL_TYPE_DOUBLE: fprintf(stream, "%.15g", cpl_property_get_double(p)); break; case CPL_TYPE_STRING: fprintf(stream, "'%s'", cpl_property_get_string(p)); break; case CPL_TYPE_FLOAT_COMPLEX: { /* Print with FITS header format */ const float complex z = cpl_property_get_float_complex(p); fprintf(stream, "(%.7g,%.7g)", crealf(z), cimagf(z)); break; } case CPL_TYPE_DOUBLE_COMPLEX: { /* Print with FITS header format */ const double complex z = cpl_property_get_double_complex(p); fprintf(stream, "(%.15g,%.15g)", creal(z), cimag(z)); break; } default: fprintf(stream, "unknown."); break; } fprintf(stream, "\n"); } return; } /** * @brief * Append a property to a property list * * @param self Property list to append to * @param property The property to append * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>property</i> is a <tt>NULL</tt> pointer. * </td> * </tr> * </table> * @enderror * * This function creates a new property and appends it to the end of a property list. * It will not check if the property already exists. */ cpl_error_code cpl_propertylist_append_property(cpl_propertylist *self, const cpl_property *property) { if((self == NULL) || (property == NULL)){ return cpl_error_set_(CPL_ERROR_NULL_INPUT); } cx_deque_push_back(self->properties, cpl_property_duplicate(property)); return CPL_ERROR_NONE; } /** * @brief * Prepend a property to a property list * * @param self Property list to prepend to * @param property The property to prepend * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i> or <i>property</i> is a <tt>NULL</tt> pointer. * </td> * </tr> * </table> * @enderror * * This function creates a new property and prepends it to the beginning of a property list. * It will not check if the property already exists. */ cpl_error_code cpl_propertylist_prepend_property(cpl_propertylist *self, const cpl_property *property) { if((self == NULL) || (property == NULL)){ return cpl_error_set_(CPL_ERROR_NULL_INPUT); } cx_deque_push_front(self->properties, cpl_property_duplicate(property)); return CPL_ERROR_NONE; } /** * @brief * Insert a property into a property list at the given position * * @param self Property list * @param here Name indicating the position where to insert the property * @param property The property to insert * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i>, <i>property</i> or <i>here</i> is a <tt>NULL</tt> pointer. * </td> * </tr> * </table> * @enderror * * The function creates a new property and inserts it into the property list * @em self at the position of the property named @em here. */ cpl_error_code cpl_propertylist_insert_property(cpl_propertylist *self, const char *here, const cpl_property *property) { cx_deque_iterator pos; if (self == NULL || here == NULL || property == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } /* * Find the position where property should be inserted. */ pos = _cpl_propertylist_find(self, here); if (pos == cx_deque_end(self->properties)) { return cpl_error_set_(CPL_ERROR_UNSPECIFIED); } /* * Insert it into the deque */ cx_deque_insert(self->properties, pos, cpl_property_duplicate(property)); return CPL_ERROR_NONE; } /** * @brief * Insert a property into a property list after the given position * * @param self Property list * @param after Name of the property after which to insert the property * @param property The property to insert * * @return * The function returns @c CPL_ERROR_NONE on success or a CPL error * code otherwise. * * * @error * <table class="ec" align="center"> * <tr> * <td class="ecl">CPL_ERROR_NULL_INPUT</td> * <td class="ecr"> * The parameter <i>self</i>, <i>property</i> or <i>after</i> is a <tt>NULL</tt> pointer. * </td> * </tr> * </table> * @enderror * * The function creates a new property and inserts it into the property list * @em self after the position of the property named @em after. */ cpl_error_code cpl_propertylist_insert_after_property(cpl_propertylist *self, const char *after, const cpl_property *property) { cx_deque_iterator pos; if (self == NULL || after == NULL || property == NULL) { return cpl_error_set_(CPL_ERROR_NULL_INPUT); } /* * Find the position where property should be inserted. */ pos = _cpl_propertylist_find(self, after); if (pos == cx_deque_end(self->properties)) { return cpl_error_set_(CPL_ERROR_UNSPECIFIED); } /* * Get the position after it */ pos = cx_deque_next(self->properties, pos); /* * Insert it into the deque */ cx_deque_insert(self->properties, pos, cpl_property_duplicate(property)); return CPL_ERROR_NONE; } /*----------------------------------------------------------------------------*/ /** @internal @brief Generate a valid FITS header for saving functions @param self The fitsfile to modify @param to_add The set of keywords to add to the minimal header @param to_rm The set of keys to remove @return 1 newly allocated valid header The passed file should contain a minimal header. The propertylist is sorted (DICB) and added after the miniaml header. Possible #_cpl_error_code_ set in this function: - CPL_ERROR_NULL_INPUT if self is NULL - CPL_ERROR_ILLEGAL_INPUT if the propertylist cannot be written */ /*----------------------------------------------------------------------------*/ cpl_error_code cpl_fits_add_properties(fitsfile * self, const cpl_propertylist * to_add, const char * to_rm) { cpl_error_code error = CPL_ERROR_NONE; if (to_add != NULL) { cpl_propertylist * out; /* Failure here would indicate a bug in CPL */ cpl_ensure_code(self, CPL_ERROR_NULL_INPUT); if (to_rm != NULL) { /* Copy all but the black-listed properties */ out = cpl_propertylist_new(); if (cpl_propertylist_copy_property_regexp(out, to_add, to_rm, 1)) { error = cpl_error_set_where_(); } } else { out = cpl_propertylist_duplicate(to_add); } if (!error) { const cpl_size ncards = cpl_propertylist_get_size(out); /* Before sorting, set the DICB type sort key, reducing the complexity of that to O(n) */ for (cpl_size i = 0; i < ncards; i++) { cpl_property* myprop = cpl_propertylist_get(out, i); cpl_property_set_sort_dicb(myprop); } /* Sort and write the propertylist to the file */ if (cpl_propertylist_sort(out, cpl_property_compare_sortkey) || cpl_propertylist_to_fitsfile(self, out, NULL)) { error = cpl_error_set_where_(); } } cpl_propertylist_delete(out); } return error; } /**@}*/ /*----------------------------------------------------------------------------*/ /** @internal @brief Get the length of the key of a FITS card @param card A FITS card (80 bytes or more) may not have null terminator @param plen The length, zero for a key-less card, undefined on error @param piparsed The index to the last parsed character @return On succes, points to start of key (skips "HIERARCH "), else NULL @note (Almost) no input validation in this internal function @see fits_get_keyname(), ffgknm() On success *piparsed is the index to the last parsed character, for a ESO HIERARCH card *piparsed is the index of the value indicator ('='), for a non ESO HIERARCH card *piparsed is 8 (whether or not that byte has a value indicator). */ /*----------------------------------------------------------------------------*/ inline static const char * cpl_fits_get_key(const char * card, int * plen, int * piparsed) { const char * kstart; if (!memcmp(card, "HIERARCH ", 9)) { /* A malformed card could be missing its value indicator (and could instead have an '=' sign in its comment) or the key could be invalid. The purpose of this library is not to process invalid FITS data, so in such cases the card may be dropped silently or a property with an unusual key may be created. */ const char * eqpos = memchr(card + 9, '=', FITS_CARD_LEN - 9); if (eqpos) { kstart = card + 9; *piparsed = (int)(eqpos - card); /* If available memrchr() would not help much here, unlikely to find a whole (properly aligned) word of ' ' */ do { eqpos--; } while (*eqpos == ' '); if (eqpos >= kstart) { *plen = (int)(1 + eqpos - kstart); } else { /* This is not a valid ESO HIERARCH card */ kstart = NULL; } } else { /* This is not a valid ESO HIERARCH card */ kstart = NULL; } } else { /* Did CFITSIO nuke the trailing blanks ? */ const char * nullbyte = memchr(card, '\0', 8); if (nullbyte != NULL) { const char * spcpos = memchr(card, ' ', nullbyte - card); *plen = (int)((spcpos ? spcpos : nullbyte) - card); *piparsed = FITS_CARD_LEN; } else { const char * spcpos = memchr(card, ' ', 8); *plen = spcpos ? (int)(spcpos - card) : 8; *piparsed = 8; } kstart = card; } return kstart; } /*----------------------------------------------------------------------------*/ /** @internal @brief Get a numerical value from a FITS card @param card A FITS card (80 bytes), must have null terminator @param iparsed The value from cpl_fits_get_key() or just before the number @param plval On positive return, *plval is the integer, unless NULL @param pdval On negative return, *pdval is the double @param pjparsed The index to the last parsed character @return Positive for int, negative for floating point, zero for NaN (error) @note (Almost) no input validation in this internal function! @see cpl_fits_get_key() On error, *pjparsed is undefined. Parsing a string for a number is non-trivial, so use sscanf(). If plval is non-NULL, the resulting number is either integer or float, as indicatd by the return value. If the string has a decimal point or an exponent part, the resulting number is a float even if its fractional part is zero. If the string has neither but the conversion to a signed long long int causes an overflow, the resulting number is deemed float. */ /*----------------------------------------------------------------------------*/ inline static int cpl_fits_get_number(const char * card, int iparsed, long long * plval, double * pdval, int * pjparsed) { /* The FITS standard (4.2.4) allows for a floating-point constant with a 'D' starting the exponent part. This format cannot by handled by sscanf(). (Coincidentally, in FORTRAN a double precision constant uses a 'D') */ cpl_boolean is_dexp = CPL_FALSE; cx_assert(FITS_CARD_LEN < FLEN_VALUE + iparsed); cx_assert(iparsed < FITS_CARD_LEN); if (plval != NULL) { errno = 0; /* Integer parsing can result in overflow, ERANGE */ if (sscanf(card + iparsed, "%lld%n", plval, pjparsed) > 0 && errno == 0 && *pjparsed > 0 && card[iparsed + *pjparsed] != '.' && card[iparsed + *pjparsed] != 'E') { if (card[iparsed + *pjparsed] != 'D') { *pjparsed += iparsed; return 1; /* Done: It is an integer fitting a long long */ } is_dexp = CPL_TRUE; } } if (!is_dexp && (sscanf(card + iparsed, "%lf%n", pdval, pjparsed) < 1 || *pjparsed < 1)) return 0; /* NaN */ /* The card has a number and it is a floating point (or too large to fit a long long, so we use a double) */ #ifdef CPL_PROPERTYLIST_DEBUG cpl_msg_warning(cpl_func, "FITSSSCAN(%d:%d): %g (%c) %s", iparsed, *pjparsed, *pdval, card[iparsed], card + iparsed); #endif if (card[iparsed + *pjparsed] == 'D') { /* Deal with the FORTRAN-format by replacing the 'D' with an 'E' in a copy */ char numparse[FLEN_VALUE]; (void)memcpy(numparse, card + iparsed, FITS_CARD_LEN - iparsed); numparse[*pjparsed] = 'E'; numparse[FITS_CARD_LEN - iparsed] = '\0'; if (sscanf(numparse, "%lf%n", pdval, pjparsed) < 1 || *pjparsed < 3) return 0; /* Malformed exponent, 0D0 shortest OK */ #ifdef CPL_PROPERTYLIST_DEBUG cpl_msg_warning(cpl_func, "FITSFTRAN(%d:%d): %g (%c) %s", iparsed, *pjparsed, *pdval, card[iparsed], card + iparsed); } else { cpl_msg_warning(cpl_func, "FITSFP(%d:%d): %g", iparsed, *pjparsed, *pdval); #endif } *pjparsed += iparsed; return -1; } /*----------------------------------------------------------------------------*/ /** @internal @brief Get the parsed value and the comment location of a FITS card @param pparseval On succes, the parsed value and its type @param card A FITS card (80 bytes), must have null terminator @param iparsed The value from cpl_fits_get_key() @param naxis Used to more efficiently find cards that must be float @param keywlen The name w. length of the property, used w. naxis @param pjparsed The index to the last parsed character (comment separator, /) @return The FITS type code, or zero on error @note (Almost) no input validation in this internal function! @see fits_parse_value(), ffpsvc(), ffdtyp() The possible return values are thes FITS type codes: 'C', 'L', 'F', 'I', 'X' - as well as 'U' (undefined), 'N' (none) or 0 (unparsable value in card) If the card has no value indicator, everything after its expected location is deemed a comment, per FITS standard sections 4.1.2.2 and 4.1.2.3. If the value is of type string, the enclosing quotes are left out. If the string itself contains (FITS-encoded, per 4.2.1 1) quotes, each is converted. If the string itself contains no quotes, the pointer to its value points to the relevant byte in the input card, so that string value is only valid while the card itself it. On error, *pjparsed is undefined. */ /*----------------------------------------------------------------------------*/ inline static char cpl_fits_get_value(cpl_fits_value * pparseval, const char * card, int iparsed, int naxis, const cpl_cstr * keywlen, int * pjparsed) { if (card[iparsed] != '=' || cx_string_size_(keywlen) == 0 || (cx_string_size_(keywlen) == 7 && (!memcmp("COMMENT", cx_string_get_(keywlen), 7) || !memcmp("HISTORY", cx_string_get_(keywlen), 7)))) { /* Card is commentary, i.e. it has no value indicator or it is a COMMENT/HISTORY or blank card, see FITS std. 4.4.2.4. Everything after the key is a comment */ /* Did CFITSIO nuke the trailing blanks ? */ const char * nullbyte = memchr(card, '\0', 8); pparseval->tcode = 'N'; *pjparsed = nullbyte ? FITS_CARD_LEN : 8; } else { /* Value indicator is present */ /* - skip it and any leading spaces */ do { iparsed++; } while (iparsed < FITS_CARD_LEN && card[iparsed] == ' '); if (iparsed < FITS_CARD_LEN && card[iparsed] != 0) { /* Did CFITSIO nuke the trailing blanks ? */ /* card[iparsed] now points to the first value byte */ /* Assume failure */ pparseval->nmemb = 0; pparseval->tcode = 0; switch (card[iparsed]) { case '\'': { /* character string starts with a quote */ const char * nextquote; int vallen = 0; /* The number of value characters */ /* - need to increase iparsed to point past current quote when looking for the next one */ iparsed++; while ((nextquote = memchr(card + iparsed, '\'', FITS_CARD_LEN - iparsed)) != NULL /* We silently ignore the error where there is 1 byte after the ending quote and before the end-of-record and that last byte equals a quote */ && nextquote + 1 < card + FITS_CARD_LEN && nextquote[1] == '\'') { /* O''HARA -> O'HARA */ /* The parsed string differs from the FITS-encoded, so we need to copy it (including the found quote) */ (void)memcpy(pparseval->unquote + vallen, card + iparsed, (int)(nextquote + 1 - card - iparsed)); vallen += (int)(nextquote + 1 - card - iparsed); /* iparsed must be updated to point to the 2nd quote */ iparsed = 2 + nextquote - card; } if (nextquote != NULL) { /* Found the ending quote (none would be a format error) */ pparseval->tcode = 'C'; if (vallen > 0) { /* Wrote to decoded string buffer */ pparseval->val.c = pparseval->unquote; /* Copy part of string following encoded quote */ (void)memcpy(pparseval->unquote + vallen, card + iparsed, (int)(nextquote - card - iparsed)); } else { /* Reference to original, quote-free string */ pparseval->val.c = card + iparsed; } vallen += (int)(nextquote - card - iparsed); /* FITS standard 4.2.1 1: Given the example "KEYWORD2= ' ' / empty string keyword" and the statement "the value of the KEYWORD2 is an empty string (nominally " "a single space character because the first space in the " " string is significant, but trailing spaces are not)." a string consisting solely of spaces is deemed to be empty */ while (vallen > 0 && pparseval->val.c[vallen - 1] == ' ') { vallen--; } /* Update iparsed to point to first byte after value */ iparsed = 1 + (int)(nextquote - card); } pparseval->nmemb = vallen; break; } case 'T': pparseval->val.l = 1; pparseval->nmemb = 1; pparseval->tcode = 'L'; /* logical True ('T' character) */ /* Update iparsed to point to first byte after value */ iparsed++; break; case 'F': pparseval->val.l = 0; pparseval->nmemb = 1; pparseval->tcode = 'L'; /* logical: False ('F' character) */ /* Update iparsed to point to first byte after value */ iparsed++; break; case '(': { double dval[2]; const char dsep[2] = {',', ')'}; int i; iparsed++; /* Skip '(' */ for (i = 0; i < 2; i++) { /* FITS std. 4.2.5: Integer allowed, but parse it as double since that is all we can store */ const int ntype = cpl_fits_get_number(card, iparsed, NULL, dval + i, &iparsed); if (ntype != -1) break; /* FITS std. 4.2.5/6: Trailing blanks are allowed */ while (iparsed < FITS_CARD_LEN && card[iparsed] == ' ') { iparsed++; } if (!(iparsed < FITS_CARD_LEN) || card[iparsed] != dsep[i]) break; iparsed++; } if (i < 2) { pparseval->nmemb = 0; pparseval->tcode = 0; } else { pparseval->val.x = dval[0] + dval[1] * _Complex_I; pparseval->nmemb = 1; pparseval->tcode = 'X'; /* complex datatype "(1.2, -3.4)" */ } break; } case '/': /* Undefinded value - with a comment */ pparseval->nmemb = 0; pparseval->tcode = 'U'; break; /* No value found, so do not advance iparsed */ default: { /* Numerical type */ /* In determining whether it is int or float, we might as well parse it. */ double dvalue = 0.0; long long lvalue = 0; /* Certain (WCS) keywords must be floating point, even if their FITS encoding is a valid integer. Use the value of NAXIS to simplify the check. */ long long * plvalue = cpl_property_find_type(keywlen, naxis) == 'F' ? NULL : &lvalue; #ifdef CPL_PROPERTYLIST_DEBUG const int iiparsed = iparsed; #endif const int ntype = cpl_fits_get_number(card, iparsed, plvalue, &dvalue, &iparsed); #ifdef CPL_PROPERTYLIST_DEBUG cpl_msg_warning(cpl_func, "FITSNUM(%d:%d<=%d): %lld %g (%c) %s", ntype, iiparsed, iparsed, lvalue, dvalue, card[iparsed], card + iparsed); #endif if (ntype != 0) { if (ntype < 0) { pparseval->tcode = 'F'; pparseval->val.f = dvalue; } else { pparseval->tcode = 'I'; pparseval->val.i = lvalue; } pparseval->nmemb = 1; } } } /* Now iparsed points to first byte after value */ if (pparseval->tcode != 0) { /* Found value. Card OK ? */ if (CPL_LIKELY(card[iparsed] == ' ' || card[iparsed] == '/' || card[iparsed] == '\0')) { const char * comchar = memchr(card + iparsed, '/', FITS_CARD_LEN - iparsed); if (comchar == NULL) { *pjparsed = FITS_CARD_LEN; /* Nothing left */ } else { *pjparsed = (int)(comchar - card); } } else { /* A value was found, but a subsequent byte is invalid */ pparseval->tcode = 0; pparseval->nmemb = 0; *pjparsed = iparsed; /* Invalid character - for error msg */ } } return pparseval->tcode; } /* The value and its type is undefined, both value and comment have zero length*/ pparseval->tcode = 'U'; *pjparsed = FITS_CARD_LEN; /* Nothing left */ } /* No value */ pparseval->nmemb = 0; return pparseval->tcode; } /*----------------------------------------------------------------------------*/ /** @internal @brief Get the comment of a FITS card @param card A FITS card (80 bytes or more) may not have null terminator @param jparsed The value from cpl_fits_get_value() @param plen The length when present, otherwise zero @return Points to start of comment, or NULL if no comment present @note (Almost) no input validation in this internal function @see fits_get_keyname(), ffgknm() A value of 80 (or more) for jparsed is allowed and interpreted as no comment available. */ /*----------------------------------------------------------------------------*/ inline static const char * cpl_fits_get_comment(const char * card, int jparsed, int * plen) { /* The comment is not a comment if it is empty */ if (jparsed + 1 < FITS_CARD_LEN && card[jparsed++] == '/') { /* CFITSIO insists on turning the 80 byte FITS record into a string */ const char * nullchr = memchr(card + jparsed, 0, FITS_CARD_LEN - jparsed); const int cardlen = nullchr ? (nullchr - card) : FITS_CARD_LEN; /* Since for some comments it is recommended that a space follows the comment byte (/) (FITS standard 4.3.2), such a space is not considered part of the commentary text */ if (card[jparsed] == ' ') jparsed++; if (jparsed < cardlen) { *plen = cardlen - jparsed; /* Drop trailing spaces */ while (card[jparsed + *plen - 1] == ' ' && *plen > 0) { *plen -= 1; } return *plen > 0 ? card + jparsed : NULL; } } *plen = 0; return NULL; } /*----------------------------------------------------------------------------*/ /** @internal @brief Deallocate memory used for checkning key uniqueness @param putkey Array of keys arrays already written, ordered after length @return Nothing @note (Almost) no input validation in this internal function */ /*----------------------------------------------------------------------------*/ inline static void cpl_fits_key_free_unique(const char ** putkey[]) { #ifdef CPL_PROPERTYLIST_DEBUG cpl_size maxpos = 0; cpl_size maxlen = 0; cpl_size nonull = 0; #endif for (cpl_size i = 0; i < FLEN_KEYWORD; i++) { if (putkey[i]) { #ifdef CPL_PROPERTYLIST_DEBUG cpl_size k = 0; while (putkey[i][k++] != NULL); nonull++; if (k > maxlen) { maxlen = k; maxpos = i; } cpl_msg_info(cpl_func, "UNIQ-check(%d<%d): %d", (int)i, FLEN_KEYWORD, (int)k); #endif cpl_free(putkey[i]); } } #ifdef CPL_PROPERTYLIST_DEBUG cpl_msg_warning(cpl_func, "UNIQ-CHECK(%d:%d<%d): %d", (int)nonull, (int)maxpos, FLEN_KEYWORD, (int)maxlen); #endif } /*----------------------------------------------------------------------------*/ /** @internal @brief Uniqueness check of a key with the given length @param KLEN The key length @return Nothing @note (Almost) no input validation in this internal macro */ /*----------------------------------------------------------------------------*/ #define CPL_FITS_IS_UNIQUE_ONE(KLEN) \ do { \ cpl_size i = 0; \ if (putkey[KLEN] != NULL) { \ do { \ if (!memcmp(putkey[KLEN][i], keyname, KLEN)) return 1; \ } while (putkey[KLEN][++i] != NULL); \ } else { \ /* One extra for the NULL-terminator */ \ putkey[KLEN] = cpl_malloc((ntocheck + 2) * sizeof(char *)); \ } \ \ putkey[KLEN][i ] = keyname; \ putkey[KLEN][i + 1] = NULL; \ \ } while (0) /*----------------------------------------------------------------------------*/ /** @internal @brief Uniqueness check of a key with the given length, larger than 8 @param KLEN The key length @return Nothing @note Longer keys tend to differ only at the end, call memcmp() differently @see CPL_FITS_IS_UNIQUE_ONE() */ /*----------------------------------------------------------------------------*/ #define CPL_FITS_IS_UNIQUE_TWO(KLEN) \ do { \ cpl_size i = 0; \ if (putkey[KLEN] != NULL) { \ do { \ if (!memcmp(putkey[KLEN][i] + KLEN - 8, keyname + KLEN - 8, 8) && \ !memcmp(putkey[KLEN][i], keyname, KLEN - 8)) return 1; \ } while (putkey[KLEN][++i] != NULL); \ } else { \ /* One extra for the NULL-terminator */ \ putkey[KLEN] = cpl_malloc((ntocheck + 2) * sizeof(char *)); \ } \ \ putkey[KLEN][i ] = keyname; \ putkey[KLEN][i + 1] = NULL; \ \ } while (0) /*----------------------------------------------------------------------------*/ /** @internal @brief Check if a FITS card has already been written @param putkey Array of keys arrays already written, ordered after length @param key The key to check @param ntocheck Number of keys to check after this one @return Zero if the card has not (yet) been written, negative if exempt @note (Almost) no input validation in this internal function As a poor-man's hash this check first groups written keys according to their length, so the actual string comparison is done only on keys with matching lengths, reducing the number of memcmp() calls. An option would also be to group the already seen keys according to their sortkey. However, with the grouping according to length, and with keys that do not share the sorting key typically differing within their first 8 bytes, this is not worth the added complexity and increased number of buffers. */ /*----------------------------------------------------------------------------*/ inline static cxint cpl_fits_key_is_unique(const char **putkey[], const cpl_cstr * key, cpl_size ntocheck) { cxsize keylen = cx_string_size_(key); const char * keyname = cx_string_get_(key); /* Trailing blanks in the key should not occur. Regardless (and since for a normal key it is only one check), make sure to remove any since they would be ignored in a FITS card. */ while (CPL_LIKELY(keylen > 0) && CPL_UNLIKELY(keyname[keylen - 1] == ' ')) { keylen--; } /* Use this cumbersome switch so each call to memcmp() can be inline'd */ /* No point in distinguishing among keys too long to convert to FITS */ switch (CX_MIN(keylen, FLEN_KEYWORD - 1)) { case 0: return -1; /* Zero length may come from all spaces */ case 1: CPL_FITS_IS_UNIQUE_ONE(1); break; case 2: CPL_FITS_IS_UNIQUE_ONE(2); break; case 3: CPL_FITS_IS_UNIQUE_ONE(3); break; case 4: CPL_FITS_IS_UNIQUE_ONE(4); break; case 5: CPL_FITS_IS_UNIQUE_ONE(5); break; case 6: CPL_FITS_IS_UNIQUE_ONE(6); break; case 7: if (!memcmp("COMMENT", keyname, 7) || !memcmp("HISTORY", keyname, 7)) return -1; CPL_FITS_IS_UNIQUE_ONE(7); break; case 8: CPL_FITS_IS_UNIQUE_ONE(8); break; case 9: CPL_FITS_IS_UNIQUE_TWO(9); break; case 10: CPL_FITS_IS_UNIQUE_TWO(10); break; case 11: CPL_FITS_IS_UNIQUE_TWO(11); break; case 12: CPL_FITS_IS_UNIQUE_TWO(12); break; case 13: CPL_FITS_IS_UNIQUE_TWO(13); break; case 14: CPL_FITS_IS_UNIQUE_TWO(14); break; case 15: CPL_FITS_IS_UNIQUE_TWO(15); break; case 16: CPL_FITS_IS_UNIQUE_TWO(16); break; case 17: CPL_FITS_IS_UNIQUE_TWO(17); break; case 18: CPL_FITS_IS_UNIQUE_TWO(18); break; case 19: CPL_FITS_IS_UNIQUE_TWO(19); break; case 20: CPL_FITS_IS_UNIQUE_TWO(20); break; case 21: CPL_FITS_IS_UNIQUE_TWO(21); break; case 22: CPL_FITS_IS_UNIQUE_TWO(22); break; case 23: CPL_FITS_IS_UNIQUE_TWO(23); break; case 24: CPL_FITS_IS_UNIQUE_TWO(24); break; case 25: CPL_FITS_IS_UNIQUE_TWO(25); break; case 26: CPL_FITS_IS_UNIQUE_TWO(26); break; case 27: CPL_FITS_IS_UNIQUE_TWO(27); break; case 28: CPL_FITS_IS_UNIQUE_TWO(28); break; case 29: CPL_FITS_IS_UNIQUE_TWO(29); break; case 30: CPL_FITS_IS_UNIQUE_TWO(30); break; case 31: CPL_FITS_IS_UNIQUE_TWO(31); break; case 32: CPL_FITS_IS_UNIQUE_TWO(32); break; case 33: CPL_FITS_IS_UNIQUE_TWO(33); break; case 34: CPL_FITS_IS_UNIQUE_TWO(34); break; case 35: CPL_FITS_IS_UNIQUE_TWO(35); break; case 36: CPL_FITS_IS_UNIQUE_TWO(36); break; case 37: CPL_FITS_IS_UNIQUE_TWO(37); break; case 38: CPL_FITS_IS_UNIQUE_TWO(38); break; case 39: CPL_FITS_IS_UNIQUE_TWO(39); break; case 40: CPL_FITS_IS_UNIQUE_TWO(40); break; case 41: CPL_FITS_IS_UNIQUE_TWO(41); break; case 42: CPL_FITS_IS_UNIQUE_TWO(42); break; case 43: CPL_FITS_IS_UNIQUE_TWO(43); break; case 44: CPL_FITS_IS_UNIQUE_TWO(44); break; case 45: CPL_FITS_IS_UNIQUE_TWO(45); break; case 46: CPL_FITS_IS_UNIQUE_TWO(46); break; case 47: CPL_FITS_IS_UNIQUE_TWO(47); break; case 48: CPL_FITS_IS_UNIQUE_TWO(48); break; case 49: CPL_FITS_IS_UNIQUE_TWO(49); break; case 50: CPL_FITS_IS_UNIQUE_TWO(50); break; case 51: CPL_FITS_IS_UNIQUE_TWO(51); break; case 52: CPL_FITS_IS_UNIQUE_TWO(52); break; case 53: CPL_FITS_IS_UNIQUE_TWO(53); break; case 54: CPL_FITS_IS_UNIQUE_TWO(54); break; case 55: CPL_FITS_IS_UNIQUE_TWO(55); break; case 56: CPL_FITS_IS_UNIQUE_TWO(56); break; case 57: CPL_FITS_IS_UNIQUE_TWO(57); break; case 58: CPL_FITS_IS_UNIQUE_TWO(58); break; case 59: CPL_FITS_IS_UNIQUE_TWO(59); break; case 60: CPL_FITS_IS_UNIQUE_TWO(60); break; case 61: CPL_FITS_IS_UNIQUE_TWO(61); break; case 62: CPL_FITS_IS_UNIQUE_TWO(62); break; case 63: CPL_FITS_IS_UNIQUE_TWO(63); break; case 64: CPL_FITS_IS_UNIQUE_TWO(64); break; case 65: CPL_FITS_IS_UNIQUE_TWO(65); break; case 66: CPL_FITS_IS_UNIQUE_TWO(66); break; case 67: CPL_FITS_IS_UNIQUE_TWO(67); break; case 68: CPL_FITS_IS_UNIQUE_TWO(68); break; case 69: CPL_FITS_IS_UNIQUE_TWO(69); break; case 70: CPL_FITS_IS_UNIQUE_TWO(70); break; case 71: CPL_FITS_IS_UNIQUE_TWO(71); break; } return 0; }
27.847331
97
0.583767
862c43bb2d1f02b559f91631361fad0de24827d4
1,586
h
C
src/sensors/ina219.h
vorsselmansphilip/SenseEsp-Universal-Module
41af4dca2f65c527551848f1246986d639d4fdfd
[ "Apache-2.0" ]
1
2020-10-30T19:22:19.000Z
2020-10-30T19:22:19.000Z
src/sensors/ina219.h
vorsselmansphilip/SenseEsp-Universal-Module
41af4dca2f65c527551848f1246986d639d4fdfd
[ "Apache-2.0" ]
null
null
null
src/sensors/ina219.h
vorsselmansphilip/SenseEsp-Universal-Module
41af4dca2f65c527551848f1246986d639d4fdfd
[ "Apache-2.0" ]
null
null
null
#ifndef _ina219_H_ #define _ina219_H_ #include <Wire.h> #include <Adafruit_INA219.h> #include "sensor.h" // The INA219 classes are based on the ADAfruit_INA219 library. // These are the used to tell the constructor what to set for maximum voltage and amperage. // The default in the Adafruit constructor is 32V and 2A, so we only need to handle the other two. enum INA219CAL_t { cal32_2, cal32_1, cal16_400 }; // INA219 represents an ADAfruit (or compatible) INA219 High Side DC Current Sensor. // The constructor creates a pointer to the instance, and starts up the sensor. The pointer is // passed to INA219value, which retrieves the specified value. // class INA219 : public Sensor { public: INA219(uint8_t addr = 0x40, INA219CAL_t calibration_setting = cal32_2, String config_path = ""); Adafruit_INA219* pAdafruitINA219; }; // Pass one of these in the constructor to INA219value() to tell which type of value you want to output enum INA219ValType { bus_voltage, shunt_voltage, current, power, load_voltage }; // INA219value reads and outputs the specified value of a INA219 sensor. class INA219value : public NumericSensor { public: INA219value(INA219* pINA219, INA219ValType val_type, uint read_delay = 500, String config_path=""); void enable() override final; INA219* pINA219; private: INA219ValType val_type; uint read_delay; virtual JsonObject& get_configuration(JsonBuffer& buf) override; virtual bool set_configuration(const JsonObject& config) override; virtual String get_config_schema() override; }; #endif
33.041667
103
0.755359
22a9caa4453791e8ccc8022563011ec2a715f032
77
h
C
arch/x64/sysroot/include/sys/reg.h
FuchsiaOS/Fuchsia-SDK
869668003f20d560a40802c7d820ef0fefba0462
[ "BSD-3-Clause" ]
49
2018-12-20T00:35:06.000Z
2021-12-30T22:40:05.000Z
arch/x64/sysroot/include/sys/reg.h
gxbllm/Fuchsia-SDK
869668003f20d560a40802c7d820ef0fefba0462
[ "BSD-3-Clause" ]
null
null
null
arch/x64/sysroot/include/sys/reg.h
gxbllm/Fuchsia-SDK
869668003f20d560a40802c7d820ef0fefba0462
[ "BSD-3-Clause" ]
21
2019-01-03T11:06:10.000Z
2021-08-06T00:55:50.000Z
#pragma once #include <limits.h> #include <unistd.h> #include <bits/reg.h>
11
21
0.688312
af00588972a2b3c9f17dd43442f861a52c314458
441
h
C
XJHCLManager/Classes/XJHCLManagerParamBuilder.h
cocoadogs/XJHCLManager
590d5be3d1522fcaaa34e45f21ef8019f7580359
[ "MIT" ]
null
null
null
XJHCLManager/Classes/XJHCLManagerParamBuilder.h
cocoadogs/XJHCLManager
590d5be3d1522fcaaa34e45f21ef8019f7580359
[ "MIT" ]
null
null
null
XJHCLManager/Classes/XJHCLManagerParamBuilder.h
cocoadogs/XJHCLManager
590d5be3d1522fcaaa34e45f21ef8019f7580359
[ "MIT" ]
null
null
null
// // XJHCLManagerParamBuilder.h // XJHCLManager // // Created by xujunhao on 2018/9/4. // XJHCLManager参数配置 #import <Foundation/Foundation.h> @interface XJHCLManagerParamBuilder : NSObject ///弹框标题 @property (nonatomic, copy) NSString *title; ///弹框提示信息 @property (nonatomic, copy) NSString *message; ///取消按键标题,默认为'取消' @property (nonatomic, copy) NSString *cancel; ///确认按键标题,默认为'设置' @property (nonatomic, copy) NSString *setting; @end
20.045455
46
0.730159
6665feba5d7689ddf19ae0e31d4006f361960642
23,006
c
C
raspberry/nfc_deamon/SW369321/NxpNfcRdLib/comps/phpalI14443p3a/src/phpalI14443p3a.c
ccruzp/drs-netatmo
87d178364dbc8c1e7259a9d7d202c9f1c86b6d2f
[ "MIT" ]
2
2019-11-08T12:45:38.000Z
2019-11-09T16:31:12.000Z
raspberry/nfc_deamon/SW369321/NxpNfcRdLib/comps/phpalI14443p3a/src/phpalI14443p3a.c
ccruzp/drs-netatmo
87d178364dbc8c1e7259a9d7d202c9f1c86b6d2f
[ "MIT" ]
null
null
null
raspberry/nfc_deamon/SW369321/NxpNfcRdLib/comps/phpalI14443p3a/src/phpalI14443p3a.c
ccruzp/drs-netatmo
87d178364dbc8c1e7259a9d7d202c9f1c86b6d2f
[ "MIT" ]
2
2019-11-07T21:56:59.000Z
2019-11-08T02:20:59.000Z
/* * Copyright (c), NXP Semiconductors Gratkorn / Austria * * (C)NXP Semiconductors * All rights are reserved. Reproduction in whole or in part is * prohibited without the written consent of the copyright owner. * NXP reserves the right to make changes without notice at any time. * NXP makes no warranty, expressed, implied or statutory, including but * not limited to any implied warranty of merchantability or fitness for any *particular purpose, or that the use will not infringe any third party patent, * copyright or trademark. NXP must not be liable for any loss or damage * arising from its use. */ /** \file * Generic ISO14443-3A Component of Reader Library Framework. * $Author$ * $Revision$ (v05.22.00) * $Date$ * * History: * CHu: Generated 19. May 2009 * */ #include <ph_Status.h> #include <phpalI14443p3a.h> #include <ph_RefDefs.h> #ifdef NXPBUILD__PHPAL_I14443P3A_SW #include "Sw/phpalI14443p3a_Sw.h" #endif /* NXPBUILD__PHPAL_I14443P3A_SW */ #ifdef NXPBUILD__PHPAL_I14443P3A #ifndef NXPRDLIB_REM_GEN_INTFS phStatus_t phpalI14443p3a_SetConfig( void * pDataParams, uint16_t wConfig, uint16_t wValue ) { phStatus_t PH_MEMLOC_REM status; PH_LOG_HELPER_ALLOCATE_TEXT(bFunctionName, "phpalI14443p3a_SetConfig"); PH_LOG_HELPER_ALLOCATE_PARAMNAME(status); PH_LOG_HELPER_ADDSTRING(PH_LOG_LOGTYPE_INFO, bFunctionName); PH_LOG_HELPER_EXECUTE(PH_LOG_OPTION_CATEGORY_ENTER); /* Check data parameters */ if (PH_GET_COMPCODE(pDataParams) != PH_COMP_PAL_ISO14443P3A) { status = PH_ADD_COMPCODE_FIXED(PH_ERR_INVALID_DATA_PARAMS, PH_COMP_PAL_ISO14443P3A); PH_LOG_HELPER_ADDSTRING(PH_LOG_LOGTYPE_INFO, bFunctionName); PH_LOG_HELPER_ADDPARAM_UINT16(PH_LOG_LOGTYPE_INFO, status_log, &status); PH_LOG_HELPER_EXECUTE(PH_LOG_OPTION_CATEGORY_LEAVE); return status; } /* perform operation on active layer */ switch (PH_GET_COMPID(pDataParams)) { #ifdef NXPBUILD__PHPAL_I14443P3A_SW case PHPAL_I14443P3A_SW_ID: status = phpalI14443p3a_Sw_SetConfig((phpalI14443p3a_Sw_DataParams_t *)pDataParams, wConfig,wValue); break; #endif /* NXPBUILD__PHPAL_I14443P3A_SW */ default: status = PH_ADD_COMPCODE_FIXED(PH_ERR_INVALID_DATA_PARAMS, PH_COMP_PAL_ISO14443P3A); break; } PH_LOG_HELPER_ADDSTRING(PH_LOG_LOGTYPE_INFO, bFunctionName); PH_LOG_HELPER_ADDPARAM_UINT16(PH_LOG_LOGTYPE_INFO, status_log, &status); PH_LOG_HELPER_EXECUTE(PH_LOG_OPTION_CATEGORY_LEAVE); return status; } phStatus_t phpalI14443p3a_GetConfig( void * pDataParams, uint16_t wConfig, uint16_t *pValue ) { phStatus_t PH_MEMLOC_REM status; PH_LOG_HELPER_ALLOCATE_TEXT(bFunctionName, "phpalI14443p3a_GetConfig"); PH_LOG_HELPER_ALLOCATE_PARAMNAME(status); PH_LOG_HELPER_ADDSTRING(PH_LOG_LOGTYPE_INFO, bFunctionName); PH_LOG_HELPER_EXECUTE(PH_LOG_OPTION_CATEGORY_ENTER); /* Check data parameters */ if (PH_GET_COMPCODE(pDataParams) != PH_COMP_PAL_ISO14443P3A) { status = PH_ADD_COMPCODE_FIXED(PH_ERR_INVALID_DATA_PARAMS, PH_COMP_PAL_ISO14443P3A); PH_LOG_HELPER_ADDSTRING(PH_LOG_LOGTYPE_INFO, bFunctionName); PH_LOG_HELPER_ADDPARAM_UINT16(PH_LOG_LOGTYPE_INFO, status_log, &status); PH_LOG_HELPER_EXECUTE(PH_LOG_OPTION_CATEGORY_LEAVE); return status; } /* perform operation on active layer */ switch (PH_GET_COMPID(pDataParams)) { #ifdef NXPBUILD__PHPAL_I14443P3A_SW case PHPAL_I14443P3A_SW_ID: status = phpalI14443p3a_Sw_GetConfig((phpalI14443p3a_Sw_DataParams_t *)pDataParams, wConfig, pValue); break; #endif /* NXPBUILD__PHPAL_I14443P3A_SW */ default: status = PH_ADD_COMPCODE_FIXED(PH_ERR_INVALID_DATA_PARAMS, PH_COMP_PAL_ISO14443P3A); break; } PH_LOG_HELPER_ADDSTRING(PH_LOG_LOGTYPE_INFO, bFunctionName); PH_LOG_HELPER_ADDPARAM_UINT16(PH_LOG_LOGTYPE_INFO, status_log, &status); PH_LOG_HELPER_EXECUTE(PH_LOG_OPTION_CATEGORY_LEAVE); return status; } phStatus_t phpalI14443p3a_RequestA( void * pDataParams, uint8_t * pAtqa ) { phStatus_t PH_MEMLOC_REM status; PH_LOG_HELPER_ALLOCATE_TEXT(bFunctionName, "phpalI14443p3a_RequestA"); /*PH_LOG_HELPER_ALLOCATE_PARAMNAME(pDataParams);*/ PH_LOG_HELPER_ALLOCATE_PARAMNAME(pAtqa); PH_LOG_HELPER_ALLOCATE_PARAMNAME(status); PH_LOG_HELPER_ADDSTRING(PH_LOG_LOGTYPE_INFO, bFunctionName); PH_LOG_HELPER_EXECUTE(PH_LOG_OPTION_CATEGORY_ENTER); PH_ASSERT_NULL (pDataParams); PH_ASSERT_NULL (pAtqa); /* Check data parameters */ if (PH_GET_COMPCODE(pDataParams) != PH_COMP_PAL_ISO14443P3A) { status = PH_ADD_COMPCODE_FIXED(PH_ERR_INVALID_DATA_PARAMS, PH_COMP_PAL_ISO14443P3A); PH_LOG_HELPER_ADDSTRING(PH_LOG_LOGTYPE_INFO, bFunctionName); PH_LOG_HELPER_ADDPARAM_UINT16(PH_LOG_LOGTYPE_INFO, status_log, &status); PH_LOG_HELPER_EXECUTE(PH_LOG_OPTION_CATEGORY_LEAVE); return status; } /* perform operation on active layer */ switch (PH_GET_COMPID(pDataParams)) { #ifdef NXPBUILD__PHPAL_I14443P3A_SW case PHPAL_I14443P3A_SW_ID: status = phpalI14443p3a_Sw_RequestA((phpalI14443p3a_Sw_DataParams_t *)pDataParams, pAtqa); break; #endif /* NXPBUILD__PHPAL_I14443P3A_SW */ default: status = PH_ADD_COMPCODE_FIXED(PH_ERR_INVALID_DATA_PARAMS, PH_COMP_PAL_ISO14443P3A); break; } PH_LOG_HELPER_ADDSTRING(PH_LOG_LOGTYPE_INFO, bFunctionName); #ifdef NXPBUILD__PH_LOG if ((status & PH_ERR_MASK) == PH_ERR_SUCCESS) { PH_LOG_HELPER_ADDPARAM_BUFFER(PH_LOG_LOGTYPE_DEBUG, pAtqa_log, pAtqa, 2); } #endif PH_LOG_HELPER_ADDPARAM_UINT16(PH_LOG_LOGTYPE_INFO, status_log, &status); PH_LOG_HELPER_EXECUTE(PH_LOG_OPTION_CATEGORY_LEAVE); return status; } phStatus_t phpalI14443p3a_WakeUpA( void * pDataParams, uint8_t * pAtqa ) { phStatus_t PH_MEMLOC_REM status; PH_LOG_HELPER_ALLOCATE_TEXT(bFunctionName, "phpalI14443p3a_WakeUpA"); /*PH_LOG_HELPER_ALLOCATE_PARAMNAME(pDataParams);*/ PH_LOG_HELPER_ALLOCATE_PARAMNAME(pAtqa); PH_LOG_HELPER_ALLOCATE_PARAMNAME(status); PH_LOG_HELPER_ADDSTRING(PH_LOG_LOGTYPE_INFO, bFunctionName); PH_LOG_HELPER_EXECUTE(PH_LOG_OPTION_CATEGORY_ENTER); PH_ASSERT_NULL (pDataParams); PH_ASSERT_NULL (pAtqa); /* Check data parameters */ if (PH_GET_COMPCODE(pDataParams) != PH_COMP_PAL_ISO14443P3A) { status = PH_ADD_COMPCODE_FIXED(PH_ERR_INVALID_DATA_PARAMS, PH_COMP_PAL_ISO14443P3A); PH_LOG_HELPER_ADDSTRING(PH_LOG_LOGTYPE_INFO, bFunctionName); PH_LOG_HELPER_ADDPARAM_UINT16(PH_LOG_LOGTYPE_INFO, status_log, &status); PH_LOG_HELPER_EXECUTE(PH_LOG_OPTION_CATEGORY_LEAVE); return status; } /* perform operation on active layer */ switch (PH_GET_COMPID(pDataParams)) { #ifdef NXPBUILD__PHPAL_I14443P3A_SW case PHPAL_I14443P3A_SW_ID: status = phpalI14443p3a_Sw_WakeUpA((phpalI14443p3a_Sw_DataParams_t *)pDataParams, pAtqa); break; #endif /* NXPBUILD__PHPAL_I14443P3A_SW */ default: status = PH_ADD_COMPCODE_FIXED(PH_ERR_INVALID_DATA_PARAMS, PH_COMP_PAL_ISO14443P3A); break; } PH_LOG_HELPER_ADDSTRING(PH_LOG_LOGTYPE_INFO, bFunctionName); #ifdef NXPBUILD__PH_LOG if ((status & PH_ERR_MASK) == PH_ERR_SUCCESS) { PH_LOG_HELPER_ADDPARAM_BUFFER(PH_LOG_LOGTYPE_DEBUG, pAtqa_log, pAtqa, 2); } #endif PH_LOG_HELPER_ADDPARAM_UINT16(PH_LOG_LOGTYPE_INFO, status_log, &status); PH_LOG_HELPER_EXECUTE(PH_LOG_OPTION_CATEGORY_LEAVE); return status; } phStatus_t phpalI14443p3a_HaltA( void * pDataParams ) { phStatus_t PH_MEMLOC_REM status; PH_LOG_HELPER_ALLOCATE_TEXT(bFunctionName, "phpalI14443p3a_HaltA"); /*PH_LOG_HELPER_ALLOCATE_PARAMNAME(pDataParams);*/ PH_LOG_HELPER_ALLOCATE_PARAMNAME(status); PH_LOG_HELPER_ADDSTRING(PH_LOG_LOGTYPE_INFO, bFunctionName); PH_LOG_HELPER_EXECUTE(PH_LOG_OPTION_CATEGORY_ENTER); PH_ASSERT_NULL (pDataParams); /* Check data parameters */ if (PH_GET_COMPCODE(pDataParams) != PH_COMP_PAL_ISO14443P3A) { status = PH_ADD_COMPCODE_FIXED(PH_ERR_INVALID_DATA_PARAMS, PH_COMP_PAL_ISO14443P3A); PH_LOG_HELPER_ADDSTRING(PH_LOG_LOGTYPE_INFO, bFunctionName); PH_LOG_HELPER_ADDPARAM_UINT16(PH_LOG_LOGTYPE_INFO, status_log, &status); PH_LOG_HELPER_EXECUTE(PH_LOG_OPTION_CATEGORY_LEAVE); return status; } /* perform operation on active layer */ switch (PH_GET_COMPID(pDataParams)) { #ifdef NXPBUILD__PHPAL_I14443P3A_SW case PHPAL_I14443P3A_SW_ID: status = phpalI14443p3a_Sw_HaltA((phpalI14443p3a_Sw_DataParams_t *)pDataParams); break; #endif /* NXPBUILD__PHPAL_I14443P3A_SW */ default: status = PH_ADD_COMPCODE_FIXED(PH_ERR_INVALID_DATA_PARAMS, PH_COMP_PAL_ISO14443P3A); break; } PH_LOG_HELPER_ADDSTRING(PH_LOG_LOGTYPE_INFO, bFunctionName); PH_LOG_HELPER_ADDPARAM_UINT16(PH_LOG_LOGTYPE_INFO, status_log, &status); PH_LOG_HELPER_EXECUTE(PH_LOG_OPTION_CATEGORY_LEAVE); return status; } phStatus_t phpalI14443p3a_Anticollision( void * pDataParams, uint8_t bCascadeLevel, uint8_t * pUidIn, uint8_t bNvbUidIn, uint8_t * pUidOut, uint8_t * pNvbUidOut ) { phStatus_t PH_MEMLOC_REM status; #ifdef NXPBUILD__PH_LOG uint8_t PH_MEMLOC_REM bNvBUid; #endif PH_LOG_HELPER_ALLOCATE_TEXT(bFunctionName, "phpalI14443p3a_Anticollision"); /*PH_LOG_HELPER_ALLOCATE_PARAMNAME(pDataParams);*/ PH_LOG_HELPER_ALLOCATE_PARAMNAME(bCascadeLevel); PH_LOG_HELPER_ALLOCATE_PARAMNAME(pUidIn); PH_LOG_HELPER_ALLOCATE_PARAMNAME(bNvbUidIn); PH_LOG_HELPER_ALLOCATE_PARAMNAME(pUidOut); PH_LOG_HELPER_ALLOCATE_PARAMNAME(pNvbUidOut); PH_LOG_HELPER_ALLOCATE_PARAMNAME(status); PH_LOG_HELPER_ADDSTRING(PH_LOG_LOGTYPE_INFO, bFunctionName); PH_LOG_HELPER_ADDPARAM_UINT8(PH_LOG_LOGTYPE_DEBUG, bCascadeLevel_log, &bCascadeLevel); #ifdef NXPBUILD__PH_LOG bNvBUid = bNvbUidIn >> 4U; /* check for incomplete bytes */ if (0U != (bNvbUidIn & 0x07U)) { ++bNvBUid; } PH_LOG_HELPER_ADDPARAM_BUFFER(PH_LOG_LOGTYPE_DEBUG, pUidIn_log, pUidIn, bNvBUid); #endif PH_LOG_HELPER_ADDPARAM_UINT8(PH_LOG_LOGTYPE_DEBUG, bNvbUidIn_log, &bNvbUidIn); PH_LOG_HELPER_EXECUTE(PH_LOG_OPTION_CATEGORY_ENTER); PH_ASSERT_NULL (pDataParams); if (0U != (bNvbUidIn)) PH_ASSERT_NULL (pUidIn); PH_ASSERT_NULL (pUidOut); PH_ASSERT_NULL (pNvbUidOut); /* Check data parameters */ if (PH_GET_COMPCODE(pDataParams) != PH_COMP_PAL_ISO14443P3A) { status = PH_ADD_COMPCODE_FIXED(PH_ERR_INVALID_DATA_PARAMS, PH_COMP_PAL_ISO14443P3A); PH_LOG_HELPER_ADDSTRING(PH_LOG_LOGTYPE_INFO, bFunctionName); PH_LOG_HELPER_ADDPARAM_UINT16(PH_LOG_LOGTYPE_INFO, status_log, &status); PH_LOG_HELPER_EXECUTE(PH_LOG_OPTION_CATEGORY_LEAVE); return status; } /* perform operation on active layer */ switch (PH_GET_COMPID(pDataParams)) { #ifdef NXPBUILD__PHPAL_I14443P3A_SW case PHPAL_I14443P3A_SW_ID: status = phpalI14443p3a_Sw_Anticollision((phpalI14443p3a_Sw_DataParams_t *)pDataParams, bCascadeLevel, pUidIn, bNvbUidIn, pUidOut, pNvbUidOut); break; #endif /* NXPBUILD__PHPAL_I14443P3A_SW */ default: status = PH_ADD_COMPCODE_FIXED(PH_ERR_INVALID_DATA_PARAMS, PH_COMP_PAL_ISO14443P3A); break; } PH_LOG_HELPER_ADDSTRING(PH_LOG_LOGTYPE_INFO, bFunctionName); #ifdef NXPBUILD__PH_LOG if ((status & PH_ERR_MASK) == PH_ERR_SUCCESS) { bNvBUid = (*pNvbUidOut) >> 4U; /* check for incomplete bytes */ if ((*pNvbUidOut) & 0x07U) { ++bNvBUid; } PH_LOG_HELPER_ADDPARAM_BUFFER(PH_LOG_LOGTYPE_DEBUG, pUidOut_log, pUidOut, bNvBUid); } #endif PH_LOG_HELPER_ADDPARAM_UINT8(PH_LOG_LOGTYPE_DEBUG, pNvbUidOut_log, pNvbUidOut); PH_LOG_HELPER_ADDPARAM_UINT16(PH_LOG_LOGTYPE_INFO, status_log, &status); PH_LOG_HELPER_EXECUTE(PH_LOG_OPTION_CATEGORY_LEAVE); return status; } phStatus_t phpalI14443p3a_Select( void * pDataParams, uint8_t bCascadeLevel, uint8_t * pUidIn, uint8_t * pSak ) { phStatus_t PH_MEMLOC_REM status; PH_LOG_HELPER_ALLOCATE_TEXT(bFunctionName, "phpalI14443p3a_Select"); /*PH_LOG_HELPER_ALLOCATE_PARAMNAME(pDataParams);*/ PH_LOG_HELPER_ALLOCATE_PARAMNAME(bCascadeLevel); PH_LOG_HELPER_ALLOCATE_PARAMNAME(pUidIn); PH_LOG_HELPER_ALLOCATE_PARAMNAME(pSak); PH_LOG_HELPER_ALLOCATE_PARAMNAME(status); PH_LOG_HELPER_ADDSTRING(PH_LOG_LOGTYPE_INFO, bFunctionName); PH_LOG_HELPER_ADDPARAM_UINT8(PH_LOG_LOGTYPE_DEBUG, bCascadeLevel_log, &bCascadeLevel); PH_LOG_HELPER_ADDPARAM_BUFFER(PH_LOG_LOGTYPE_DEBUG, pUidIn_log, pUidIn, 4); PH_LOG_HELPER_EXECUTE(PH_LOG_OPTION_CATEGORY_ENTER); PH_ASSERT_NULL (pDataParams); PH_ASSERT_NULL (pUidIn); PH_ASSERT_NULL (pSak); /* Check data parameters */ if (PH_GET_COMPCODE(pDataParams) != PH_COMP_PAL_ISO14443P3A) { status = PH_ADD_COMPCODE_FIXED(PH_ERR_INVALID_DATA_PARAMS, PH_COMP_PAL_ISO14443P3A); PH_LOG_HELPER_ADDSTRING(PH_LOG_LOGTYPE_INFO, bFunctionName); PH_LOG_HELPER_ADDPARAM_UINT16(PH_LOG_LOGTYPE_INFO, status_log, &status); PH_LOG_HELPER_EXECUTE(PH_LOG_OPTION_CATEGORY_LEAVE); return status; } /* perform operation on active layer */ switch (PH_GET_COMPID(pDataParams)) { #ifdef NXPBUILD__PHPAL_I14443P3A_SW case PHPAL_I14443P3A_SW_ID: status = phpalI14443p3a_Sw_Select((phpalI14443p3a_Sw_DataParams_t *)pDataParams, bCascadeLevel, pUidIn, pSak); break; #endif /* NXPBUILD__PHPAL_I14443P3A_SW */ default: status = PH_ADD_COMPCODE_FIXED(PH_ERR_INVALID_DATA_PARAMS, PH_COMP_PAL_ISO14443P3A); break; } PH_LOG_HELPER_ADDSTRING(PH_LOG_LOGTYPE_INFO, bFunctionName); PH_LOG_HELPER_ADDPARAM_UINT8(PH_LOG_LOGTYPE_DEBUG, pSak_log, pSak); PH_LOG_HELPER_ADDPARAM_UINT16(PH_LOG_LOGTYPE_INFO, status_log, &status); PH_LOG_HELPER_EXECUTE(PH_LOG_OPTION_CATEGORY_LEAVE); return status; } phStatus_t phpalI14443p3a_ActivateCard( void * pDataParams, uint8_t * pUidIn, uint8_t bLenUidIn, uint8_t * pUidOut, uint8_t * pLenUidOut, uint8_t * pSak, uint8_t * pMoreCardsAvailable ) { phStatus_t PH_MEMLOC_REM status; PH_LOG_HELPER_ALLOCATE_TEXT(bFunctionName, "phpalI14443p3a_ActivateCard"); /*PH_LOG_HELPER_ALLOCATE_PARAMNAME(pDataParams);*/ PH_LOG_HELPER_ALLOCATE_PARAMNAME(pUidIn); PH_LOG_HELPER_ALLOCATE_PARAMNAME(pUidOut); PH_LOG_HELPER_ALLOCATE_PARAMNAME(pSak); PH_LOG_HELPER_ALLOCATE_PARAMNAME(pMoreCardsAvailable); PH_LOG_HELPER_ALLOCATE_PARAMNAME(status); PH_LOG_HELPER_ADDSTRING(PH_LOG_LOGTYPE_INFO, bFunctionName); PH_LOG_HELPER_ADDPARAM_BUFFER(PH_LOG_LOGTYPE_DEBUG, pUidIn_log, pUidIn, bLenUidIn); PH_LOG_HELPER_EXECUTE(PH_LOG_OPTION_CATEGORY_ENTER); PH_ASSERT_NULL (pDataParams); if (0U != (bLenUidIn)) PH_ASSERT_NULL (pUidIn); PH_ASSERT_NULL (pUidOut); PH_ASSERT_NULL (pLenUidOut); PH_ASSERT_NULL (pSak); PH_ASSERT_NULL (pMoreCardsAvailable); /* Check data parameters */ if (PH_GET_COMPCODE(pDataParams) != PH_COMP_PAL_ISO14443P3A) { status = PH_ADD_COMPCODE_FIXED(PH_ERR_INVALID_DATA_PARAMS, PH_COMP_PAL_ISO14443P3A); PH_LOG_HELPER_ADDSTRING(PH_LOG_LOGTYPE_INFO, bFunctionName); PH_LOG_HELPER_ADDPARAM_UINT16(PH_LOG_LOGTYPE_INFO, status_log, &status); PH_LOG_HELPER_EXECUTE(PH_LOG_OPTION_CATEGORY_LEAVE); return status; } /* perform operation on active layer */ switch (PH_GET_COMPID(pDataParams)) { #ifdef NXPBUILD__PHPAL_I14443P3A_SW case PHPAL_I14443P3A_SW_ID: status = phpalI14443p3a_Sw_ActivateCard((phpalI14443p3a_Sw_DataParams_t *)pDataParams, pUidIn, bLenUidIn, pUidOut, pLenUidOut, pSak, pMoreCardsAvailable); break; #endif /* NXPBUILD__PHPAL_I14443P3A_SW */ default: status = PH_ADD_COMPCODE_FIXED(PH_ERR_INVALID_DATA_PARAMS, PH_COMP_PAL_ISO14443P3A); break; } PH_LOG_HELPER_ADDSTRING(PH_LOG_LOGTYPE_INFO, bFunctionName); #ifdef NXPBUILD__PH_LOG if ((status & PH_ERR_MASK) == PH_ERR_SUCCESS) { PH_LOG_HELPER_ADDPARAM_BUFFER(PH_LOG_LOGTYPE_DEBUG, pUidOut_log, pUidOut, *pLenUidOut); } #endif PH_LOG_HELPER_ADDPARAM_UINT8(PH_LOG_LOGTYPE_DEBUG, pSak_log, pSak); PH_LOG_HELPER_ADDPARAM_UINT8(PH_LOG_LOGTYPE_DEBUG, pMoreCardsAvailable_log, pMoreCardsAvailable); PH_LOG_HELPER_ADDPARAM_UINT16(PH_LOG_LOGTYPE_INFO, status_log, &status); PH_LOG_HELPER_EXECUTE(PH_LOG_OPTION_CATEGORY_LEAVE); return status; } phStatus_t phpalI14443p3a_Exchange( void * pDataParams, uint16_t wOption, uint8_t * pTxBuffer, uint16_t wTxLength, uint8_t ** ppRxBuffer, uint16_t * pRxLength ) { phStatus_t PH_MEMLOC_REM status; PH_LOG_HELPER_ALLOCATE_TEXT(bFunctionName, "phpalI14443p3a_Exchange"); /*PH_LOG_HELPER_ALLOCATE_PARAMNAME(pDataParams);*/ PH_LOG_HELPER_ALLOCATE_PARAMNAME(wOption); PH_LOG_HELPER_ALLOCATE_PARAMNAME(pTxBuffer); PH_LOG_HELPER_ALLOCATE_PARAMNAME(ppRxBuffer); PH_LOG_HELPER_ALLOCATE_PARAMNAME(status); PH_LOG_HELPER_ADDSTRING(PH_LOG_LOGTYPE_INFO, bFunctionName); PH_LOG_HELPER_ADDPARAM_UINT16(PH_LOG_LOGTYPE_DEBUG, wOption_log, &wOption); PH_LOG_HELPER_ADDPARAM_BUFFER(PH_LOG_LOGTYPE_DEBUG, pTxBuffer_log, pTxBuffer, wTxLength); PH_LOG_HELPER_EXECUTE(PH_LOG_OPTION_CATEGORY_ENTER); PH_ASSERT_NULL (pDataParams); if (0U != (wTxLength)) PH_ASSERT_NULL (pTxBuffer); /* Check data parameters */ if (PH_GET_COMPCODE(pDataParams) != PH_COMP_PAL_ISO14443P3A) { status = PH_ADD_COMPCODE_FIXED(PH_ERR_INVALID_DATA_PARAMS, PH_COMP_PAL_ISO14443P3A); PH_LOG_HELPER_ADDSTRING(PH_LOG_LOGTYPE_INFO, bFunctionName); PH_LOG_HELPER_ADDPARAM_UINT16(PH_LOG_LOGTYPE_INFO, status_log, &status); PH_LOG_HELPER_EXECUTE(PH_LOG_OPTION_CATEGORY_LEAVE); return status; } /* perform operation on active layer */ switch (PH_GET_COMPID(pDataParams)) { #ifdef NXPBUILD__PHPAL_I14443P3A_SW case PHPAL_I14443P3A_SW_ID: status = phpalI14443p3a_Sw_Exchange((phpalI14443p3a_Sw_DataParams_t *)pDataParams, wOption, pTxBuffer, wTxLength, ppRxBuffer, pRxLength); break; #endif /* NXPBUILD__PHPAL_I14443P3A_SW */ default: status = PH_ADD_COMPCODE_FIXED(PH_ERR_INVALID_DATA_PARAMS, PH_COMP_PAL_ISO14443P3A); break; } PH_LOG_HELPER_ADDSTRING(PH_LOG_LOGTYPE_INFO, bFunctionName); #ifdef NXPBUILD__PH_LOG if ((((status & PH_ERR_MASK) == PH_ERR_SUCCESS) || ((status & PH_ERR_MASK) == PH_ERR_SUCCESS_CHAINING) || ((status & PH_ERR_MASK) == PH_ERR_SUCCESS_INCOMPLETE_BYTE)) && (0U == ((wOption & PH_EXCHANGE_BUFFERED_BIT))) && (ppRxBuffer != NULL)) { PH_LOG_HELPER_ADDPARAM_BUFFER(PH_LOG_LOGTYPE_DEBUG, ppRxBuffer_log, *ppRxBuffer, *pRxLength); } #endif PH_LOG_HELPER_ADDPARAM_UINT16(PH_LOG_LOGTYPE_INFO, status_log, &status); PH_LOG_HELPER_EXECUTE(PH_LOG_OPTION_CATEGORY_LEAVE); return status; } phStatus_t phpalI14443p3a_GetSerialNo( void * pDataParams, uint8_t * pUidOut, uint8_t * pLenUidOut ) { phStatus_t PH_MEMLOC_REM status; PH_LOG_HELPER_ALLOCATE_TEXT(bFunctionName, "phpalI14443p3a_GetSerialNo"); /*PH_LOG_HELPER_ALLOCATE_PARAMNAME(pDataParams);*/ PH_LOG_HELPER_ALLOCATE_PARAMNAME(pUidOut); PH_LOG_HELPER_ALLOCATE_PARAMNAME(status); PH_LOG_HELPER_ADDSTRING(PH_LOG_LOGTYPE_INFO, bFunctionName); PH_LOG_HELPER_EXECUTE(PH_LOG_OPTION_CATEGORY_ENTER); PH_ASSERT_NULL (pDataParams); PH_ASSERT_NULL (pUidOut); PH_ASSERT_NULL (pLenUidOut); /* Check data parameters */ if (PH_GET_COMPCODE(pDataParams) != PH_COMP_PAL_ISO14443P3A) { status = PH_ADD_COMPCODE_FIXED(PH_ERR_INVALID_DATA_PARAMS, PH_COMP_PAL_ISO14443P3A); PH_LOG_HELPER_ADDSTRING(PH_LOG_LOGTYPE_INFO, bFunctionName); PH_LOG_HELPER_ADDPARAM_UINT16(PH_LOG_LOGTYPE_INFO, status_log, &status); PH_LOG_HELPER_EXECUTE(PH_LOG_OPTION_CATEGORY_LEAVE); return status; } /* perform operation on active layer */ switch (PH_GET_COMPID(pDataParams)) { #ifdef NXPBUILD__PHPAL_I14443P3A_SW case PHPAL_I14443P3A_SW_ID: status = phpalI14443p3a_Sw_GetSerialNo((phpalI14443p3a_Sw_DataParams_t *)pDataParams, pUidOut, pLenUidOut); break; #endif /* NXPBUILD__PHPAL_I14443P3A_SW */ default: status = PH_ADD_COMPCODE_FIXED(PH_ERR_INVALID_DATA_PARAMS, PH_COMP_PAL_ISO14443P3A); break; } PH_LOG_HELPER_ADDSTRING(PH_LOG_LOGTYPE_INFO, bFunctionName); #ifdef NXPBUILD__PH_LOG if ((status & PH_ERR_MASK) == PH_ERR_SUCCESS) { PH_LOG_HELPER_ADDPARAM_BUFFER(PH_LOG_LOGTYPE_DEBUG, pUidOut_log, pUidOut, *pLenUidOut); } #endif PH_LOG_HELPER_ADDPARAM_UINT16(PH_LOG_LOGTYPE_INFO, status_log, &status); PH_LOG_HELPER_EXECUTE(PH_LOG_OPTION_CATEGORY_LEAVE); return status; } #endif /* NXPRDLIB_REM_GEN_INTFS */ #endif /* NXPBUILD__PHPAL_I14443P3A */
34.91047
162
0.703208
390e812ed463dddffcda9add64243feb47116dd6
941
h
C
GLOParallaxTabbedProfileViewController/GLOParallaxTabbedPager.h
gotte/GLOParallaxTabbedProfileViewController
61587a29e3951bf7843a69e534e382dc57f5ff25
[ "MIT" ]
null
null
null
GLOParallaxTabbedProfileViewController/GLOParallaxTabbedPager.h
gotte/GLOParallaxTabbedProfileViewController
61587a29e3951bf7843a69e534e382dc57f5ff25
[ "MIT" ]
null
null
null
GLOParallaxTabbedProfileViewController/GLOParallaxTabbedPager.h
gotte/GLOParallaxTabbedProfileViewController
61587a29e3951bf7843a69e534e382dc57f5ff25
[ "MIT" ]
null
null
null
// // GLOParallaxTabbedPager.h // GLOParallaxTabbedProfileViewController // // Created by Gabriel Otte on 8/15/15. // Copyright (c) 2015 Gabriel Otte. All rights reserved. // #import <UIKit/UIKit.h> @class GLOParallaxTabbedPager; @protocol GLOParallaxTabbedPagerDelegate <NSObject> @optional - (void)tabbedPager:(GLOParallaxTabbedPager *)tabbedPager didSelectView:(UIView *)view; @end @protocol GLOParallaxTabbedPagerDataSource <NSObject> @required - (NSInteger)numberOfPagesInTabbedPager:(GLOParallaxTabbedPager *)tabbedPager; - (UIView *)tabbedPager:(GLOParallaxTabbedPager *)tabbedPager viewForTabAtIndex:(NSInteger)index; - (NSString *)tabbedPager:(GLOParallaxTabbedPager *)tabbedPager titleForTabAtIndex:(NSInteger)index; @end @interface GLOParallaxTabbedPager : UIView @property (nonatomic) id<GLOParallaxTabbedPagerDelegate> delegate; @property (nonatomic) id<GLOParallaxTabbedPagerDataSource> dataSource; @end
21.883721
100
0.79915
799ba22b1b29ba2e361cfe5d58a69c4c149649f8
491
h
C
UIKit/_UIHostedWindowHostingHandle.h
LacertosusRepo/headers
f3eef2127548c631b325a0b28c907cc59b1716ac
[ "Unlicense", "Apache-2.0", "OpenSSL", "BSD-3-Clause" ]
182
2016-03-28T00:30:04.000Z
2022-03-31T02:04:58.000Z
UIKit/_UIHostedWindowHostingHandle.h
LacertosusRepo/headers
f3eef2127548c631b325a0b28c907cc59b1716ac
[ "Unlicense", "Apache-2.0", "OpenSSL", "BSD-3-Clause" ]
36
2016-05-09T09:45:41.000Z
2022-03-06T04:02:42.000Z
UIKit/_UIHostedWindowHostingHandle.h
LacertosusRepo/headers
f3eef2127548c631b325a0b28c907cc59b1716ac
[ "Unlicense", "Apache-2.0", "OpenSSL", "BSD-3-Clause" ]
69
2016-04-16T19:48:18.000Z
2022-02-28T09:05:05.000Z
#import <Foundation/Foundation.h> API_AVAILABLE(ios(7.0)) @interface _UIHostedWindowHostingHandle : NSObject <NSSecureCoding> @property (readonly, nonatomic) unsigned int contextID; @property (readonly, nonatomic) CGAffineTransform rootLayerTransform; @property (readonly, nonatomic) CGRect rootLayerFrame; + (instancetype)hostedWindowHostingHandleWithContextID:(unsigned int)contextID rootLayerTransform:(CGAffineTransform)rootLayerTransform rootLayerFrame:(CGRect)rootLayerFrame; @end
37.769231
174
0.843177
06739e647664c420c2a613dfae658a2f4caafab3
765
h
C
include/trick/variable_server_proto.h
TheCivilAge/RogueKitten
0b9fbe17624e77752f6160463c6d8aa5a781aad1
[ "NASA-1.3" ]
null
null
null
include/trick/variable_server_proto.h
TheCivilAge/RogueKitten
0b9fbe17624e77752f6160463c6d8aa5a781aad1
[ "NASA-1.3" ]
null
null
null
include/trick/variable_server_proto.h
TheCivilAge/RogueKitten
0b9fbe17624e77752f6160463c6d8aa5a781aad1
[ "NASA-1.3" ]
3
2021-06-22T11:02:39.000Z
2021-10-21T00:58:00.000Z
#ifndef VARIABLE_SERVER_PROTO_H #define VARIABLE_SERVER_PROTO_H #ifdef __cplusplus extern "C" { #endif const char * var_server_get_hostname() ; unsigned short var_server_get_port() ; void var_server_set_port(unsigned short port) ; void var_server_set_source_address(const char * address) ; const char * var_server_get_user_tag() ; void var_server_set_user_tag(const char * tag) ; int var_server_get_enabled() ; void var_server_set_enabled(int on_off) ; int var_server_create_tcp_socket(const char * address, unsigned short port) ; int var_server_create_udp_socket(const char * address, unsigned short port) ; int var_server_create_multicast_socket(const char * mcast_address, const char * address, unsigned short port) ; #ifdef __cplusplus } #endif #endif
25.5
111
0.805229
c2077f883090a8e50fe7874406d5181d47e92bfe
1,011
h
C
src/mame/includes/warpwarp.h
Zoltan45/Mame-mkp119
d219a3549eafb4215727c974e09e43b28d058328
[ "CC0-1.0" ]
null
null
null
src/mame/includes/warpwarp.h
Zoltan45/Mame-mkp119
d219a3549eafb4215727c974e09e43b28d058328
[ "CC0-1.0" ]
null
null
null
src/mame/includes/warpwarp.h
Zoltan45/Mame-mkp119
d219a3549eafb4215727c974e09e43b28d058328
[ "CC0-1.0" ]
null
null
null
#include "sound/custom.h" /*----------- defined in video/warpwarp.c -----------*/ extern UINT8 *geebee_videoram,*warpwarp_videoram; extern int geebee_bgw; extern int warpwarp_ball_on; extern int warpwarp_ball_h, warpwarp_ball_v; extern int warpwarp_ball_sizex, warpwarp_ball_sizey; extern int geebee_handleoverlay; PALETTE_INIT( geebee ); PALETTE_INIT( navarone ); PALETTE_INIT( warpwarp ); VIDEO_START( geebee ); VIDEO_START( navarone ); VIDEO_START( warpwarp ); VIDEO_UPDATE( geebee ); VIDEO_UPDATE( warpwarp ); WRITE8_HANDLER( warpwarp_videoram_w ); WRITE8_HANDLER( geebee_videoram_w ); /*----------- defined in audio/geebee.c -----------*/ WRITE8_HANDLER( geebee_sound_w ); void *geebee_sh_start(int clock, const struct CustomSound_interface *config); /*----------- defined in audio/warpwarp.c -----------*/ WRITE8_HANDLER( warpwarp_sound_w ); WRITE8_HANDLER( warpwarp_music1_w ); WRITE8_HANDLER( warpwarp_music2_w ); void *warpwarp_sh_start(int clock, const struct CustomSound_interface *config);
28.083333
79
0.746785
05c5122a643764ec12f51e387cdfc15bf370e926
1,202
h
C
modules/sre.h
weimingtom/python222mod
89ecf277352d72500a158ee3e7fb29e061d1f7df
[ "PSF-2.0" ]
null
null
null
modules/sre.h
weimingtom/python222mod
89ecf277352d72500a158ee3e7fb29e061d1f7df
[ "PSF-2.0" ]
null
null
null
modules/sre.h
weimingtom/python222mod
89ecf277352d72500a158ee3e7fb29e061d1f7df
[ "PSF-2.0" ]
null
null
null
//20180406 #pragma once #include "sre_constants.h" #define SRE_CODE unsigned short typedef struct { PyObject_VAR_HEAD int groups; PyObject* groupindex; PyObject* indexgroup; PyObject* pattern; int flags; int codesize; SRE_CODE code[1]; } PatternObject; #define PatternObject_GetCode(o) (((PatternObject*)(o))->code) typedef struct { PyObject_VAR_HEAD PyObject* string; PyObject* regs; PatternObject* pattern; int pos, endpos; int lastindex; int groups; int mark[1]; } MatchObject; typedef unsigned int (*SRE_TOLOWER_HOOK)(unsigned int ch); #define SRE_MARK_SIZE 200 typedef struct SRE_REPEAT_T { int count; SRE_CODE* pattern; struct SRE_REPEAT_T *prev; } SRE_REPEAT; typedef struct { void* ptr; void* beginning; void* start; void* end; PyObject* string; int pos, endpos; int charsize; int lastindex; int lastmark; void* mark[SRE_MARK_SIZE]; void** mark_stack; int mark_stack_size; int mark_stack_base; SRE_REPEAT *repeat; SRE_TOLOWER_HOOK lower; } SRE_STATE; typedef struct { PyObject_HEAD PyObject* pattern; SRE_STATE state; } ScannerObject;
18.492308
62
0.680532
399faf24ae72a32ca402d27e507e5055cfc9c751
996
c
C
test/seed-generation/all_arrs.c
michael-emmi/ct-fuzz
a6a1ec26501ba23ce059794abc94fb8c8af33aee
[ "MIT" ]
7
2019-04-18T00:08:49.000Z
2022-02-21T08:03:43.000Z
test/seed-generation/all_arrs.c
michael-emmi/ct-fuzz
a6a1ec26501ba23ce059794abc94fb8c8af33aee
[ "MIT" ]
null
null
null
test/seed-generation/all_arrs.c
michael-emmi/ct-fuzz
a6a1ec26501ba23ce059794abc94fb8c8af33aee
[ "MIT" ]
null
null
null
// RUN: ct-fuzz %s --entry-point=foo -o %t --seed-file %t1 // RUN: seq 2 | xargs -i -- cat %t1 | xargs -0 echo -n -e | tr -d '\n' | %t > %t2 // RUN: diff %t2 %s.output #include <stdio.h> #include "ct-fuzz.h" #define INT_LEN 2 #define SHORT_LEN 4 #define CHAR_LEN 8 void foo(int* a, short* b, char* c) { a[0] = 1; } CT_FUZZ_SPEC(void, foo, int* a, short* b, char* c) { __ct_fuzz_ptr_len(a, INT_LEN, INT_LEN); __ct_fuzz_ptr_len(b, SHORT_LEN, SHORT_LEN); __ct_fuzz_ptr_len(c, CHAR_LEN, CHAR_LEN); for (unsigned short i = 0; i < INT_LEN; ++i) printf("%d,", a[i]); printf("\n"); for (unsigned short i = 0; i < SHORT_LEN; ++i) printf("%d,", b[i]); printf("\n"); for (unsigned short i = 0; i < CHAR_LEN; ++i) printf("%d,", c[i]); printf("\n"); } CT_FUZZ_SEED(void, foo, int*, short*, char*) { SEED_1D_ARR(int, a, INT_LEN, {1, 1}) SEED_1D_ARR(short, b, SHORT_LEN, {2, 2, 2, 2}) SEED_1D_ARR(char, c, CHAR_LEN, {3, 3, 3, 3, 3, 3, 3, 3}) PRODUCE(foo, a, b, c); }
27.666667
81
0.585341
586831a44b573637136eb48f8dd942829174f3b5
820
h
C
net/rras/netsh/ip/preview/msdp.h
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
net/rras/netsh/ip/preview/msdp.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
net/rras/netsh/ip/preview/msdp.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1999, Microsoft Corporation Module Name: net\routing\netsh\ip\protocols\msdphlp.h Abstract: MSDP Command dispatcher declarations Author: Peeyush Ranjan (peeyushr) 1-Mar-1999 Revision History: --*/ #ifndef _NETSH_MSDPHLP_H_ #define _NETSH_MSDPHLP_H_ extern CMD_ENTRY g_MsdpAddCmdTable[]; extern CMD_ENTRY g_MsdpDelCmdTable[]; extern CMD_ENTRY g_MsdpSetCmdTable[]; extern CMD_ENTRY g_MsdpShowCmdTable[]; extern CMD_GROUP_ENTRY g_MsdpCmdGroupTable[]; extern ULONG g_MsdpCmdGroupCount; extern CMD_ENTRY g_MsdpTopCmdTable[]; extern ULONG g_MsdpTopCmdCount; NS_CONTEXT_DUMP_FN MsdpDump; extern VALUE_STRING MsdpEncapsStringArray[]; extern VALUE_TOKEN MsdpEncapsTokenArray[]; #define MSDP_ENCAPS_SIZE 1 #endif // _NETSH_MSDPHLP_H_
18.636364
46
0.757317
bad51c7553ff838c47262b32959d5e3dfc77a66c
1,549
h
C
component/oai-amf/src/sbi/amf_server/model/Arp.h
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
component/oai-amf/src/sbi/amf_server/model/Arp.h
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
component/oai-amf/src/sbi/amf_server/model/Arp.h
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
/** * Namf_Communication * AMF Communication Service © 2019, 3GPP Organizational Partners (ARIB, ATIS, * CCSA, ETSI, TSDSI, TTA, TTC). All rights reserved. * * The version of the OpenAPI document: 1.1.0.alpha-1 * * * NOTE: This class is auto generated by OpenAPI Generator * (https://openapi-generator.tech). https://openapi-generator.tech Do not edit * the class manually. */ /* * Arp.h * * */ #ifndef Arp_H_ #define Arp_H_ #include "PreemptionCapability.h" #include "PreemptionVulnerability.h" #include <nlohmann/json.hpp> namespace oai { namespace amf { namespace model { /// <summary> /// /// </summary> class Arp { public: Arp(); virtual ~Arp(); void validate(); ///////////////////////////////////////////// /// Arp members /// <summary> /// nullable true shall not be used for this attribute /// </summary> int32_t getPriorityLevel() const; void setPriorityLevel(int32_t const value); /// <summary> /// /// </summary> PreemptionCapability getPreemptCap() const; void setPreemptCap(PreemptionCapability const& value); /// <summary> /// /// </summary> PreemptionVulnerability getPreemptVuln() const; void setPreemptVuln(PreemptionVulnerability const& value); friend void to_json(nlohmann::json& j, const Arp& o); friend void from_json(const nlohmann::json& j, Arp& o); protected: int32_t m_PriorityLevel; PreemptionCapability m_PreemptCap; PreemptionVulnerability m_PreemptVuln; }; } // namespace model } // namespace amf } // namespace oai #endif /* Arp_H_ */
20.653333
79
0.671401
c97d200114e59e223b43a116e39c14b852af14c7
5,162
h
C
linux-3.4/sound/soc/sunxi/audiocodec/switch_hdset.h
xregist/v3s-linux-sdk
a2b013e3959662d65650a13fc23ec1cd503865eb
[ "Apache-2.0" ]
null
null
null
linux-3.4/sound/soc/sunxi/audiocodec/switch_hdset.h
xregist/v3s-linux-sdk
a2b013e3959662d65650a13fc23ec1cd503865eb
[ "Apache-2.0" ]
null
null
null
linux-3.4/sound/soc/sunxi/audiocodec/switch_hdset.h
xregist/v3s-linux-sdk
a2b013e3959662d65650a13fc23ec1cd503865eb
[ "Apache-2.0" ]
1
2020-01-31T10:27:07.000Z
2020-01-31T10:27:07.000Z
/* * sound\soc\sunxi\audiocodec\switch_hdset.h * (C) Copyright 2010-2016 * Reuuimlla Technology Co., Ltd. <www.reuuimllatech.com> * huangxin <huangxin@reuuimllatech.com> * * some simple description for this code * * 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. * */ #ifndef _SWITCH_HEADSET_H #define _SWITCH_HEADSET_H #include <mach/platform.h> /*Codec Register*/ #define baseaddr SUNXI_AUDIO_VBASE #ifdef CONFIG_ARCH_SUN8IW5 #define ADDA_PR_CFG_REG (SUNXI_R_PRCM_VBASE+0x1c0) #define VIR_HMIC_BASSADDRESS (SUNXI_R_PRCM_VBASE) #define SUNXI_HMIC_ENABLE (0x1c4) #define SUNXI_HMIC_CTL (0x1c8) #define SUNXI_HMIC_DATA (0x1cc) #else/*CONFIG_ARCH_SUN8IW8*/ #define ADDA_PR_CFG_REG (SUNXI_AUDIO_VBASE+0x400) #define VIR_HMIC_BASSADDRESS (SUNXI_AUDIO_VBASE) //#define SUNXI_HMIC_ENABLE (0x1c4) #define SUNXI_HMIC_CTL (0x50) #define SUNXI_HMIC_DATA (0x54) #endif #define HP_VOLC (0x00) #define LOMIXSC (0x01) #define ROMIXSC (0x02) #define DAC_PA_SRC (0x03) #define PAEN_HP_CTRL (0x07) #define ADDA_APT2 (0x12) #define MIC1G_MICBIAS_CTRL (0x0B) #define PA_ANTI_POP_REG_CTRL (0x0E) /* * apb0 base * 0x00 HP_VOLC */ #define PA_CLK_GC (7) #define HPVOL (0) /* * apb0 base * 0x01 LOMIXSC */ #define LMIXMUTE (0) /* * apb0 base * 0x02 ROMIXSC */ #define RMIXMUTE (0) /* * apb0 base * 0x03 DAC_PA_SRC */ #define RMIXEN (5) #define LMIXEN (4) /* * apb0 base * 0x07 PAEN_HP_CTRL */ #define HPPAEN (7) #define HPCOM_FC (5) #define PA_ANTI_POP_CTRL (2) /* * apb0 base * 0x0B MIC1G_MICBIAS_CTRL */ #define HMICBIASEN (7) #ifdef CONFIG_ARCH_SUN8IW5 #define HMICBIAS_MODE (5) #else/*CONFIG_ARCH_SUN8IW8*/ #define HMICADCEN (5) #endif /*0xE*/ #define PA_ANTI_POP_EN (0) /* * apb0 base * 0x12 ADDA_APT2 */ #define PA_SLOPE_SELECT (3) /* *SUNXI_HMIC_ENABLE *HMIC DIG Enable *CONFIG_ARCH_SUN8IW5:0x1c4 */ #define HMIC_DIG_EN (0) /* * SUNXI_HMIC_CTL *HMIC Control Register *CONFIG_ARCH_SUN8IW5:0x1c8 */ #define HMIC_M (28) #define HMIC_N (24) #define HMIC_DIRQ (23) #define HMIC_TH1_HYS (21) #define HMIC_EARPHONE_OUT_IRQ_EN (20) #define HMIC_EARPHONE_IN_IRQ_EN (19) #define HMIC_KEY_UP_IRQ_EN (18) #define HMIC_KEY_DOWN_IRQ_EN (17) #define HMIC_DATA_IRQ_EN (16) #define HMIC_DS_SAMP (14) #define HMIC_TH2_HYS (13) #define HMIC_TH2_KEY (8) #define HMIC_SF_SMOOTH_FIL (6) #define KEY_UP_IRQ_PEND (5) #define HMIC_TH1_EARPHONE (0) /* * SUNXI_HMIC_DATA *HMIC Data Register * *CONFIG_ARCH_SUN8IW5:0x1cc */ #define HMIC_EARPHONE_OUT_IRQ_PEND (20) #define HMIC_EARPHONE_IN_IRQ_PEND (19) #define HMIC_KEY_UP_IRQ_PEND (18) #define HMIC_KEY_DOWN_IRQ_PEND (17) #define HMIC_DATA_IRQ_PEND (16) #define HMIC_ADC_DATA (0) //#define FUNCTION_NAME "h2w" #define hmic_rdreg(reg) readl((VIR_HMIC_BASSADDRESS+(reg))) #define hmic_wrreg(reg,val) writel((val),(VIR_HMIC_BASSADDRESS+(reg))) static unsigned int read_prcm_wvalue(unsigned int addr) { unsigned int reg; reg = readl(ADDA_PR_CFG_REG); reg |= (0x1<<28); writel(reg, ADDA_PR_CFG_REG); reg = readl(ADDA_PR_CFG_REG); reg &= ~(0x1<<24); writel(reg, ADDA_PR_CFG_REG); reg = readl(ADDA_PR_CFG_REG); reg &= ~(0x1f<<16); reg |= (addr<<16); writel(reg, ADDA_PR_CFG_REG); reg = readl(ADDA_PR_CFG_REG); reg &= (0xff<<0); return reg; } static void write_prcm_wvalue(unsigned int addr, unsigned int val) { unsigned int reg; reg = readl(ADDA_PR_CFG_REG); reg |= (0x1<<28); writel(reg, ADDA_PR_CFG_REG); reg = readl(ADDA_PR_CFG_REG); reg &= ~(0x1f<<16); reg |= (addr<<16); writel(reg, ADDA_PR_CFG_REG); reg = readl(ADDA_PR_CFG_REG); reg &= ~(0xff<<8); reg |= (val<<8); writel(reg, ADDA_PR_CFG_REG); reg = readl(ADDA_PR_CFG_REG); reg |= (0x1<<24); writel(reg, ADDA_PR_CFG_REG); reg = readl(ADDA_PR_CFG_REG); reg &= ~(0x1<<24); writel(reg, ADDA_PR_CFG_REG); } /** * codec_wrreg_bits - update codec register bits * @reg: codec register * @mask: register mask * @value: new value * * Writes new register value. * Return 1 for change else 0. */ static int hmic_wrreg_prcm_bits(unsigned short reg, unsigned int mask, unsigned int value) { unsigned int old, new; old = read_prcm_wvalue(reg); new = (old & ~mask) | value; write_prcm_wvalue(reg,new); return 0; } static int hmic_wr_prcm_control(u32 reg, u32 mask, u32 shift, u32 val) { u32 reg_val; reg_val = val << shift; mask = mask << shift; hmic_wrreg_prcm_bits(reg, mask, reg_val); return 0; } static int hmic_wrreg_bits(unsigned short reg, unsigned int mask, unsigned int value) { unsigned int old, new; old = hmic_rdreg(reg); new = (old & ~mask) | value; hmic_wrreg(reg,new); return 0; } static int hmic_wr_control(u32 reg, u32 mask, u32 shift, u32 val) { u32 reg_val; reg_val = val << shift; mask = mask << shift; hmic_wrreg_bits(reg, mask, reg_val); return 0; } #endif
21.069388
90
0.697792
b5dd1f0a73560f684f48d4053c9e048401d0a507
395
h
C
src/stdafx.h
lintest/GitFor1C
ee4b45cf09caa3ce610302def92ef2beeb9439af
[ "BSD-3-Clause" ]
16
2020-07-13T17:29:49.000Z
2021-07-02T19:14:38.000Z
src/stdafx.h
BDDSM/GraphViz1C
dd30c2cf3ca89b36ac3dc88855accd53cc05974a
[ "BSD-3-Clause" ]
3
2020-08-21T05:52:20.000Z
2020-10-09T23:48:43.000Z
src/stdafx.h
lintest/GitFor1C
ee4b45cf09caa3ce610302def92ef2beeb9439af
[ "BSD-3-Clause" ]
2
2020-08-13T09:21:23.000Z
2020-08-13T15:30:58.000Z
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #ifndef __STDAFX_H__ #define __STDAFX_H__ #ifdef _WINDOWS #include <windows.h> #endif //_WINDOWS #include <string> std::wstring MB2WC(const std::string& source); std::string WC2MB(const std::wstring& source); #endif //__STDAFX_H__
21.944444
66
0.756962
57cc58f87e480e18c5c13b5c1203215c9be44819
2,577
h
C
PBFrameworkUIStreamDetails.framework/Headers/ContactViewController.h
PBMain/PBUIStreamDetails
34171815999561cca13ba36fc320fa4266c7a5d3
[ "MIT" ]
null
null
null
PBFrameworkUIStreamDetails.framework/Headers/ContactViewController.h
PBMain/PBUIStreamDetails
34171815999561cca13ba36fc320fa4266c7a5d3
[ "MIT" ]
null
null
null
PBFrameworkUIStreamDetails.framework/Headers/ContactViewController.h
PBMain/PBUIStreamDetails
34171815999561cca13ba36fc320fa4266c7a5d3
[ "MIT" ]
null
null
null
// // ContactViewController.h // PhotoButler // // Created by Mirant Patel on 11/08/16. // Copyright © 2016 Photo Butler. All rights reserved. // #import <UIKit/UIKit.h> #import "CollaborateStream.h" @class LoadingView; @interface NSString (emailValidation) -(BOOL)isValidEmail; @end @protocol ContactViewControllerDelegate <NSObject> - (void)setHeightByCount:(NSMutableArray *)arraySelected isEmail:(BOOL)isEmail; - (void)setHeightByCount:(NSMutableArray *)arraySelected; @end @interface ContactViewController : UIViewController<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UICollectionViewDelegate,UICollectionViewDataSource,CollaborateStreamDelegate>{ IBOutlet UIButton *btnForAddContact; IBOutlet UILabel *lblEmailSearchInst1; IBOutlet UIView *viewForSelectedName; } @property (nonatomic) LoadingView *loadingView; @property (nonatomic) NSTimer *loadingTimer; @property (nonatomic) BOOL hasPermission; @property (nonatomic) IBOutlet UIView *loadingViewContainer; @property (strong, nonatomic) NSMutableDictionary *hashContact; @property (nonatomic, weak) id <ContactViewControllerDelegate> delegate; @property (strong, nonatomic) IBOutlet UITableView *tblContact; @property (strong, nonatomic) IBOutlet UICollectionView *colvContactSelected; @property (strong, nonatomic) IBOutlet UILabel *lblFrequentlySharedWith; @property (strong, nonatomic) IBOutlet NSMutableArray *arrayFrequentlyDisplayed; @property (strong, nonatomic) IBOutlet NSMutableArray *arrayWhitelistPhones; @property (nonatomic) BOOL lastNewStream; @property (nonatomic) BOOL isEmail; @property (nonatomic) BOOL isNotPhone; @property (nonatomic) BOOL isNotEmail; @property (nonatomic) int keyboardSpace; @property (nonatomic) NSString *albumId; @property (strong, nonatomic) IBOutlet UILabel *lblTitleMain; @property (strong, nonatomic) IBOutlet UILabel *lblForNotFoundInst; @property (strong, nonatomic) IBOutlet UIButton *btnShare; @property (strong, nonatomic) IBOutlet UIButton *btnBack; @property (weak, nonatomic) IBOutlet UIView *viewNavigationBar; @property (weak, nonatomic) IBOutlet UIView *viewSafeArea; @property (weak, nonatomic) IBOutlet UIView *viewForStartTyping; @property (weak, nonatomic) IBOutlet UIView *viewForContactAccess; @property (weak, nonatomic) IBOutlet UIView *viewForCollectionView; @property (weak, nonatomic) IBOutlet UITextField *txtForSearch; @property (weak, nonatomic) IBOutlet UIImageView *imgForSearch; @property (weak, nonatomic) IBOutlet UIImageView *imgForMainImageSearch; -(IBAction)pressCancel:(id)sender; @end
35.791667
193
0.807528
84ae2443661f6891df5696d3a7779eea5a8d4b21
1,292
h
C
src/colorer/unicode/BitArray.h
elfmz/Colorer-library
b1ddc95064a030bfc583eea1a7f70c9cdc1a9e30
[ "MIT" ]
null
null
null
src/colorer/unicode/BitArray.h
elfmz/Colorer-library
b1ddc95064a030bfc583eea1a7f70c9cdc1a9e30
[ "MIT" ]
null
null
null
src/colorer/unicode/BitArray.h
elfmz/Colorer-library
b1ddc95064a030bfc583eea1a7f70c9cdc1a9e30
[ "MIT" ]
null
null
null
#ifndef _COLORER_BITARRAY_H_ #define _COLORER_BITARRAY_H_ #include <colorer/Common.h> /** Bit Array field. Creates and manages bit array objects. @ingroup unicode */ class BitArray { public: /** Creates bit array with specified number of stored bitfields. */ BitArray(int size = 256); ~BitArray(); /** Sets bit at position @c pos */ void setBit(int pos); /** Clears bit at position @c pos */ void clearBit(int pos); /** Sets bit range */ void addRange(int s, int e); /** Clears bit range */ void clearRange(int s, int e); /** Sets bits to 1, whose corresponding values in passed bit array are also 1 (bitwize OR) */ void addBitArray(BitArray*); /** Sets bits to 0, whose corresponding values in passed bit array are also 1 */ void clearBitArray(BitArray*); /** Makes intersection of current and the passed bit array (bitwize AND) */ void intersectBitArray(BitArray*); /** Adds bit array from the passed byte stream. */ void addBitArray(char*, int); /** Clears bit array from the passed byte stream. */ void clearBitArray(char*, int); /** Returns bit value at position @c pos. */ bool getBit(int pos); #define CNAME "BitArray" private: int* array; int size; void createArray(bool set = false); }; #endif
23.925926
66
0.673375
b99e8b54fc579cc4d6572819128672ec4b964bba
3,441
h
C
include/genFFT/FFTUtil.h
mzient/genFFT
93e778ba6c16b989fe0eb3150e1e56fcac6f665c
[ "BSD-2-Clause" ]
3
2019-10-30T11:17:32.000Z
2019-11-04T16:38:37.000Z
include/genFFT/FFTUtil.h
mzient/genFFT
93e778ba6c16b989fe0eb3150e1e56fcac6f665c
[ "BSD-2-Clause" ]
null
null
null
include/genFFT/FFTUtil.h
mzient/genFFT
93e778ba6c16b989fe0eb3150e1e56fcac6f665c
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (C) 2017 Michal Zientkiewicz All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 GEN_FFT_UTIL_H #define GEN_FFT_UTIL_H #include <type_traits> #include "FFTTypes.h" namespace genfft { template <int N, class T, class U> inline typename std::enable_if<(N == 1), void>::type static_scramble(T *out, const U *in, stride_t stride = 1) { (void)stride; *out = *in; } template <int N, class T, class U> inline typename std::enable_if<(N>1), void>::type static_scramble(T *out, const U *in, stride_t stride = 1) { static_scramble<N/2, T, U>(out, in, 2 * stride); static_scramble<N/2, T, U>(out + stride, in + N/2, 2 * stride); } template <class T, class U> void scramble(T *out, const U *in, int N, stride_t stride = 1) { switch (N) { case 0: break; case 1: static_scramble<1, T, U>(out, in, stride); break; case 2: static_scramble<2, T, U>(out, in, stride); break; case 4: static_scramble<4, T, U>(out, in, stride); break; case 8: static_scramble<8, T, U>(out, in, stride); break; case 16: static_scramble<16, T, U>(out, in, stride); break; case 32: static_scramble<32, T, U>(out, in, stride); break; case 64: static_scramble<64, T, U>(out, in, stride); break; case 128: static_scramble<128, T, U>(out, in, stride); break; case 256: static_scramble<256, T, U>(out, in, stride); break; case 512: static_scramble<512, T, U>(out, in, stride); break; default: scramble<T, U>(out, in, N >> 1, stride << 1); scramble<T, U>(out + stride, in + (N >> 1), N >> 1, stride << 1); break; } } template <class T, class U> void scramble_rows(T *out, stride_t out_stride, const U *in, stride_t in_stride, index_t rows, index_t cols) { if (rows == 1) { for (index_t i=0; i<cols; i++) out[i] = in[i]; } else { scramble_rows<T, U>(out, 2*out_stride, in, in_stride, rows/2, cols); scramble_rows<T, U>(out+out_stride, 2*out_stride, in+(rows/2)*in_stride, in_stride, rows/2, cols); } } } // genfft #endif /* GEN_FFT_UTIL_H */
33.086538
110
0.66347
b9dc2a37b41e2242aa7ac77e790035c8efa07b66
6,077
c
C
kbdfans_kbd67_lite.c
Tecsmith/kbdfans-kdb67-lite
35437c88788c7aed1d84c556fbb429600d4917cc
[ "MIT" ]
null
null
null
kbdfans_kbd67_lite.c
Tecsmith/kbdfans-kdb67-lite
35437c88788c7aed1d84c556fbb429600d4917cc
[ "MIT" ]
null
null
null
kbdfans_kbd67_lite.c
Tecsmith/kbdfans-kdb67-lite
35437c88788c7aed1d84c556fbb429600d4917cc
[ "MIT" ]
null
null
null
/* Copyright 2021 DZTECH <moyi4681@live.cn> * * 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, see <http://www.gnu.org/licenses/>. */ #include <quantum.h> #include "kbdfans_kbd67_lite.h" #ifdef RGB_MATRIX_ENABLE const is31_led PROGMEM g_is31_leds[DRIVER_LED_TOTAL] = { {0, CS21_SW1, CS20_SW1, CS19_SW1}, {0, CS21_SW2, CS20_SW2, CS19_SW2}, {0, CS21_SW3, CS20_SW3, CS19_SW3}, {0, CS21_SW4, CS20_SW4, CS19_SW4}, {0, CS21_SW5, CS20_SW5, CS19_SW5}, {0, CS21_SW6, CS20_SW6, CS19_SW6}, {0, CS21_SW7, CS20_SW7, CS19_SW7}, {0, CS21_SW8, CS20_SW8, CS19_SW8}, {0, CS24_SW1, CS23_SW1, CS22_SW1}, {0, CS24_SW2, CS23_SW2, CS22_SW2}, {0, CS24_SW3, CS23_SW3, CS22_SW3}, {0, CS24_SW4, CS23_SW4, CS22_SW4}, {0, CS24_SW5, CS23_SW5, CS22_SW5}, {0, CS24_SW6, CS23_SW6, CS22_SW6}, {0, CS24_SW7, CS23_SW7, CS22_SW7}, {0, CS15_SW1, CS14_SW1, CS13_SW1}, {0, CS15_SW2, CS14_SW2, CS13_SW2}, {0, CS15_SW3, CS14_SW3, CS13_SW3}, {0, CS15_SW4, CS14_SW4, CS13_SW4}, {0, CS15_SW5, CS14_SW5, CS13_SW5}, {0, CS15_SW6, CS14_SW6, CS13_SW6}, {0, CS15_SW7, CS14_SW7, CS13_SW7}, {0, CS15_SW8, CS14_SW8, CS13_SW8}, {0, CS30_SW1, CS29_SW1, CS28_SW1}, {0, CS30_SW2, CS29_SW2, CS28_SW2}, {0, CS30_SW3, CS29_SW3, CS28_SW3}, {0, CS30_SW4, CS29_SW4, CS28_SW4}, {0, CS30_SW5, CS29_SW5, CS28_SW5}, {0, CS30_SW6, CS29_SW6, CS28_SW6}, {0, CS30_SW7, CS29_SW7, CS28_SW7}, {0, CS12_SW1, CS11_SW1, CS10_SW1}, {0, CS12_SW2, CS11_SW2, CS10_SW2}, {0, CS12_SW3, CS11_SW3, CS10_SW3}, {0, CS12_SW4, CS11_SW4, CS10_SW4}, {0, CS12_SW5, CS11_SW5, CS10_SW5}, {0, CS12_SW6, CS11_SW6, CS10_SW6}, {0, CS12_SW7, CS11_SW7, CS10_SW7}, {0, CS12_SW8, CS11_SW8, CS10_SW8}, {0, CS33_SW1, CS32_SW1, CS31_SW1}, {0, CS33_SW2, CS32_SW2, CS31_SW2}, {0, CS33_SW3, CS32_SW3, CS31_SW3}, {0, CS33_SW4, CS32_SW4, CS31_SW4}, {0, CS33_SW5, CS32_SW5, CS31_SW5}, {0, CS33_SW7, CS32_SW7, CS31_SW7}, {0, CS9_SW1, CS8_SW1, CS7_SW1}, {0, CS9_SW2, CS8_SW2, CS7_SW2}, {0, CS9_SW3, CS8_SW3, CS7_SW3}, {0, CS9_SW4, CS8_SW4, CS7_SW4}, {0, CS9_SW5, CS8_SW5, CS7_SW5}, {0, CS9_SW6, CS8_SW6, CS7_SW6}, {0, CS9_SW7, CS8_SW7, CS7_SW7}, {0, CS9_SW8, CS8_SW8, CS7_SW8}, {0, CS36_SW1, CS35_SW1, CS34_SW1}, {0, CS36_SW2, CS35_SW2, CS34_SW2}, {0, CS36_SW3, CS35_SW3, CS34_SW3}, {0, CS36_SW4, CS35_SW4, CS34_SW4}, {0, CS36_SW5, CS35_SW5, CS34_SW5}, {0, CS36_SW7, CS35_SW7, CS34_SW7}, {0, CS3_SW1, CS2_SW1, CS1_SW1}, {0, CS3_SW2, CS2_SW2, CS1_SW2}, {0, CS3_SW3, CS2_SW3, CS1_SW3}, {0, CS3_SW6, CS2_SW6, CS1_SW6}, // {0, CS39_SW1, CS38_SW1, CS37_SW1}, {0, CS39_SW2, CS38_SW2, CS37_SW2}, {0, CS39_SW3, CS38_SW3, CS37_SW3}, {0, CS39_SW4, CS38_SW4, CS37_SW4}, {0, CS39_SW5, CS38_SW5, CS37_SW5}, {0, CS39_SW7, CS38_SW7, CS37_SW7} }; #define __ NO_LED #define CAPS_LOCK_LED_INDEX 30 led_config_t g_led_config = { { // Key Matrix to LED Index { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 }, { 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29 }, { 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, __, 42, 43 }, { 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, __, 56, 57 }, { 58, 59, 60, __, __, 61, __, __, 62, __, 63, 64, __, 65, 66 } }, { // LED Index to Physical Position {0, 0}, {15, 0}, {30, 0}, {45, 0}, {60, 0}, {75, 0}, {90, 0}, {105, 0}, {119, 0}, {134, 0}, {149, 0}, {164, 0}, {179, 0}, {202, 0}, {224, 0}, {4, 16}, {22, 16}, {37, 16}, {52, 16}, {67, 16}, {82, 16}, {97, 16}, {112, 16}, {127, 16}, {142, 16}, {157, 16}, {172, 16}, {187, 16}, {205, 16}, {224, 16}, {6, 32}, {26, 32}, {41, 32}, {56, 32}, {71, 32}, {86, 32}, {101, 32}, {116, 32}, {131, 32}, {146, 32}, {161, 32}, {175, 32}, {200, 32}, {224, 32}, {9, 48}, {34, 48}, {49, 48}, {63, 48}, {78, 48}, {93, 48}, {108, 48}, {123, 48}, {138, 48}, {153, 48}, {168, 48}, {189, 48}, {209, 48}, {224, 48}, {2, 64}, {21, 64}, {39, 64}, {95, 64}, {151, 64}, {170, 64}, {194, 64}, {209, 64}, {224, 64} }, { // LED Index to Flag 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 1, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 1, 9, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 1, // caps lock is also an indicator so mask is `0x01 | 0x08` 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 1, 1, 1, 1, 4, 1, 1, 1, 1, 1 } }; #endif /* ---------------------------------------- */ #if defined(RGB_MATRIX_ENABLE) && defined(CAPS_LOCK_LED_INDEX) #ifdef RGB_MATRIX_MAXIMUM_BRIGHTNESS #define CAPS_LOCK_MAX_BRIGHTNESS RGB_MATRIX_MAXIMUM_BRIGHTNESS #else #define CAPS_LOCK_MAX_BRIGHTNESS 0xFF #endif #ifdef RGB_MATRIX_VAL_STEP #define CAPS_LOCK_VAL_STEP RGB_MATRIX_VAL_STEP #else #define CAPS_LOCK_VAL_STEP 8 #endif __attribute__ ((weak)) void rgb_matrix_indicators_user(void) { if (host_keyboard_led_state().caps_lock) { uint8_t b = rgb_matrix_get_val(); if (b < CAPS_LOCK_VAL_STEP) { b = CAPS_LOCK_VAL_STEP; } else if (b < (CAPS_LOCK_MAX_BRIGHTNESS - CAPS_LOCK_VAL_STEP)) { b += CAPS_LOCK_VAL_STEP; // one step more than current brightness } else { b = CAPS_LOCK_MAX_BRIGHTNESS; } rgb_matrix_set_color(CAPS_LOCK_LED_INDEX, b, b, b); // white, with the adjusted brightness } } #endif
38.707006
161
0.592562
f1e58b166ffdb46ac58054bb07df7cb23216f75e
11,272
c
C
SampleCode/RegBased/UART_Autoflow_Slave/main.c
OpenNuvoton/NUC121_125BSP
a8d9fda2db099eb45b47e3836b14bec425d2bb86
[ "Apache-2.0" ]
3
2020-01-14T11:07:37.000Z
2022-03-10T07:44:11.000Z
SampleCode/RegBased/UART_Autoflow_Slave/main.c
OpenNuvoton/NUC121_125BSP
a8d9fda2db099eb45b47e3836b14bec425d2bb86
[ "Apache-2.0" ]
3
2020-03-31T08:40:04.000Z
2021-08-31T21:14:14.000Z
SampleCode/RegBased/UART_Autoflow_Slave/main.c
OpenNuvoton/NUC121_125BSP
a8d9fda2db099eb45b47e3836b14bec425d2bb86
[ "Apache-2.0" ]
1
2020-01-04T01:45:46.000Z
2020-01-04T01:45:46.000Z
/***************************************************************************//** * @file main.c * @version V3.00 * @brief Transmit and receive data with auto flow control. * This sample code needs to work with UART_Autoflow_Master. * * SPDX-License-Identifier: Apache-2.0 * @copyright (C) 2016 Nuvoton Technology Corp. All rights reserved. ******************************************************************************/ #include <stdio.h> #include "NuMicro.h" #define RXBUFSIZE 1024 /*---------------------------------------------------------------------------------------------------------*/ /* Global variables */ /*---------------------------------------------------------------------------------------------------------*/ uint8_t g_u8SendData[12] = {0}; uint8_t g_u8RecData[RXBUFSIZE] = {0}; volatile int32_t g_i32pointer = 0; /*---------------------------------------------------------------------------------------------------------*/ /* Define functions prototype */ /*---------------------------------------------------------------------------------------------------------*/ void AutoFlow_FunctionRxTest(void); void SYS_Init(void) { /*---------------------------------------------------------------------------------------------------------*/ /* Init System Clock */ /*---------------------------------------------------------------------------------------------------------*/ /* Enable HIRC clock (Internal RC 48MHz) */ CLK->PWRCTL |= CLK_PWRCTL_HIRCEN_Msk; /* Wait for HIRC clock ready */ while (!(CLK->STATUS & CLK_STATUS_HIRCSTB_Msk)); /* Select HCLK clock source as HIRC and HCLK clock divider as 1 */ CLK->CLKSEL0 = (CLK->CLKSEL0 & (~CLK_CLKSEL0_HCLKSEL_Msk)) | CLK_CLKSEL0_HCLKSEL_HIRC; CLK->CLKDIV0 = (CLK->CLKDIV0 & (~CLK_CLKDIV0_HCLKDIV_Msk)) | CLK_CLKDIV0_HCLK(1); /* Enable UART and USCI module clock */ CLK->APBCLK0 |= CLK_APBCLK0_UART0CKEN_Msk; CLK->APBCLK1 |= CLK_APBCLK1_USCI0CKEN_Msk; /* Select UART module clock source as HIRC/2 and UART module clock divider as 1 */ CLK->CLKSEL1 = (CLK->CLKSEL1 & (~CLK_CLKSEL1_UARTSEL_Msk)) | CLK_CLKSEL1_UARTSEL_HIRC_DIV2; CLK->CLKDIV0 = (CLK->CLKDIV0 & (~CLK_CLKDIV0_UARTDIV_Msk)) | CLK_CLKDIV0_UART(1); /* Update System Core Clock */ PllClock = 0; // PLL SystemCoreClock = __HIRC; // HCLK CyclesPerUs = __HIRC / 1000000; // For CLK_SysTickDelay() /*---------------------------------------------------------------------------------------------------------*/ /* Init I/O Multi-function */ /*---------------------------------------------------------------------------------------------------------*/ /* Set PC multi-function pins for UART0 RXD(PC.4) and TXD(PC.5) */ SYS->GPC_MFPL = (SYS->GPC_MFPL & (~SYS_GPC_MFPL_PC4MFP_Msk)) | SYS_GPC_MFPL_PC4MFP_UART0_RXD; SYS->GPC_MFPL = (SYS->GPC_MFPL & (~SYS_GPC_MFPL_PC5MFP_Msk)) | SYS_GPC_MFPL_PC5MFP_UART0_TXD; /* Set PC multi-function pins for UART0 RTS(PC.3) and CTS(PC.2) */ SYS->GPC_MFPL = (SYS->GPC_MFPL & (~SYS_GPC_MFPL_PC3MFP_Msk)) | SYS_GPC_MFPL_PC3MFP_UART0_nRTS; SYS->GPC_MFPL = (SYS->GPC_MFPL & (~SYS_GPC_MFPL_PC2MFP_Msk)) | SYS_GPC_MFPL_PC2MFP_UART0_nCTS; /* Set PB multi-function pins for USCI0_DAT0(PB.4) and USCI0_DAT1(PB.5) */ SYS->GPB_MFPL = (SYS->GPB_MFPL & (~SYS_GPB_MFPL_PB4MFP_Msk)) | SYS_GPB_MFPL_PB4MFP_USCI0_DAT0; SYS->GPB_MFPL = (SYS->GPB_MFPL & (~SYS_GPB_MFPL_PB5MFP_Msk)) | SYS_GPB_MFPL_PB5MFP_USCI0_DAT1; } void UART0_Init() { /*---------------------------------------------------------------------------------------------------------*/ /* Init UART */ /*---------------------------------------------------------------------------------------------------------*/ /* Reset UART0 */ SYS->IPRST1 |= SYS_IPRST1_UART0RST_Msk; SYS->IPRST1 &= ~SYS_IPRST1_UART0RST_Msk; /* Configure UART0 and set UART0 baud rate */ UART0->BAUD = UART_BAUD_MODE2 | UART_BAUD_MODE2_DIVIDER(__HIRC_DIV2, 115200); UART0->LINE = UART_WORD_LEN_8 | UART_PARITY_NONE | UART_STOP_BIT_1; } void USCI0_Init() { /*---------------------------------------------------------------------------------------------------------*/ /* Init USCI */ /*---------------------------------------------------------------------------------------------------------*/ /* Reset USCI0 */ SYS->IPRST2 |= SYS_IPRST2_USCI0RST_Msk; SYS->IPRST2 &= ~SYS_IPRST2_USCI0RST_Msk; /* Configure USCI0 as UART mode */ UUART0->CTL = (2 << UUART_CTL_FUNMODE_Pos); /* Set UART function mode */ UUART0->LINECTL = UUART_WORD_LEN_8 | UUART_LINECTL_LSB_Msk; /* Set UART line configuration */ UUART0->DATIN0 = (2 << UUART_DATIN0_EDGEDET_Pos); /* Set falling edge detection */ UUART0->BRGEN = ((34 << UUART_BRGEN_CLKDIV_Pos) | (5 << UUART_BRGEN_DSCNT_Pos) | (1 << UUART_BRGEN_PDSCNT_Pos)); /* Set UART baud rate as 115200bps */ UUART0->PROTCTL |= UUART_PROTCTL_PROTEN_Msk; /* Enable UART protocol */ } /*---------------------------------------------------------------------------------------------------------*/ /* MAIN function */ /*---------------------------------------------------------------------------------------------------------*/ int main(void) { /* Unlock protected registers */ SYS_UnlockReg(); /* Init System, peripheral clock and multi-function I/O */ SYS_Init(); /* Lock protected registers */ SYS_LockReg(); /* Init UART0 for test */ UART0_Init(); /* Init USCI0 for printf */ USCI0_Init(); /*---------------------------------------------------------------------------------------------------------*/ /* SAMPLE CODE */ /*---------------------------------------------------------------------------------------------------------*/ printf("\n\nCPU @ %dHz\n", SystemCoreClock); printf("\nUART Sample Program\n"); /* UART auto flow sample slave function */ AutoFlow_FunctionRxTest(); while (1); } /*---------------------------------------------------------------------------------------------------------*/ /* ISR to handle UART Channel 0 interrupt event */ /*---------------------------------------------------------------------------------------------------------*/ void UART0_IRQHandler(void) { volatile uint32_t u32IntSts = UART0->INTSTS;; /* Rx Ready or Time-out INT */ if (UART_GET_INT_FLAG(UART0, UART_INTSTS_RDAINT_Msk)) { /* Handle received data */ g_u8RecData[g_i32pointer] = UART_READ(UART0); g_i32pointer++; } /* Time out */ else if (UART_GET_INT_FLAG(UART0, UART_INTSTS_RXTOINT_Msk)) { do { /* Handle received data */ g_u8RecData[g_i32pointer] = UART_READ(UART0); g_i32pointer++; /* Read data when FIFO RX pointer is not 0 */ } while (UART0->FIFOSTS & UART_FIFOSTS_RXPTR_Msk); } } /*---------------------------------------------------------------------------------------------------------*/ /* AutoFlow Function Test (Slave) */ /*---------------------------------------------------------------------------------------------------------*/ void AutoFlow_FunctionRxTest() { uint32_t u32i; printf("\n"); printf("+-----------------------------------------------------------+\n"); printf("| Pin Configure |\n"); printf("+-----------------------------------------------------------+\n"); printf("| ______ _____ |\n"); printf("| | | | | |\n"); printf("| |Master|--UART0_TXD(PC.5) <==> UART0_RXD(PC.4)--|Slave| |\n"); printf("| | |--UART0_nCTS(PC.2) <==> UART0_nRTS(PC.3)--| | |\n"); printf("| |______| |_____| |\n"); printf("| |\n"); printf("+-----------------------------------------------------------+\n"); printf("\n"); printf("+-----------------------------------------------------------+\n"); printf("| AutoFlow Function Test (Slave) |\n"); printf("+-----------------------------------------------------------+\n"); printf("| Description : |\n"); printf("| The sample code needs two boards. One is Master and |\n"); printf("| the other is slave. Master will send 1k bytes data |\n"); printf("| to slave. Slave will check if received data is correct |\n"); printf("| after getting 1k bytes data. |\n"); printf("| Press any key to start... |\n"); printf("+-----------------------------------------------------------+\n"); getchar(); /* Enable RTS autoflow control */ UART0->INTEN |= UART_INTEN_ATORTSEN_Msk; /* Set RTS pin output is low level active */ UART0->MODEM |= UART_MODEM_RTSACTLV_Msk; /* Set RTS Trigger Level as 8 bytes */ UART0->FIFO = (UART0->FIFO & (~UART_FIFO_RTSTRGLV_Msk)) | UART_FIFO_RTSTRGLV_8BYTES; /* Set RX Trigger Level as 8 bytes */ UART0->FIFO = (UART0->FIFO & (~UART_FIFO_RFITL_Msk)) | UART_FIFO_RFITL_8BYTES; /* Enable RDA and RTO Interrupt */ UART0->INTEN |= (UART_INTEN_RDAIEN_Msk | UART_INTEN_RXTOIEN_Msk); /* Set Timeout time 0x3E bit-time and time-out counter enable */ UART0->TOUT = (UART0->TOUT & ~UART_TOUT_TOIC_Msk) | (0x3E); UART0->INTEN |= UART_INTEN_TOCNTEN_Msk; /* Enable UART0 interrupt */ NVIC_EnableIRQ(UART0_IRQn); printf("\n Starting to receive data...\n"); /* Wait for receive 1k bytes data */ while (g_i32pointer < RXBUFSIZE); /* Compare Data */ for (u32i = 0; u32i < RXBUFSIZE; u32i++) { if (g_u8RecData[u32i] != (u32i & 0xFF)) { printf("Compare Data Failed\n"); while (1); } } printf("\n Receive OK & Check OK\n"); /* Disable UART0 interrupt */ NVIC_DisableIRQ(UART0_IRQn); /* Disable RDA and RTO Interrupt */ UART0->INTEN &= ~(UART_INTEN_RDAIEN_Msk | UART_INTEN_RXTOIEN_Msk); }
45.088
118
0.404454
477fc320e2edf06738e25decf9fef2f858ee0d0c
9,754
c
C
crypto_dh/surf127eps/mpfq/surf127eps.c
iadgov/simon-speck-supercop
5bba85c3094029eb73b7077441e5c6ea2f2cb1c6
[ "CC0-1.0" ]
21
2016-12-03T14:19:01.000Z
2018-03-09T14:52:25.000Z
crypto_dh/surf127eps/mpfq/surf127eps.c
iadgov/simon-speck-supercop
5bba85c3094029eb73b7077441e5c6ea2f2cb1c6
[ "CC0-1.0" ]
null
null
null
crypto_dh/surf127eps/mpfq/surf127eps.c
iadgov/simon-speck-supercop
5bba85c3094029eb73b7077441e5c6ea2f2cb1c6
[ "CC0-1.0" ]
11
2017-03-06T17:21:42.000Z
2018-03-18T03:52:58.000Z
/* * Author: Pierrick Gaudry * * Purpose: implement a Kummer cryptosystem on GF(2^127-eps) * see "Fast genus 2 arithmetic based on Theta functions" by P. Gaudry. * * The curve is a CM one, computed using Thomas Houtmann's tools. * * Modulus is p=2^127-735 * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <gmp.h> #include "mpfq_p_127_735.h" /* The squaring is inefficient and buggy at the moment */ #define mpfq_p_127_735_sqr(k,z,x) mpfq_p_127_735_mul(k,z,x,x) // Kummer arithmetic. typedef struct { mpfq_p_127_735_elt x; mpfq_p_127_735_elt y; mpfq_p_127_735_elt z; mpfq_p_127_735_elt t; } KSpoint_struct; typedef KSpoint_struct KSpoint[1]; typedef KSpoint_struct * dst_KSpoint; typedef const KSpoint_struct * src_KSpoint; typedef struct { mpfq_p_127_735_elt y0; mpfq_p_127_735_elt z0; mpfq_p_127_735_elt t0; mpfq_p_127_735_elt y0p; mpfq_p_127_735_elt z0p; mpfq_p_127_735_elt t0p; } KSparam_struct; typedef KSparam_struct KSparam[1]; typedef const KSparam_struct * src_KSparam; //-------------------- void KSinit(mpfq_p_127_735_field k, dst_KSpoint P) { mpfq_p_127_735_init(k, &(P->x)); mpfq_p_127_735_init(k, &(P->y)); mpfq_p_127_735_init(k, &(P->z)); mpfq_p_127_735_init(k, &(P->t)); } void KSclear(mpfq_p_127_735_field k, dst_KSpoint P) { mpfq_p_127_735_clear(k, &(P->x)); mpfq_p_127_735_clear(k, &(P->y)); mpfq_p_127_735_clear(k, &(P->z)); mpfq_p_127_735_clear(k, &(P->t)); } void KScopy(mpfq_p_127_735_field k, dst_KSpoint Q, src_KSpoint P) { mpfq_p_127_735_copy(k, Q->x, P->x); mpfq_p_127_735_copy(k, Q->y, P->y); mpfq_p_127_735_copy(k, Q->z, P->z); mpfq_p_127_735_copy(k, Q->t, P->t); } // do Hadamard-like transform in place: 8 Adds. void KShadamard(mpfq_p_127_735_field k, dst_KSpoint P) { #ifdef HAS_NATIVE_HADAMARD mpfq_p_127_735_hadamard(k, P->x, P->y, P->z, P->t); #else mpfq_p_127_735_elt tmp; mpfq_p_127_735_init(k, &tmp); mpfq_p_127_735_add(k, tmp, P->x, P->y); mpfq_p_127_735_sub(k, P->y, P->x, P->y); mpfq_p_127_735_copy(k, P->x, tmp); mpfq_p_127_735_add(k, tmp, P->z, P->t); mpfq_p_127_735_sub(k, P->t, P->z, P->t); mpfq_p_127_735_copy(k, P->z, tmp); mpfq_p_127_735_sub(k, tmp, P->x, P->z); mpfq_p_127_735_add(k, P->x, P->x, P->z); mpfq_p_127_735_add(k, P->z, P->y, P->t); mpfq_p_127_735_sub(k, P->t, P->y, P->t); mpfq_p_127_735_copy(k, P->y, tmp); mpfq_p_127_735_clear(k, &tmp); #endif } void KSdouble(mpfq_p_127_735_field k, dst_KSpoint Q, src_KSpoint P, src_KSparam KS) { KScopy(k, Q, P); KShadamard(k, Q); mpfq_p_127_735_sqr(k, Q->x, Q->x); mpfq_p_127_735_sqr(k, Q->y, Q->y); mpfq_p_127_735_mul(k, Q->y, Q->y, KS->y0p); mpfq_p_127_735_sqr(k, Q->z, Q->z); mpfq_p_127_735_mul(k, Q->z, Q->z, KS->z0p); mpfq_p_127_735_sqr(k, Q->t, Q->t); mpfq_p_127_735_mul(k, Q->t, Q->t, KS->t0p); KShadamard(k, Q); mpfq_p_127_735_sqr(k, Q->x, Q->x); mpfq_p_127_735_sqr(k, Q->y, Q->y); mpfq_p_127_735_mul(k, Q->y, Q->y, KS->y0); mpfq_p_127_735_sqr(k, Q->z, Q->z); mpfq_p_127_735_mul(k, Q->z, Q->z, KS->z0); mpfq_p_127_735_sqr(k, Q->t, Q->t); mpfq_p_127_735_mul(k, Q->t, Q->t, KS->t0); } void KSprint(mpfq_p_127_735_field k, src_KSpoint P) { mpfq_p_127_735_print(k, P->x); printf("\n"); mpfq_p_127_735_print(k, P->y); printf("\n"); mpfq_p_127_735_print(k, P->z); printf("\n"); mpfq_p_127_735_print(k, P->t); printf("\n"); } // scalar multiplication on Surf127_735. // key is 4 limb long. void KSmul(mpfq_p_127_735_field k, dst_KSpoint res, src_KSpoint P, mpz_t key, src_KSparam KS) { KSpoint Pm, Pp; mpfq_p_127_735_elt tmpy, tmpz, tmpt; mpfq_p_127_735_elt YY, ZZ, TT; KSpoint_struct *pm, *pp, *tmp; int i, l; if (mpz_cmp_ui(key, 0)==0) { // implement me! assert (0); } if (mpz_cmp_ui(key, 1)==0) { KScopy(k, res, P); return; } KSinit(k, Pm); KSinit(k, Pp); KScopy(k, Pm, P); KSdouble(k, Pp, Pm, KS); if (mpz_cmp_ui(key, 2)==0) { KScopy(k, res, Pp); KSclear(k, Pm); KSclear(k, Pp); return; } mpfq_p_127_735_init(k, &tmpy); mpfq_p_127_735_init(k, &tmpz); mpfq_p_127_735_init(k, &tmpt); mpfq_p_127_735_init(k, &YY); mpfq_p_127_735_init(k, &ZZ); mpfq_p_127_735_init(k, &TT); mpfq_p_127_735_mul(k, tmpy, P->y, P->z); mpfq_p_127_735_mul(k, tmpz, tmpy, P->t); mpfq_p_127_735_inv(k, tmpz, tmpz); mpfq_p_127_735_mul(k, tmpz, tmpz, P->x); mpfq_p_127_735_mul(k, TT, tmpz, tmpy); // x/t mpfq_p_127_735_mul(k, tmpy, P->z, P->t); mpfq_p_127_735_mul(k, YY, tmpz, tmpy); // x/y mpfq_p_127_735_mul(k, tmpy, P->y, P->t); mpfq_p_127_735_mul(k, ZZ, tmpz, tmpy); // x/z #if 0 mpfq_p_127_735_inv(k, YY, P->y); mpfq_p_127_735_mul(k, YY, YY, P->x); mpfq_p_127_735_inv(k, ZZ, P->z); mpfq_p_127_735_mul(k, ZZ, ZZ, P->x); mpfq_p_127_735_inv(k, TT, P->t); mpfq_p_127_735_mul(k, TT, TT, P->x); #endif // initialize loop pm = Pm; pp = Pp; // loop l = mpz_sizeinbase(key, 2); assert (mpz_tstbit(key, l-1) == 1); for (i = l-2; i >= 0; --i) { int swap; swap = (mpz_tstbit(key, i) == 1); if (swap) { tmp = pp; pp = pm; pm = tmp; } // pseudo add(pm, pp) -> pp ; dble(pm) -> pm // Total: 32A + 16P + 9S KShadamard(k, pm); // 8A mpfq_p_127_735_mul(k, tmpy, pm->y, KS->y0p); mpfq_p_127_735_mul(k, tmpz, pm->z, KS->z0p); mpfq_p_127_735_mul(k, tmpt, pm->t, KS->t0p); // 3P KShadamard(k, pp); // 8A mpfq_p_127_735_mul(k, pp->x, pp->x, pm->x); mpfq_p_127_735_mul(k, pp->y, pp->y, tmpy); mpfq_p_127_735_mul(k, pp->z, pp->z, tmpz); mpfq_p_127_735_mul(k, pp->t, pp->t, tmpt); // 4P KShadamard(k, pp); // 8A mpfq_p_127_735_sqr(k, pp->x, pp->x); mpfq_p_127_735_sqr(k, pp->y, pp->y); mpfq_p_127_735_sqr(k, pp->z, pp->z); mpfq_p_127_735_sqr(k, pp->t, pp->t); // 4S mpfq_p_127_735_mul(k, pp->y, pp->y, YY); mpfq_p_127_735_mul(k, pp->z, pp->z, ZZ); mpfq_p_127_735_mul(k, pp->t, pp->t, TT); // 3P mpfq_p_127_735_sqr(k, pm->x, pm->x); // 1S mpfq_p_127_735_mul(k, pm->y, pm->y, tmpy); mpfq_p_127_735_mul(k, pm->z, pm->z, tmpz); mpfq_p_127_735_mul(k, pm->t, pm->t, tmpt); // 3P KShadamard(k, pm); // 8A mpfq_p_127_735_sqr(k, pm->x, pm->x); mpfq_p_127_735_sqr(k, pm->y, pm->y); mpfq_p_127_735_sqr(k, pm->z, pm->z); mpfq_p_127_735_sqr(k, pm->t, pm->t); // 4S mpfq_p_127_735_mul(k, pm->y, pm->y, KS->y0); mpfq_p_127_735_mul(k, pm->z, pm->z, KS->z0); mpfq_p_127_735_mul(k, pm->t, pm->t, KS->t0); // 3P if (swap) { tmp = pp; pp = pm; pm = tmp; } } KScopy(k, res, pm); KSclear(k, Pm); KSclear(k, Pp); mpfq_p_127_735_clear(k, &YY); mpfq_p_127_735_clear(k, &ZZ); mpfq_p_127_735_clear(k, &TT); mpfq_p_127_735_clear(k, &tmpy); mpfq_p_127_735_clear(k, &tmpz); mpfq_p_127_735_clear(k, &tmpt); } int read_mp(mp_limb_t* x, int k, const char *str, int base) { int i, n, len; unsigned char *tmp; len = strlen(str); tmp = (unsigned char *) malloc(sizeof(unsigned char)*len); if (!tmp) { fprintf(stderr, "malloc failed in read_mp\n"); return 0; } for (i = 0; i < len; ++i) tmp[i] = (unsigned char)(str[i]-'0'); n = mpn_set_str(x, tmp, len, base); if (n > k) { fprintf(stderr, "error in read_mp, input number is too large\n"); return 0; } for (i = n; i<k; ++i) x[i] = 0UL; free(tmp); return 1; } #ifdef WANT_MAIN int main(int argc, char** argv) { mpz_t key; mpfq_p_127_735_field k; KSpoint res, base_point; KSparam KS; int i; mpfq_p_127_735_field_init(k, (mp_limb_t *)NULL); if (argc != 6) { fprintf(stderr, "usage: %s key base_point\n", argv[0]); fprintf(stderr, " key is the secret key (an integer < 2^254)\n"); fprintf(stderr, " base_point is the point to multiply\n"); fprintf(stderr, " base_point must be of the form 1 y z t\n"); fprintf(stderr, " (integers less than 2^127, whitespace separated.\n"); return 1; } // KS parameters. mpfq_p_127_735_init(k, &(KS->y0 )); mpfq_p_127_735_init(k, &(KS->z0 )); mpfq_p_127_735_init(k, &(KS->t0 )); mpfq_p_127_735_init(k, &(KS->y0p)); mpfq_p_127_735_init(k, &(KS->z0p)); mpfq_p_127_735_init(k, &(KS->t0p)); mpfq_p_127_735_read(k, KS->y0, "86208552985914662648361214299883935423", 10); mpfq_p_127_735_read(k, KS->z0, "160053938517731349632395585267160595069", 10); mpfq_p_127_735_read(k, KS->t0, "35005564474699507747312683600916451858", 10); mpfq_p_127_735_read(k, KS->y0p, "94814796580219064497014986095768528928", 10); mpfq_p_127_735_read(k, KS->z0p, "42902767594179849850407630572137072504", 10); mpfq_p_127_735_read(k, KS->t0p, "22524084758416781578372604087642334537", 10); mpz_init_set_str(key, argv[1], 10); KSinit(k, base_point); mpfq_p_127_735_read(k, base_point->x, argv[2], 10); mpfq_p_127_735_read(k, base_point->y, argv[3], 10); mpfq_p_127_735_read(k, base_point->z, argv[4], 10); mpfq_p_127_735_read(k, base_point->t, argv[5], 10); KSinit(k, res); for (i = 0; i < 10000; ++i) { KSmul(k, res, base_point, key, KS); } mpfq_p_127_735_inv(k, res->x, res->x); mpfq_p_127_735_mul(k, res->y, res->y, res->x); mpfq_p_127_735_mul(k, res->z, res->z, res->x); mpfq_p_127_735_mul(k, res->t, res->t, res->x); // set x to 1. (res->x)[0] = 1UL; for (i = 1; i < k->kl; ++i) (res->x)[i] = 0UL; KSprint(k, res); printf("\n"); mpfq_p_127_735_clear(k, &(KS->y0 )); mpfq_p_127_735_clear(k, &(KS->z0 )); mpfq_p_127_735_clear(k, &(KS->t0 )); mpfq_p_127_735_clear(k, &(KS->y0p)); mpfq_p_127_735_clear(k, &(KS->z0p)); mpfq_p_127_735_clear(k, &(KS->t0p)); KSclear(k, base_point); KSclear(k, res); mpz_clear(key); return 0; } #endif
27.948424
80
0.636252
a48704328adc29ed3e340fface78fee086131b28
527
c
C
libc/unistd/eventfd.c
cfriedt/bionic
d65ab1d9017fe191208974be49aa244688177e26
[ "BSD-2-Clause" ]
18
2015-06-28T23:08:40.000Z
2021-11-19T17:55:25.000Z
libc/unistd/eventfd.c
cfriedt/bionic
d65ab1d9017fe191208974be49aa244688177e26
[ "BSD-2-Clause" ]
1
2015-12-05T14:20:14.000Z
2015-12-05T14:20:14.000Z
libc/unistd/eventfd.c
cfriedt/bionic
d65ab1d9017fe191208974be49aa244688177e26
[ "BSD-2-Clause" ]
4
2017-12-19T12:22:07.000Z
2022-01-25T16:07:47.000Z
#include <sys/eventfd.h> #include <unistd.h> /* We duplicate the GLibc error semantics, which are poorly defined * if the read() or write() does not return the proper number of bytes. */ int eventfd_read(int fd, eventfd_t *counter) { int ret = read(fd, counter, sizeof(*counter)); if (ret == sizeof(*counter)) return 0; return -1; } int eventfd_write(int fd, eventfd_t counter) { int ret = write(fd, &counter, sizeof(counter)); if (ret == sizeof(counter)) return 0; return -1; }
20.269231
71
0.643264
a8a17cc75cd36ef0dc823482a435265d4bc4c635
6,734
c
C
lib/wplua/object.c
PipeWire/wireplumber
51713d309a08d1040d883a226d0f82a832c7eb2d
[ "MIT" ]
10
2020-02-02T18:18:47.000Z
2022-03-29T13:22:46.000Z
lib/wplua/object.c
PipeWire/wireplumber
51713d309a08d1040d883a226d0f82a832c7eb2d
[ "MIT" ]
6
2021-06-01T09:31:09.000Z
2022-03-14T13:18:42.000Z
lib/wplua/object.c
PipeWire/wireplumber
51713d309a08d1040d883a226d0f82a832c7eb2d
[ "MIT" ]
1
2020-10-11T08:30:59.000Z
2020-10-11T08:30:59.000Z
/* WirePlumber * * Copyright © 2020 Collabora Ltd. * @author George Kiagiadakis <george.kiagiadakis@collabora.com> * * SPDX-License-Identifier: MIT */ #include "wplua.h" #include "private.h" #include <wp/wp.h> static int _wplua_gobject_call (lua_State *L) { GObject *obj = wplua_checkobject (L, 1, G_TYPE_OBJECT); const char *sig_name = lua_tostring (L, 2); guint n_params = lua_gettop (L) - 2; GSignalQuery query; guint sig_id = 0; GQuark detail = 0; if (G_UNLIKELY (!g_signal_parse_name (sig_name, G_TYPE_FROM_INSTANCE (obj), &sig_id, &detail, FALSE))) luaL_error (L, "unknown signal '%s::%s'", G_OBJECT_TYPE_NAME (obj), sig_name); g_signal_query (sig_id, &query); if (G_UNLIKELY (!(query.signal_flags & G_SIGNAL_ACTION))) luaL_error (L, "lua code is not allowed to emit non-action signal '%s::%s'", G_OBJECT_TYPE_NAME (obj), sig_name); if (G_UNLIKELY (query.n_params > n_params)) luaL_error (L, "not enough arguments for '%s::%s': expected %d, got %d", G_OBJECT_TYPE_NAME (obj), sig_name, query.n_params, n_params); GValue ret = G_VALUE_INIT; GValue *vals = g_newa (GValue, n_params + 1); memset (vals, 0, sizeof (GValue) * (n_params + 1)); if (query.return_type != G_TYPE_NONE) g_value_init (&ret, query.return_type); g_value_init_from_instance (&vals[0], obj); for (guint i = 0; i < n_params; i++) { g_value_init (&vals[i+1], query.param_types[i]); wplua_lua_to_gvalue (L, i+3, &vals[i+1]); } g_signal_emitv (vals, sig_id, detail, &ret); for (guint i = 0; i < n_params + 1; i++) { g_value_unset (&vals[i]); } int n_ret = 0; if (query.return_type != G_TYPE_NONE) n_ret = wplua_gvalue_to_lua (L, &ret); g_value_unset (&ret); return n_ret; } static int _wplua_gobject_connect (lua_State *L) { GObject *obj = wplua_checkobject (L, 1, G_TYPE_OBJECT); const char *sig_name = luaL_checkstring (L, 2); luaL_checktype (L, 3, LUA_TFUNCTION); guint sig_id = 0; GQuark detail = 0; if (G_UNLIKELY (!g_signal_parse_name (sig_name, G_TYPE_FROM_INSTANCE (obj), &sig_id, &detail, FALSE))) luaL_error (L, "unknown signal '%s::%s'", G_OBJECT_TYPE_NAME (obj), sig_name); GClosure *closure = wplua_function_to_closure (L, 3); gulong handler = g_signal_connect_closure_by_id (obj, sig_id, detail, closure, FALSE); lua_pushinteger (L, handler); return 1; } static lua_CFunction find_method_in_luaL_Reg (luaL_Reg *reg, const gchar *method) { if (reg) { while (reg->name) { if (!g_strcmp0 (method, reg->name)) return reg->func; reg++; } } return NULL; } static int _wplua_gobject___index (lua_State *L) { GObject *obj = wplua_checkobject (L, 1, G_TYPE_OBJECT); const gchar *key = luaL_checkstring (L, 2); lua_CFunction func = NULL; GHashTable *vtables; lua_pushliteral (L, "wplua_vtables"); lua_gettable (L, LUA_REGISTRYINDEX); vtables = wplua_toboxed (L, -1); lua_pop (L, 1); if (!g_strcmp0 (key, "call")) func = _wplua_gobject_call; else if (!g_strcmp0 (key, "connect")) func = _wplua_gobject_connect; /* search in registered vtables */ if (!func) { GType type = G_TYPE_FROM_INSTANCE (obj); while (!func && type) { luaL_Reg *reg = g_hash_table_lookup (vtables, GUINT_TO_POINTER (type)); func = find_method_in_luaL_Reg (reg, key); type = g_type_parent (type); } } /* search in registered vtables of interfaces */ if (!func) { g_autofree GType *interfaces = g_type_interfaces (G_TYPE_FROM_INSTANCE (obj), NULL); GType *type = interfaces; while (!func && *type) { luaL_Reg *reg = g_hash_table_lookup (vtables, GUINT_TO_POINTER (*type)); func = find_method_in_luaL_Reg (reg, key); type++; } } if (func) { lua_pushcfunction (L, func); return 1; } else { /* search in properties */ GObjectClass *klass = G_OBJECT_GET_CLASS (obj); GParamSpec *pspec = g_object_class_find_property (klass, key); if (pspec && (pspec->flags & G_PARAM_READABLE)) { g_auto (GValue) v = G_VALUE_INIT; g_value_init (&v, pspec->value_type); g_object_get_property (obj, key, &v); return wplua_gvalue_to_lua (L, &v); } } return 0; } static int _wplua_gobject___newindex (lua_State *L) { GObject *obj = wplua_checkobject (L, 1, G_TYPE_OBJECT); const gchar *key = luaL_checkstring (L, 2); /* search in properties */ GObjectClass *klass = G_OBJECT_GET_CLASS (obj); GParamSpec *pspec = g_object_class_find_property (klass, key); if (pspec && (pspec->flags & G_PARAM_WRITABLE)) { g_auto (GValue) v = G_VALUE_INIT; g_value_init (&v, pspec->value_type); wplua_lua_to_gvalue (L, 3, &v); g_object_set_property (obj, key, &v); } else { luaL_error (L, "attempted to assign unknown or non-writable property '%s'", key); } return 0; } static int _wplua_gobject__tostring (lua_State *L) { GObject *obj; gchar *str; obj = wplua_checkobject (L, 1, G_TYPE_OBJECT); str = g_strdup_printf (WP_OBJECT_FORMAT, WP_OBJECT_ARGS (obj)); lua_pushstring (L, str); g_free (str); return 1; } void _wplua_init_gobject (lua_State *L) { static const luaL_Reg gobject_meta[] = { { "__gc", _wplua_gvalue_userdata___gc }, { "__eq", _wplua_gvalue_userdata___eq }, { "__index", _wplua_gobject___index }, { "__newindex", _wplua_gobject___newindex }, { "__tostring", _wplua_gobject__tostring }, { NULL, NULL } }; luaL_newmetatable (L, "GObject"); luaL_setfuncs (L, gobject_meta, 0); lua_pop (L, 1); } void wplua_pushobject (lua_State * L, gpointer object) { g_return_if_fail (G_IS_OBJECT (object)); GValue *v = _wplua_pushgvalue_userdata (L, G_TYPE_FROM_INSTANCE (object)); wp_trace_object (object, "pushing to Lua, v=%p", v); g_value_take_object (v, object); luaL_getmetatable (L, "GObject"); lua_setmetatable (L, -2); } gpointer wplua_toobject (lua_State *L, int idx) { g_return_val_if_fail (_wplua_isgvalue_userdata (L, idx, G_TYPE_OBJECT), NULL); return g_value_get_object ((GValue *) lua_touserdata (L, idx)); } gpointer wplua_checkobject (lua_State *L, int idx, GType type) { if (G_UNLIKELY (!_wplua_isgvalue_userdata (L, idx, type))) { wp_critical ("expected userdata storing GValue<%s>", g_type_name (type)); luaL_argerror (L, idx, "expected userdata storing GValue<GObject>"); } return g_value_get_object ((GValue *) lua_touserdata (L, idx)); } gboolean wplua_isobject (lua_State *L, int idx, GType type) { if (!g_type_is_a (type, G_TYPE_OBJECT)) return FALSE; return _wplua_isgvalue_userdata (L, idx, type); }
27.263158
80
0.665726
a8b92cc18f316e9b36c3b790363d4450372ff8dd
26,080
c
C
rock/external/xserver/Xi/xibarriers.c
NovasomIndustries/Utils-2019.01
ab6d48edc03363f3ee4f1e9efc5269fdecfe35a8
[ "MIT" ]
2
2019-04-20T14:21:56.000Z
2019-06-14T07:17:22.000Z
rock/external/xserver/Xi/xibarriers.c
NovasomIndustries/Utils-2019.07
4a41062e0f50c1f97cb37df91457672ce386516d
[ "MIT" ]
null
null
null
rock/external/xserver/Xi/xibarriers.c
NovasomIndustries/Utils-2019.07
4a41062e0f50c1f97cb37df91457672ce386516d
[ "MIT" ]
1
2021-07-11T14:36:00.000Z
2021-07-11T14:36:00.000Z
/* * Copyright 2012 Red Hat, Inc. * * 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 (including the next * paragraph) 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. * * Copyright © 2002 Keith Packard * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of Keith Packard not be used in * advertising or publicity pertaining to distribution of the software without * specific, written prior permission. Keith Packard makes no * representations about the suitability of this software for any purpose. It * is provided "as is" without express or implied warranty. * * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL KEITH PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ #ifdef HAVE_DIX_CONFIG_H #include <dix-config.h> #endif #include "xibarriers.h" #include "scrnintstr.h" #include "cursorstr.h" #include "dixevents.h" #include "servermd.h" #include "mipointer.h" #include "inputstr.h" #include "windowstr.h" #include "xace.h" #include "list.h" #include "exglobals.h" #include "eventstr.h" #include "mi.h" RESTYPE PointerBarrierType; static DevPrivateKeyRec BarrierScreenPrivateKeyRec; #define BarrierScreenPrivateKey (&BarrierScreenPrivateKeyRec) typedef struct PointerBarrierClient *PointerBarrierClientPtr; struct PointerBarrierDevice { struct xorg_list entry; int deviceid; Time last_timestamp; int barrier_event_id; int release_event_id; Bool hit; Bool seen; }; struct PointerBarrierClient { XID id; ScreenPtr screen; Window window; struct PointerBarrier barrier; struct xorg_list entry; /* num_devices/device_ids are devices the barrier applies to */ int num_devices; int *device_ids; /* num_devices */ /* per_device keeps track of devices actually blocked by barriers */ struct xorg_list per_device; }; typedef struct _BarrierScreen { struct xorg_list barriers; } BarrierScreenRec, *BarrierScreenPtr; #define GetBarrierScreen(s) ((BarrierScreenPtr)dixLookupPrivate(&(s)->devPrivates, BarrierScreenPrivateKey)) #define GetBarrierScreenIfSet(s) GetBarrierScreen(s) #define SetBarrierScreen(s,p) dixSetPrivate(&(s)->devPrivates, BarrierScreenPrivateKey, p) static struct PointerBarrierDevice *AllocBarrierDevice(void) { struct PointerBarrierDevice *pbd = NULL; pbd = malloc(sizeof(struct PointerBarrierDevice)); if (!pbd) return NULL; pbd->deviceid = -1; /* must be set by caller */ pbd->barrier_event_id = 1; pbd->release_event_id = 0; pbd->hit = FALSE; pbd->seen = FALSE; xorg_list_init(&pbd->entry); return pbd; } static void FreePointerBarrierClient(struct PointerBarrierClient *c) { struct PointerBarrierDevice *pbd = NULL, *tmp = NULL; xorg_list_for_each_entry_safe(pbd, tmp, &c->per_device, entry) { free(pbd); } free(c); } static struct PointerBarrierDevice *GetBarrierDevice(struct PointerBarrierClient *c, int deviceid) { struct PointerBarrierDevice *pbd = NULL; xorg_list_for_each_entry(pbd, &c->per_device, entry) { if (pbd->deviceid == deviceid) break; } BUG_WARN(!pbd); return pbd; } static BOOL barrier_is_horizontal(const struct PointerBarrier *barrier) { return barrier->y1 == barrier->y2; } static BOOL barrier_is_vertical(const struct PointerBarrier *barrier) { return barrier->x1 == barrier->x2; } /** * @return The set of barrier movement directions the movement vector * x1/y1 → x2/y2 represents. */ int barrier_get_direction(int x1, int y1, int x2, int y2) { int direction = 0; /* which way are we trying to go */ if (x2 > x1) direction |= BarrierPositiveX; if (x2 < x1) direction |= BarrierNegativeX; if (y2 > y1) direction |= BarrierPositiveY; if (y2 < y1) direction |= BarrierNegativeY; return direction; } /** * Test if the barrier may block movement in the direction defined by * x1/y1 → x2/y2. This function only tests whether the directions could be * blocked, it does not test if the barrier actually blocks the movement. * * @return TRUE if the barrier blocks the direction of movement or FALSE * otherwise. */ BOOL barrier_is_blocking_direction(const struct PointerBarrier * barrier, int direction) { /* Barriers define which way is ok, not which way is blocking */ return (barrier->directions & direction) != direction; } static BOOL inside_segment(int v, int v1, int v2) { if (v1 < 0 && v2 < 0) /* line */ return TRUE; else if (v1 < 0) /* ray */ return v <= v2; else if (v2 < 0) /* ray */ return v >= v1; else /* line segment */ return v >= v1 && v <= v2; } #define T(v, a, b) (((float)v) - (a)) / ((b) - (a)) #define F(t, a, b) ((t) * ((a) - (b)) + (a)) /** * Test if the movement vector x1/y1 → x2/y2 is intersecting with the * barrier. A movement vector with the startpoint or endpoint adjacent to * the barrier itself counts as intersecting. * * @param x1 X start coordinate of movement vector * @param y1 Y start coordinate of movement vector * @param x2 X end coordinate of movement vector * @param y2 Y end coordinate of movement vector * @param[out] distance The distance between the start point and the * intersection with the barrier (if applicable). * @return TRUE if the barrier intersects with the given vector */ BOOL barrier_is_blocking(const struct PointerBarrier * barrier, int x1, int y1, int x2, int y2, double *distance) { if (barrier_is_vertical(barrier)) { float t, y; t = T(barrier->x1, x1, x2); if (t < 0 || t > 1) return FALSE; /* Edge case: moving away from barrier. */ if (x2 > x1 && t == 0) return FALSE; y = F(t, y1, y2); if (!inside_segment(y, barrier->y1, barrier->y2)) return FALSE; *distance = sqrt((pow(y - y1, 2) + pow(barrier->x1 - x1, 2))); return TRUE; } else { float t, x; t = T(barrier->y1, y1, y2); if (t < 0 || t > 1) return FALSE; /* Edge case: moving away from barrier. */ if (y2 > y1 && t == 0) return FALSE; x = F(t, x1, x2); if (!inside_segment(x, barrier->x1, barrier->x2)) return FALSE; *distance = sqrt((pow(x - x1, 2) + pow(barrier->y1 - y1, 2))); return TRUE; } } #define HIT_EDGE_EXTENTS 2 static BOOL barrier_inside_hit_box(struct PointerBarrier *barrier, int x, int y) { int x1, x2, y1, y2; int dir; x1 = barrier->x1; x2 = barrier->x2; y1 = barrier->y1; y2 = barrier->y2; dir = ~(barrier->directions); if (barrier_is_vertical(barrier)) { if (dir & BarrierPositiveX) x1 -= HIT_EDGE_EXTENTS; if (dir & BarrierNegativeX) x2 += HIT_EDGE_EXTENTS; } if (barrier_is_horizontal(barrier)) { if (dir & BarrierPositiveY) y1 -= HIT_EDGE_EXTENTS; if (dir & BarrierNegativeY) y2 += HIT_EDGE_EXTENTS; } return x >= x1 && x <= x2 && y >= y1 && y <= y2; } static BOOL barrier_blocks_device(struct PointerBarrierClient *client, DeviceIntPtr dev) { int i; int master_id; /* Clients with no devices are treated as * if they specified XIAllDevices. */ if (client->num_devices == 0) return TRUE; master_id = GetMaster(dev, POINTER_OR_FLOAT)->id; for (i = 0; i < client->num_devices; i++) { int device_id = client->device_ids[i]; if (device_id == XIAllDevices || device_id == XIAllMasterDevices || device_id == master_id) return TRUE; } return FALSE; } /** * Find the nearest barrier client that is blocking movement from x1/y1 to x2/y2. * * @param dir Only barriers blocking movement in direction dir are checked * @param x1 X start coordinate of movement vector * @param y1 Y start coordinate of movement vector * @param x2 X end coordinate of movement vector * @param y2 Y end coordinate of movement vector * @return The barrier nearest to the movement origin that blocks this movement. */ static struct PointerBarrierClient * barrier_find_nearest(BarrierScreenPtr cs, DeviceIntPtr dev, int dir, int x1, int y1, int x2, int y2) { struct PointerBarrierClient *c, *nearest = NULL; double min_distance = INT_MAX; /* can't get higher than that in X anyway */ xorg_list_for_each_entry(c, &cs->barriers, entry) { struct PointerBarrier *b = &c->barrier; struct PointerBarrierDevice *pbd; double distance; pbd = GetBarrierDevice(c, dev->id); if (pbd->seen) continue; if (!barrier_is_blocking_direction(b, dir)) continue; if (!barrier_blocks_device(c, dev)) continue; if (barrier_is_blocking(b, x1, y1, x2, y2, &distance)) { if (min_distance > distance) { min_distance = distance; nearest = c; } } } return nearest; } /** * Clamp to the given barrier given the movement direction specified in dir. * * @param barrier The barrier to clamp to * @param dir The movement direction * @param[out] x The clamped x coordinate. * @param[out] y The clamped x coordinate. */ void barrier_clamp_to_barrier(struct PointerBarrier *barrier, int dir, int *x, int *y) { if (barrier_is_vertical(barrier)) { if ((dir & BarrierNegativeX) & ~barrier->directions) *x = barrier->x1; if ((dir & BarrierPositiveX) & ~barrier->directions) *x = barrier->x1 - 1; } if (barrier_is_horizontal(barrier)) { if ((dir & BarrierNegativeY) & ~barrier->directions) *y = barrier->y1; if ((dir & BarrierPositiveY) & ~barrier->directions) *y = barrier->y1 - 1; } } void input_constrain_cursor(DeviceIntPtr dev, ScreenPtr screen, int current_x, int current_y, int dest_x, int dest_y, int *out_x, int *out_y, int *nevents, InternalEvent* events) { /* Clamped coordinates here refer to screen edge clamping. */ BarrierScreenPtr cs = GetBarrierScreen(screen); int x = dest_x, y = dest_y; int dir; struct PointerBarrier *nearest = NULL; PointerBarrierClientPtr c; Time ms = GetTimeInMillis(); BarrierEvent ev = { .header = ET_Internal, .type = 0, .length = sizeof (BarrierEvent), .time = ms, .deviceid = dev->id, .sourceid = dev->id, .dx = dest_x - current_x, .dy = dest_y - current_y, .root = screen->root->drawable.id, }; InternalEvent *barrier_events = events; DeviceIntPtr master; if (nevents) *nevents = 0; if (xorg_list_is_empty(&cs->barriers) || IsFloating(dev)) goto out; /** * This function is only called for slave devices, but pointer-barriers * are for master-devices only. Flip the device to the master here, * continue with that. */ master = GetMaster(dev, MASTER_POINTER); /* How this works: * Given the origin and the movement vector, get the nearest barrier * to the origin that is blocking the movement. * Clamp to that barrier. * Then, check from the clamped intersection to the original * destination, again finding the nearest barrier and clamping. */ dir = barrier_get_direction(current_x, current_y, x, y); while (dir != 0) { int new_sequence; struct PointerBarrierDevice *pbd; c = barrier_find_nearest(cs, master, dir, current_x, current_y, x, y); if (!c) break; nearest = &c->barrier; pbd = GetBarrierDevice(c, master->id); new_sequence = !pbd->hit; pbd->seen = TRUE; pbd->hit = TRUE; if (pbd->barrier_event_id == pbd->release_event_id) continue; ev.type = ET_BarrierHit; barrier_clamp_to_barrier(nearest, dir, &x, &y); if (barrier_is_vertical(nearest)) { dir &= ~(BarrierNegativeX | BarrierPositiveX); current_x = x; } else if (barrier_is_horizontal(nearest)) { dir &= ~(BarrierNegativeY | BarrierPositiveY); current_y = y; } ev.flags = 0; ev.event_id = pbd->barrier_event_id; ev.barrierid = c->id; ev.dt = new_sequence ? 0 : ms - pbd->last_timestamp; ev.window = c->window; pbd->last_timestamp = ms; /* root x/y is filled in later */ barrier_events->barrier_event = ev; barrier_events++; *nevents += 1; } xorg_list_for_each_entry(c, &cs->barriers, entry) { struct PointerBarrierDevice *pbd; int flags = 0; pbd = GetBarrierDevice(c, master->id); pbd->seen = FALSE; if (!pbd->hit) continue; if (barrier_inside_hit_box(&c->barrier, x, y)) continue; pbd->hit = FALSE; ev.type = ET_BarrierLeave; if (pbd->barrier_event_id == pbd->release_event_id) flags |= XIBarrierPointerReleased; ev.flags = flags; ev.event_id = pbd->barrier_event_id; ev.barrierid = c->id; ev.dt = ms - pbd->last_timestamp; ev.window = c->window; pbd->last_timestamp = ms; /* root x/y is filled in later */ barrier_events->barrier_event = ev; barrier_events++; *nevents += 1; /* If we've left the hit box, this is the * start of a new event ID. */ pbd->barrier_event_id++; } out: *out_x = x; *out_y = y; } static void sort_min_max(INT16 *a, INT16 *b) { INT16 A, B; if (*a < 0 || *b < 0) return; A = *a; B = *b; *a = min(A, B); *b = max(A, B); } static int CreatePointerBarrierClient(ClientPtr client, xXFixesCreatePointerBarrierReq * stuff, PointerBarrierClientPtr *client_out) { WindowPtr pWin; ScreenPtr screen; BarrierScreenPtr cs; int err; int size; int i; struct PointerBarrierClient *ret; CARD16 *in_devices; DeviceIntPtr dev; size = sizeof(*ret) + sizeof(DeviceIntPtr) * stuff->num_devices; ret = malloc(size); if (!ret) { return BadAlloc; } xorg_list_init(&ret->per_device); err = dixLookupWindow(&pWin, stuff->window, client, DixReadAccess); if (err != Success) { client->errorValue = stuff->window; goto error; } screen = pWin->drawable.pScreen; cs = GetBarrierScreen(screen); ret->screen = screen; ret->window = stuff->window; ret->num_devices = stuff->num_devices; if (ret->num_devices > 0) ret->device_ids = (int*)&ret[1]; else ret->device_ids = NULL; in_devices = (CARD16 *) &stuff[1]; for (i = 0; i < stuff->num_devices; i++) { int device_id = in_devices[i]; DeviceIntPtr device; if ((err = dixLookupDevice (&device, device_id, client, DixReadAccess))) { client->errorValue = device_id; goto error; } if (!IsMaster (device)) { client->errorValue = device_id; err = BadDevice; goto error; } ret->device_ids[i] = device_id; } /* Alloc one per master pointer, they're the ones that can be blocked */ xorg_list_init(&ret->per_device); nt_list_for_each_entry(dev, inputInfo.devices, next) { struct PointerBarrierDevice *pbd; if (dev->type != MASTER_POINTER) continue; pbd = AllocBarrierDevice(); if (!pbd) { err = BadAlloc; goto error; } pbd->deviceid = dev->id; xorg_list_add(&pbd->entry, &ret->per_device); } ret->id = stuff->barrier; ret->barrier.x1 = stuff->x1; ret->barrier.x2 = stuff->x2; ret->barrier.y1 = stuff->y1; ret->barrier.y2 = stuff->y2; sort_min_max(&ret->barrier.x1, &ret->barrier.x2); sort_min_max(&ret->barrier.y1, &ret->barrier.y2); ret->barrier.directions = stuff->directions & 0x0f; if (barrier_is_horizontal(&ret->barrier)) ret->barrier.directions &= ~(BarrierPositiveX | BarrierNegativeX); if (barrier_is_vertical(&ret->barrier)) ret->barrier.directions &= ~(BarrierPositiveY | BarrierNegativeY); xorg_list_add(&ret->entry, &cs->barriers); *client_out = ret; return Success; error: *client_out = NULL; FreePointerBarrierClient(ret); return err; } static int BarrierFreeBarrier(void *data, XID id) { struct PointerBarrierClient *c; Time ms = GetTimeInMillis(); DeviceIntPtr dev = NULL; ScreenPtr screen; c = container_of(data, struct PointerBarrierClient, barrier); screen = c->screen; for (dev = inputInfo.devices; dev; dev = dev->next) { struct PointerBarrierDevice *pbd; int root_x, root_y; BarrierEvent ev = { .header = ET_Internal, .type = ET_BarrierLeave, .length = sizeof (BarrierEvent), .time = ms, /* .deviceid */ .sourceid = 0, .barrierid = c->id, .window = c->window, .root = screen->root->drawable.id, .dx = 0, .dy = 0, /* .root_x */ /* .root_y */ /* .dt */ /* .event_id */ .flags = XIBarrierPointerReleased, }; if (dev->type != MASTER_POINTER) continue; pbd = GetBarrierDevice(c, dev->id); if (!pbd->hit) continue; ev.deviceid = dev->id; ev.event_id = pbd->barrier_event_id; ev.dt = ms - pbd->last_timestamp; GetSpritePosition(dev, &root_x, &root_y); ev.root_x = root_x; ev.root_y = root_y; mieqEnqueue(dev, (InternalEvent *) &ev); } xorg_list_del(&c->entry); FreePointerBarrierClient(c); return Success; } static void add_master_func(void *res, XID id, void *devid) { struct PointerBarrier *b; struct PointerBarrierClient *barrier; struct PointerBarrierDevice *pbd; int *deviceid = devid; b = res; barrier = container_of(b, struct PointerBarrierClient, barrier); pbd = AllocBarrierDevice(); pbd->deviceid = *deviceid; xorg_list_add(&pbd->entry, &barrier->per_device); } static void remove_master_func(void *res, XID id, void *devid) { struct PointerBarrierDevice *pbd; struct PointerBarrierClient *barrier; struct PointerBarrier *b; DeviceIntPtr dev; int *deviceid = devid; int rc; Time ms = GetTimeInMillis(); rc = dixLookupDevice(&dev, *deviceid, serverClient, DixSendAccess); if (rc != Success) return; b = res; barrier = container_of(b, struct PointerBarrierClient, barrier); pbd = GetBarrierDevice(barrier, *deviceid); if (pbd->hit) { BarrierEvent ev = { .header = ET_Internal, .type =ET_BarrierLeave, .length = sizeof (BarrierEvent), .time = ms, .deviceid = *deviceid, .sourceid = 0, .dx = 0, .dy = 0, .root = barrier->screen->root->drawable.id, .window = barrier->window, .dt = ms - pbd->last_timestamp, .flags = XIBarrierPointerReleased, .event_id = pbd->barrier_event_id, .barrierid = barrier->id, }; mieqEnqueue(dev, (InternalEvent *) &ev); } xorg_list_del(&pbd->entry); free(pbd); } void XIBarrierNewMasterDevice(ClientPtr client, int deviceid) { FindClientResourcesByType(client, PointerBarrierType, add_master_func, &deviceid); } void XIBarrierRemoveMasterDevice(ClientPtr client, int deviceid) { FindClientResourcesByType(client, PointerBarrierType, remove_master_func, &deviceid); } int XICreatePointerBarrier(ClientPtr client, xXFixesCreatePointerBarrierReq * stuff) { int err; struct PointerBarrierClient *barrier; struct PointerBarrier b; b.x1 = stuff->x1; b.x2 = stuff->x2; b.y1 = stuff->y1; b.y2 = stuff->y2; if (!barrier_is_horizontal(&b) && !barrier_is_vertical(&b)) return BadValue; /* no 0-sized barriers */ if (barrier_is_horizontal(&b) && barrier_is_vertical(&b)) return BadValue; /* no infinite barriers on the wrong axis */ if (barrier_is_horizontal(&b) && (b.y1 < 0 || b.y2 < 0)) return BadValue; if (barrier_is_vertical(&b) && (b.x1 < 0 || b.x2 < 0)) return BadValue; if ((err = CreatePointerBarrierClient(client, stuff, &barrier))) return err; if (!AddResource(stuff->barrier, PointerBarrierType, &barrier->barrier)) return BadAlloc; return Success; } int XIDestroyPointerBarrier(ClientPtr client, xXFixesDestroyPointerBarrierReq * stuff) { int err; void *barrier; err = dixLookupResourceByType((void **) &barrier, stuff->barrier, PointerBarrierType, client, DixDestroyAccess); if (err != Success) { client->errorValue = stuff->barrier; return err; } if (CLIENT_ID(stuff->barrier) != client->index) return BadAccess; FreeResource(stuff->barrier, RT_NONE); return Success; } int SProcXIBarrierReleasePointer(ClientPtr client) { xXIBarrierReleasePointerInfo *info; REQUEST(xXIBarrierReleasePointerReq); int i; info = (xXIBarrierReleasePointerInfo*) &stuff[1]; swaps(&stuff->length); swapl(&stuff->num_barriers); for (i = 0; i < stuff->num_barriers; i++, info++) { swaps(&info->deviceid); swapl(&info->barrier); swapl(&info->eventid); } return (ProcXIBarrierReleasePointer(client)); } int ProcXIBarrierReleasePointer(ClientPtr client) { int i; int err; struct PointerBarrierClient *barrier; struct PointerBarrier *b; xXIBarrierReleasePointerInfo *info; REQUEST(xXIBarrierReleasePointerReq); REQUEST_AT_LEAST_SIZE(xXIBarrierReleasePointerReq); info = (xXIBarrierReleasePointerInfo*) &stuff[1]; for (i = 0; i < stuff->num_barriers; i++, info++) { struct PointerBarrierDevice *pbd; DeviceIntPtr dev; CARD32 barrier_id, event_id; _X_UNUSED CARD32 device_id; barrier_id = info->barrier; event_id = info->eventid; err = dixLookupDevice(&dev, info->deviceid, client, DixReadAccess); if (err != Success) { client->errorValue = BadDevice; return err; } err = dixLookupResourceByType((void **) &b, barrier_id, PointerBarrierType, client, DixReadAccess); if (err != Success) { client->errorValue = barrier_id; return err; } if (CLIENT_ID(barrier_id) != client->index) return BadAccess; barrier = container_of(b, struct PointerBarrierClient, barrier); pbd = GetBarrierDevice(barrier, dev->id); if (pbd->barrier_event_id == event_id) pbd->release_event_id = event_id; } return Success; } Bool XIBarrierInit(void) { int i; if (!dixRegisterPrivateKey(&BarrierScreenPrivateKeyRec, PRIVATE_SCREEN, 0)) return FALSE; for (i = 0; i < screenInfo.numScreens; i++) { ScreenPtr pScreen = screenInfo.screens[i]; BarrierScreenPtr cs; cs = (BarrierScreenPtr) calloc(1, sizeof(BarrierScreenRec)); if (!cs) return FALSE; xorg_list_init(&cs->barriers); SetBarrierScreen(pScreen, cs); } PointerBarrierType = CreateNewResourceType(BarrierFreeBarrier, "XIPointerBarrier"); return PointerBarrierType; } void XIBarrierReset(void) { int i; for (i = 0; i < screenInfo.numScreens; i++) { ScreenPtr pScreen = screenInfo.screens[i]; BarrierScreenPtr cs = GetBarrierScreen(pScreen); free(cs); SetBarrierScreen(pScreen, NULL); } }
27.982833
108
0.617446
015b744c0e457e13562fff6327a723d527ac6dfa
373
h
C
MONOV3/Find/Model/Mod_list.h
chilejiang1024/MONOV3
211f781fda79ba02062d0ddf4ca7166a30c1dfcb
[ "MIT" ]
1
2016-04-24T12:01:03.000Z
2016-04-24T12:01:03.000Z
MONOV3/Find/Model/Mod_list.h
chilejiang1024/MONOV3
211f781fda79ba02062d0ddf4ca7166a30c1dfcb
[ "MIT" ]
null
null
null
MONOV3/Find/Model/Mod_list.h
chilejiang1024/MONOV3
211f781fda79ba02062d0ddf4ca7166a30c1dfcb
[ "MIT" ]
null
null
null
// // Mod_list.h // MONOV3 // // Created by apple on 16/3/25. // Copyright © 2016年 JiangChile. All rights reserved. // #import "BaseModel.h" @interface Mod_list : BaseModel @property (nonatomic, retain) NSMutableArray *entity_list; @property (nonatomic, copy) NSString *type; @property (nonatomic, copy) NSString *Id; @property (nonatomic, copy) NSString *name; @end
21.941176
58
0.715818
75fbdcc163edb0e95b19ee53eb183c848a6d9808
1,390
h
C
GoogleWifi Headers/JETFamilyHubDayRangeViewController.h
LemaMichael/BetterGoogleWifi
b02a0adc35d80f1fa9443874d12de483c3d63c06
[ "MIT" ]
1
2022-01-25T13:08:30.000Z
2022-01-25T13:08:30.000Z
GoogleWifi Headers/JETFamilyHubDayRangeViewController.h
LemaMichael/BetterGoogleWifi
b02a0adc35d80f1fa9443874d12de483c3d63c06
[ "MIT" ]
null
null
null
GoogleWifi Headers/JETFamilyHubDayRangeViewController.h
LemaMichael/BetterGoogleWifi
b02a0adc35d80f1fa9443874d12de483c3d63c06
[ "MIT" ]
null
null
null
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import "JETGroupAwareCollectionViewController.h" @class NSArray, NSIndexSet, UIColor; @interface JETFamilyHubDayRangeViewController : JETGroupAwareCollectionViewController { _Bool _startSelected; NSArray *_daysOfTheWeek; UIColor *_selectedColor; UIColor *_itemTitleColor; UIColor *_itemSubtitleColor; } @property(nonatomic) _Bool startSelected; // @synthesize startSelected=_startSelected; @property(retain, nonatomic) UIColor *itemSubtitleColor; // @synthesize itemSubtitleColor=_itemSubtitleColor; @property(retain, nonatomic) UIColor *itemTitleColor; // @synthesize itemTitleColor=_itemTitleColor; @property(retain, nonatomic) UIColor *selectedColor; // @synthesize selectedColor=_selectedColor; - (void).cxx_destruct; @property(readonly, nonatomic) NSIndexSet *selectedDays; - (void)collectionView:(id)arg1 didDeselectItemAtIndexPath:(id)arg2; - (void)collectionView:(id)arg1 didSelectItemAtIndexPath:(id)arg2; - (void)viewWillAppear:(_Bool)arg1; - (void)viewDidLoad; @property(readonly, nonatomic) NSArray *daysOfTheWeek; // @synthesize daysOfTheWeek=_daysOfTheWeek; - (void)constructModel; - (id)initWithCoder:(id)arg1; - (id)initWithNibName:(id)arg1 bundle:(id)arg2; @end
37.567568
109
0.778417
f3f4ff65d6c0f2af5a2bb81eabfed8ab0913ade8
407
h
C
project_history/version2/Scene.h
rodohanna/Simulation-Engine
1ff3acf5949a5651f862cac90a44eb7e0d044e9f
[ "MIT" ]
null
null
null
project_history/version2/Scene.h
rodohanna/Simulation-Engine
1ff3acf5949a5651f862cac90a44eb7e0d044e9f
[ "MIT" ]
null
null
null
project_history/version2/Scene.h
rodohanna/Simulation-Engine
1ff3acf5949a5651f862cac90a44eb7e0d044e9f
[ "MIT" ]
null
null
null
#ifndef SCENE_h_ #define SCENE_h_ #include "Entity.h" #include "EventBus.h" #include "World.h" #include "GUI.h" #include "Console.h" #include <memory> #include <vector> #include <string> struct Scene { Scene(EventBus *); void update(double ts); EventBus *event_bus; std::unique_ptr<GUI> gui; std::unique_ptr<Console> console; std::unique_ptr<ChunkManager> chunk_manager; }; #endif
17.695652
48
0.697789
13ec0087a38bb4c73a1bf65c4c068fc12b41e5ad
788
h
C
Source/Renderer/include/RiveLinearAnimationInstance.h
oah2008/rive-ios
7b52ebb1007dbe306b97f836dccd853533dac51f
[ "MIT" ]
57
2020-10-05T21:32:52.000Z
2022-03-20T00:59:22.000Z
Source/Renderer/include/RiveLinearAnimationInstance.h
oah2008/rive-ios
7b52ebb1007dbe306b97f836dccd853533dac51f
[ "MIT" ]
59
2020-10-06T05:22:41.000Z
2022-03-30T18:10:01.000Z
Source/Renderer/include/RiveLinearAnimationInstance.h
oah2008/rive-ios
7b52ebb1007dbe306b97f836dccd853533dac51f
[ "MIT" ]
11
2020-11-27T16:04:57.000Z
2022-03-10T10:00:03.000Z
// // RiveLinearAnimationInstance.h // RiveRuntime // // Created by Maxwell Talbot on 5/14/21. // Copyright © 2021 Rive. All rights reserved. // #ifndef rive_linear_animation_instance_h #define rive_linear_animation_instance_h #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @class RiveLinearAnimation; /* * RiveLinearAnimationInstance */ @interface RiveLinearAnimationInstance : NSObject - (float)time; - (void)setTime:(float) time; - (const RiveLinearAnimation *)animation; - (void)applyTo:(RiveArtboard*)artboard; - (bool)advanceBy:(double)elapsedSeconds; - (int)direction; - (void)direction:(int)direction; - (int)loop; - (void)loop:(int)loopMode; - (bool)didLoop; - (NSString *)name; @end NS_ASSUME_NONNULL_END #endif /* rive_linear_animation_instance_h */
19.219512
49
0.756345
cd06c523d26633733e0f3be1f850c4c69d589aa3
517
c
C
testsuite/sandbox/gemver/cookie/gemver.c
parsabee/Orio
64de0f7ee422483b60a9f02793472e20e864aa08
[ "MIT" ]
24
2015-01-26T03:14:19.000Z
2021-09-27T23:10:12.000Z
testsuite/sandbox/gemver/cookie/gemver.c
parsabee/Orio
64de0f7ee422483b60a9f02793472e20e864aa08
[ "MIT" ]
30
2015-04-17T18:14:27.000Z
2021-05-30T15:01:47.000Z
testsuite/sandbox/gemver/cookie/gemver.c
parsabee/Orio
64de0f7ee422483b60a9f02793472e20e864aa08
[ "MIT" ]
20
2015-02-11T08:20:19.000Z
2022-01-15T17:55:00.000Z
/* pluto start (n,a,b) */ for (i = 0; i <= n-1; i++) { for (j = 0; j <= n-1; j++) { B[i][j] = A[i][j] + u1[i]*v1[j] + u2[i]*v2[j]; } } for (i = 0; i <= n-1; i++) x[i] = 0; for (i = 0; i <= n-1; i++) { for (j = 0; j <= n-1; j++) { x[j] = x[j] + y[i]*B[i][j]; } } for (i = 0; i <= n-1; i++) { x[i] = z[i] + b*x[i]; } for (i = 0; i <= n-1; i++) w[i] = 0; /* pluto end */ for (i = 0; i <= n-1; i++) { for (j = 0; j <= n-1; j++) { w[i] = w[i] + B[i][j]*x[j]; } w[i] = a*w[i]; }
15.205882
50
0.301741
431af41bf49ea6db2b89fb4f6dfaf37c96081955
331
h
C
GlyphPaths.h
corgibytes/WordTree
78481250df31745c54b8a82848e2aa15e2610062
[ "MIT" ]
null
null
null
GlyphPaths.h
corgibytes/WordTree
78481250df31745c54b8a82848e2aa15e2610062
[ "MIT" ]
null
null
null
GlyphPaths.h
corgibytes/WordTree
78481250df31745c54b8a82848e2aa15e2610062
[ "MIT" ]
null
null
null
// // GlyphPaths.h // WordTree // // Created by M. Scott Ford on 5/24/08. // Copyright 2008 __MyCompanyName__. // #import <Cocoa/Cocoa.h> @interface GlyphPaths : NSObject { CTFontRef font; NSMutableDictionary* pathCache; } - (id) initWithFont: (CTFontRef) font; - (CGPathRef) pathForLetter: (NSString*) letter; @end
15.045455
48
0.682779
9e964c73bf81006fae9d1d451fc60ab3ba9ac4ce
5,761
h
C
libbdmp/proto.h
jiverson002/bdmpi
11fc719f82a6851644fa21c6b12b0adec84feaf9
[ "Apache-2.0" ]
null
null
null
libbdmp/proto.h
jiverson002/bdmpi
11fc719f82a6851644fa21c6b12b0adec84feaf9
[ "Apache-2.0" ]
null
null
null
libbdmp/proto.h
jiverson002/bdmpi
11fc719f82a6851644fa21c6b12b0adec84feaf9
[ "Apache-2.0" ]
null
null
null
/* * proto.h * * This file contains function prototypes * * Started 3/31/2013 * George * * $Id: proto.h 10513 2011-07-07 22:06:03Z karypis $ * */ #ifndef _PROTO_H_ #define _PROTO_H_ /* init.c */ int bdmp_Init(sjob_t **r_job, int *argc, char **argv[]); /* finalize.c */ int bdmp_Finalize(sjob_t *job); /* comm.c */ int bdmp_Comm_size(sjob_t *job, BDMPI_Comm comm, int *size); int bdmp_Comm_lsize(sjob_t *job, BDMPI_Comm comm, int *lsize); int bdmp_Comm_nsize(sjob_t *job, BDMPI_Comm comm, int *nsize); int bdmp_Comm_rank(sjob_t *job, BDMPI_Comm comm, int *rank); int bdmp_Comm_lrank(sjob_t *job, BDMPI_Comm comm, int *lrank); int bdmp_Comm_nrank(sjob_t *job, BDMPI_Comm comm, int *nrank); int bdmp_Comm_rrank(sjob_t *job, BDMPI_Comm comm, int *rrank); int bdmp_Comm_dup(sjob_t *job, BDMPI_Comm comm, BDMPI_Comm *newcomm); int bdmp_Comm_free(sjob_t *job, BDMPI_Comm *comm); int bdmp_Comm_split(sjob_t *job, BDMPI_Comm comm, int color, int key, BDMPI_Comm *newcomm); /* send.c */ int bdmp_Send(sjob_t *job, void *buf, size_t count, BDMPI_Datatype datatype, int dest, int tag, BDMPI_Comm comm); int bdmp_Isend(sjob_t *job, void *buf, size_t count, BDMPI_Datatype datatype, int dest, int tag, BDMPI_Comm comm, BDMPI_Request *request); /* recv.c */ int bdmp_Recv(sjob_t *job, void *buf, size_t count, BDMPI_Datatype datatype, int source, int tag, BDMPI_Comm comm, BDMPI_Status *status); int bdmp_Irecv(sjob_t *job, void *buf, size_t count, BDMPI_Datatype datatype, int source, int tag, BDMPI_Comm comm, BDMPI_Request *request); /* probe.c */ int bdmp_Probe(sjob_t *job, int source, int tag, BDMPI_Comm comm, BDMPI_Status *status); int bdmp_Iprobe(sjob_t *job, int source, int tag, BDMPI_Comm comm, int *flag, BDMPI_Status *status); /* test.c */ int bdmp_Test(sjob_t *job, BDMPI_Request *request, int *flag, BDMPI_Status *status); /* wait.c */ int bdmp_Wait(sjob_t *job, BDMPI_Request *request, BDMPI_Status *status); /* getcount.c */ int bdmp_Get_count(sjob_t *job, BDMPI_Status *status, BDMPI_Datatype datatype, size_t *count); /* barrier.c */ int bdmp_Barrier(sjob_t *job, BDMPI_Comm comm); /* bcast.c */ int bdmp_Bcast(sjob_t *job, void *buf, size_t count, BDMPI_Datatype datatype, int root, BDMPI_Comm comm); /* allgather.c */ int bdmp_Allgatherv(sjob_t *job, void *sendbuf, size_t sendcount, BDMPI_Datatype sendtype, void *recvbuf, size_t *recvcounts, size_t *displs, BDMPI_Datatype recvtype, BDMPI_Comm comm); /* reduce.c */ int bdmp_Reduce(sjob_t *job, void *sendbuf, void *recvbuf, size_t count, BDMPI_Datatype datatype, BDMPI_Op op, int root, BDMPI_Comm comm); int bdmp_Reduce_init(sjob_t *job, void *sendbuf, void *recvbuf, size_t count, BDMPI_Datatype datatype, BDMPI_Op op, int root, BDMPI_Comm comm, BDMPI_Request *request); int bdmp_Reduce_fine(sjob_t *job, void *recvbuf, size_t count, BDMPI_Datatype datatype, BDMPI_Op op, int root, BDMPI_Comm comm, BDMPI_Request *request); int bdmp_Allreduce(sjob_t *job, void *sendbuf, void *recvbuf, size_t count, BDMPI_Datatype datatype, BDMPI_Op op, BDMPI_Comm comm); /* merge.c */ int bdmp_Merge(sjob_t *job, void *sendbuf, int *sendids, int sendcount, void *recvbuf, int *recvids, size_t *r_recvcount, BDMPI_Datatype datatype, BDMPI_Op op, int root, BDMPI_Comm comm); /* alltoall.c */ int bdmp_Alltoallv_node(sjob_t *job, void *sendbuf, size_t *sendcounts, size_t *sdispls, BDMPI_Datatype sendtype, void *recvbuf, size_t *recvcounts, size_t *rdispls, BDMPI_Datatype recvtype, BDMPI_Comm comm); int bdmp_Alltoallv_p2p(sjob_t *job, void *sendbuf, size_t *sendcounts, size_t *sdispls, BDMPI_Datatype sendtype, void *recvbuf, size_t *recvcounts, size_t *rdispls, BDMPI_Datatype recvtype, BDMPI_Comm comm); /* scatter.c */ int bdmp_Scatterv_node(sjob_t *job, void *sendbuf, size_t *sendcounts, size_t *sdispls, BDMPI_Datatype sendtype, void *recvbuf, size_t recvcount, BDMPI_Datatype recvtype, int root, BDMPI_Comm comm); int bdmp_Scatterv_p2p(sjob_t *job, void *sendbuf, size_t *sendcounts, size_t *sdispls, BDMPI_Datatype sendtype, void *recvbuf, size_t recvcount, BDMPI_Datatype recvtype, int root, BDMPI_Comm comm); /* gather.c */ int bdmp_Gatherv_node(sjob_t *job, void *sendbuf, size_t sendcount, BDMPI_Datatype sendtype, void *recvbuf, size_t *recvcounts, size_t *rdispls, BDMPI_Datatype recvtype, int root, BDMPI_Comm comm); int bdmp_Gatherv_p2p(sjob_t *job, void *sendbuf, size_t sendcount, BDMPI_Datatype sendtype, void *recvbuf, size_t *recvcounts, size_t *rdispls, BDMPI_Datatype recvtype, int root, BDMPI_Comm comm); /* scan.c */ int bdmp_Scan(sjob_t *job, void *sendbuf, void *recvbuf, size_t count, BDMPI_Datatype datatype, BDMPI_Op op, BDMPI_Comm icomm); int bdmp_Exscan(sjob_t *job, void *sendbuf, void *recvbuf, size_t count, BDMPI_Datatype datatype, BDMPI_Op op, BDMPI_Comm icomm); /* debug.c */ int slv_printf(char *f_str,...); /* memory.c */ void *bd_malloc(size_t nbytes, char *msg); void bd_free(void **ptr1,...); /* sbmalloc.c */ int sb_init(sjob_t * const job); int sb_finalize(); void *sb_malloc(size_t nbytes); void *sb_realloc(void *ptr, size_t nbytes); void sb_free(void *buf); int sb_exists(void *ptr); void sb_save(void *buf); void sb_saveall(); size_t sb_saveall_internal(); void sb_load(void const *buf); void sb_loadall(); void sb_discard(void *ptr, size_t size); /* route.c */ void slv_route(sjob_t * const job, bdmsg_t const * const gomsg); #endif
37.167742
86
0.704912
7f60b1131ded18effe132b323ced4e37fd9a2a02
3,938
h
C
cpp/inc/bond/comm/service_table.h
grisharav/bond
db05b170c83f74d0ea561d109ea90ed63b13cfa6
[ "MIT" ]
null
null
null
cpp/inc/bond/comm/service_table.h
grisharav/bond
db05b170c83f74d0ea561d109ea90ed63b13cfa6
[ "MIT" ]
null
null
null
cpp/inc/bond/comm/service_table.h
grisharav/bond
db05b170c83f74d0ea561d109ea90ed63b13cfa6
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #pragma once #include <bond/core/config.h> #include "services.h" namespace bond { namespace comm { // // Table of all exported RPC service interfaces. // class ServiceTable : public IService { template <typename WireProtocol> class Registrar { public: template <typename Service> Registrar Register(const boost::reference_wrapper<Service>& service, const std::string& name = Service::Schema::metadata.qualified_name) { _table.Register(service, _wireProtocol, name); return *this; } template <typename Service> Registrar Register(const boost::shared_ptr<Service>& service, const std::string& name = Service::Schema::metadata.qualified_name) { _table.Register(service, _wireProtocol, name); return *this; } private: friend class ServiceTable; Registrar(ServiceTable& table, const WireProtocol& wireProtocol) : _table(table), _wireProtocol(wireProtocol) {} Registrar(const Registrar& that) = default; ServiceTable& _table; const WireProtocol& _wireProtocol; }; public: ServiceTable() {} ServiceTable(const ServiceTable& that) : m_table(that.m_table) {} ServiceTable(ServiceTable&& that) : m_table(std::move(that.m_table)) {} template <typename WireProtocol> Registrar<WireProtocol> Using(const WireProtocol& wireProtocol) { return Registrar<WireProtocol>(*this, wireProtocol); } template <typename Service, typename WireProtocol> ServiceTable& Register(const boost::reference_wrapper<Service>& service, const WireProtocol& wireProtocol, const std::string& name = Service::Schema::metadata.qualified_name) { return Register(boost::make_shared< ServiceStub<Service, WireProtocol>>(service, wireProtocol, name)); } template <typename Service, typename WireProtocol> ServiceTable& Register(const boost::shared_ptr<Service>& service, const WireProtocol& wireProtocol, const std::string& name = Service::Schema::metadata.qualified_name) { return Register(boost::make_shared< ServiceStub<Service, WireProtocol>>(service, wireProtocol, name)); } void Notify(Event& event) override { GetService(event.service_name)->Notify(event); } void Invoke(Request& request, const ResponseCallback& callback) override { GetService(request.service_name)->Invoke(request, callback); } private: template <typename Service, typename WireProtocol> ServiceTable& Register(boost::shared_ptr<ServiceStub<Service, WireProtocol>>&& stub) { if (!m_table.emplace(stub->_service_name, stub).second) { // This is an expected exception to indicate that user is trying to register // service of a name that already exists in the table. BOND_THROW(InvalidInvocationException, "Service " << stub->_service_name << " is already inserted!"); } return *this; } const boost::shared_ptr<IService>& GetService(const std::string& service_name) const { // // Find service in the map. // auto it = m_table.find(service_name); if (it == m_table.end()) { BOND_THROW(MethodNotFoundException, "Service " << service_name << " is not registered!"); } return it->second; } std::map<std::string, boost::shared_ptr<IService> > m_table; }; } } // namespace bond.comm
28.536232
101
0.621889
7fdd4c7c2b59068039fa4c2804de766a4db1c06e
12,531
c
C
drivers/misc/tzdev/tztui_fts.c
CaelestisZ/HeraQ
2804afc99bf59c43740038833077ef7b14993592
[ "MIT" ]
null
null
null
drivers/misc/tzdev/tztui_fts.c
CaelestisZ/HeraQ
2804afc99bf59c43740038833077ef7b14993592
[ "MIT" ]
null
null
null
drivers/misc/tzdev/tztui_fts.c
CaelestisZ/HeraQ
2804afc99bf59c43740038833077ef7b14993592
[ "MIT" ]
null
null
null
/* * Copyright (C) 2015 Samsung Electronics, Inc. * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/kernel.h> #include <linux/spinlock.h> #include <linux/module.h> #include <linux/interrupt.h> #include <linux/ioctl.h> #include <linux/errno.h> #include <linux/fs.h> #include <linux/version.h> #include <linux/types.h> #include <linux/clk.h> #include <asm/io.h> #include <linux/i2c.h> #include <linux/pm.h> #include <linux/pm_runtime.h> #include <linux/gpio.h> #include <linux/delay.h> #include <linux/input.h> #include <linux/kthread.h> #include <linux/completion.h> #include <linux/atomic.h> #include <linux/kallsyms.h> #include <linux/irq.h> #include <linux/irqdesc.h> #include <linux/suspend.h> #include "../../input/touchscreen/stm/fts_ts.h" #include "tz_cdev.h" #include "tztui.h" MODULE_AUTHOR("Egor Uleyskiy <e.uleyskiy@samsung.com>"); MODULE_DESCRIPTION("TZTUI driver"); /* TrustZone Trusted User Interface */ MODULE_LICENSE("GPL"); int tztui_verbosity = 2; module_param(tztui_verbosity, int, 0644); MODULE_PARM_DESC(tztui_verbosity, "0: normal, 1: verbose, 2: debug"); #define TUI_OFFLINE 0x0 #define TUI_ONLINE 0x1 #define TZTUI_IOCTL_OPEN_SESSION 0x10 #define TZTUI_IOCTL_CLOSE_SESSION 0x11 #define TZTUI_IOCTL_CANCEL 0x12 #define TZTUI_IOCTL_BLANK_FB 0x20 #define TZTUI_IOCTL_UNBLANK_FB 0x21 #define TZTUI_IOCTL_GETINFO 0x30 struct dummy_qup_i2c_dev { struct device *dev; }; static DEFINE_SPINLOCK(tui_event_lock); static DEFINE_MUTEX(tui_mode_mutex); static DECLARE_WAIT_QUEUE_HEAD(irq_wait_queue); static bool tui_status = false; static int tui_mode = TUI_OFFLINE; static unsigned int tui_event_flag = 0; static volatile int thread_handler_stop = 0; static struct device *local_dev, *local_i2c_dev; static struct fts_ts_info *local_fts_info; static irq_handler_t local_irq_handler; static struct task_struct *ts; static const char i2c_dev_name[] = "1-0049"; static atomic_t touch_requested; static struct completion irq_completion; static struct wake_lock wakelock; static int request_touch(void); static int release_touch(void); static int fts_pm_notify(struct notifier_block *b, unsigned long ev, void *p) { (void)b; (void)p; DBG("%s: ev=%lu", __func__, ev); if (ev == PM_SUSPEND_PREPARE || ev == PM_HIBERNATION_PREPARE) release_touch(); return NOTIFY_DONE; } static struct notifier_block fts_pm_notifier; int tui_get_current(void) { int mode; mutex_lock(&tui_mode_mutex); mode = tui_mode; mutex_unlock(&tui_mode_mutex); return mode; } int tui_set_mode(int mode) { int ret_val = (-EINVAL); DBG("%s(%d) : Enter", __func__, mode); mutex_lock(&tui_mode_mutex); if (mode == tui_mode) ret_val = (-EALREADY); else if (mode == TUI_ONLINE) { ret_val = request_touch(); if (!ret_val) { tui_mode = mode; tui_event_flag = 0; thread_handler_stop = 0; } } else if (mode == TUI_OFFLINE) { ret_val = release_touch(); if (!ret_val) tui_mode = mode; } mutex_unlock(&tui_mode_mutex); return ret_val; } void tui_set_event(unsigned int event) { unsigned long flags; spin_lock_irqsave(&tui_event_lock, flags); tui_event_flag |= event; spin_unlock_irqrestore(&tui_event_lock, flags); wake_up(&irq_wait_queue); } /* Get pointer to synaptic driver on i2c bus */ struct device *get_fts_device(const char *name) { struct device *dev = NULL; DBG("%s() : Enter", __func__); dev = bus_find_device_by_name(&i2c_bus_type, NULL, name); return dev; } int thread_handler(void *data) { unsigned long flags, event; (void)data; do { if (wait_event_interruptible(irq_wait_queue, (tui_event_flag || thread_handler_stop)) == ERESTARTSYS) break; spin_lock_irqsave(&tui_event_lock, flags); event = tui_event_flag; tui_event_flag = 0; spin_unlock_irqrestore(&tui_event_lock, flags); if (thread_handler_stop || kthread_should_stop()) break; if (event) { tztui_smc_tui_event(event); complete(&irq_completion); } } while (1); return 0; } /* GPIO irq handler */ static irqreturn_t tui_fts_irq(int irq, void *data) { (void)irq; (void)data; tui_set_event(TUI_EVENT_TOUCH_IRQ); wait_for_completion_interruptible_timeout(&irq_completion, msecs_to_jiffies(10 * MSEC_PER_SEC)); return IRQ_HANDLED; } static irq_handler_t find_irqhandler(int irq, void *dev_id) { typedef struct irq_desc* (*irq_to_desc_func_t) (unsigned int irq); irq_to_desc_func_t irq_to_desc = NULL; struct irq_desc *desc; struct irqaction *action = NULL; struct irqaction *action_ptr = NULL; unsigned long flags; irq_to_desc = (irq_to_desc_func_t)((void **)kallsyms_lookup_name("irq_to_desc")); if (!irq_to_desc) return NULL; desc = irq_to_desc(irq); if (!desc) return NULL; raw_spin_lock_irqsave(&desc->lock, flags); action_ptr = desc->action; while (1) { action = action_ptr; if (!action) { raw_spin_unlock_irqrestore(&desc->lock, flags); return NULL; } if (action->dev_id == dev_id) { DBG("FOUND thread_fn=%p", action->thread_fn); DBG("FOUND handler=%p", action->handler); break; } action_ptr = action->next; } if (!action->handler) { raw_spin_unlock_irqrestore(&desc->lock, flags); return NULL; } raw_spin_unlock_irqrestore(&desc->lock, flags); return action->thread_fn; } /* Get pointer to qup-i2c device connected to touch controller */ struct device *get_i2c_device(struct fts_ts_info *fts_info) { struct device *dev = NULL; struct i2c_adapter *i2c_adapt; struct dummy_qup_i2c_dev *qup_dev; DBG("%s() : Enter", __func__); if (fts_info && fts_info->client) { i2c_adapt = fts_info->client->adapter; if (i2c_adapt) { qup_dev = i2c_get_adapdata(i2c_adapt); if (qup_dev) dev = qup_dev->dev; } } return dev; } /* Find synaptic touch driver by name and try to disallow its working */ static int request_touch(void) { int retval = -EFAULT; struct device *dev = NULL, *i2c_dev = NULL; struct fts_ts_info *fts_info; irq_handler_t irqhandler = NULL; (void)tui_fts_irq; DBG("%s() : Enter", __func__); if (atomic_read(&touch_requested) == 1) return -EALREADY; dev = get_fts_device(i2c_dev_name); if (!dev) { ERR("FTS Device %s not found.", i2c_dev_name); retval = -ENXIO; goto exit_err; } fts_info = dev_get_drvdata(dev); if (!fts_info) { ERR("Touchscreen driver internal data is empty."); retval = -EFAULT; goto exit_err; } wake_lock(&wakelock); wake_lock(&fts_info->wakelock); /*mutex_lock(&fts_info->device_mutex);*/ if (fts_info->touch_stopped) { DBG("Sensor stopped."); retval = -EBUSY; goto exit_err; } if (pm_runtime_get(fts_info->client->adapter->dev.parent) < 0) ERR("pm_runtime_get error"); INIT_COMPLETION(fts_info->st_powerdown); /*INIT_COMPLETION(info->st_interrupt);*/ i2c_dev = get_i2c_device(fts_info); if (!i2c_dev) { ERR("QUP-I2C Device not found."); retval = -ENXIO; goto exit_err2; } DBG("start"); irqhandler = find_irqhandler(fts_info->irq, fts_info); if (!irqhandler) ERR("irqhandler not found"); synchronize_irq(fts_info->client->irq); local_irq_handler = irqhandler; fts_info->touch_stopped = true; /* disable irq */ if (fts_info->irq_enabled) { disable_irq(fts_info->irq); free_irq(fts_info->irq, fts_info); DBG("Disable IRQ of fts_touch"); fts_info->irq_enabled = false; } local_dev = dev; local_i2c_dev = i2c_dev; local_fts_info = fts_info; INIT_COMPLETION(irq_completion); retval = request_threaded_irq(fts_info->irq, NULL, tui_fts_irq, IRQF_TRIGGER_LOW | IRQF_ONESHOT, "tztui", tui_fts_irq); /*retval = request_irq(fts_info->irq, tui_fts_irq, IRQF_TRIGGER_LOW | IRQF_ONESHOT, "tztui", tui_fts_irq);*/ if (retval < 0) { ERR("Request IRQ failed:%d", retval); goto exit_err3; } atomic_set(&touch_requested, 1); fts_pm_notifier.notifier_call = fts_pm_notify; fts_pm_notifier.priority = 0; retval = register_pm_notifier(&fts_pm_notifier); if (retval < 0) { DBG("register_pm_notifier: retval=%d", retval); goto exit_err4; } DBG("Touch requested"); return 0; exit_err4: retval = unregister_pm_notifier(&fts_pm_notifier); if (retval < 0) DBG("unregister_pm_notifier: retval=%d", retval); exit_err3: disable_irq(fts_info->irq); retval = request_threaded_irq(fts_info->irq, NULL, irqhandler, IRQF_TRIGGER_LOW | IRQF_ONESHOT, FTS_TS_DRV_NAME, fts_info); if (retval < 0) ERR("Request IRQ FATAL:%d", retval); fts_info->irq_enabled = true; wake_unlock(&fts_info->wakelock); wake_unlock(&wakelock); complete(&fts_info->st_powerdown); exit_err2: pm_runtime_put(fts_info->client->adapter->dev.parent); exit_err: fts_info->touch_stopped = false; local_dev = NULL; local_fts_info = NULL; local_i2c_dev = NULL; local_irq_handler = NULL; return retval; } /* Release synaptic touch driver */ static int release_touch(void) { int retval = -EFAULT; struct fts_ts_info *fts_info = local_fts_info; struct device *i2c_dev = local_i2c_dev, *dev = local_dev; irq_handler_t irqhandler = local_irq_handler; (void) i2c_dev; (void) dev; DBG("%s() : Enter", __func__); if (atomic_read(&touch_requested) != 1) return -EALREADY; synchronize_irq(fts_info->client->irq); fts_info->touch_stopped = false; if (!fts_info->irq_enabled) { disable_irq(fts_info->irq); free_irq(fts_info->irq, tui_fts_irq); retval = request_threaded_irq(fts_info->irq, NULL, irqhandler, IRQF_TRIGGER_LOW | IRQF_ONESHOT, FTS_TS_DRV_NAME, fts_info); if (retval < 0) { ERR("Request IRQ failed:%d", retval); goto exit_err; } fts_info->irq_enabled = true; DBG("fts_touch irqhandler restored"); } retval = pm_runtime_put(fts_info->client->adapter->dev.parent); /*mutex_unlock(&fts_info->device_mutex);*/ if (retval < 0) ERR("pm_runtime_put fauled:%d", retval); retval = unregister_pm_notifier(&fts_pm_notifier); DBG("%s: retval=%d", __func__, retval); wake_unlock(&fts_info->wakelock); wake_unlock(&wakelock); complete(&fts_info->st_powerdown); exit_err: atomic_set(&touch_requested, 0); return retval; } static long tztui_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { int rc = -ENOTTY; (void)arg; (void)file; switch (cmd) { case TZTUI_IOCTL_OPEN_SESSION: rc = tui_set_mode(TUI_ONLINE); break; case TZTUI_IOCTL_CLOSE_SESSION: rc = tui_set_mode(TUI_OFFLINE); break; case TZTUI_IOCTL_CANCEL: if (tui_get_current() == TUI_ONLINE) { tui_set_event(TUI_EVENT_CANCEL); rc = 0; } else rc = -EPERM; break; default: return -ENOTTY; /* Wrong or not-implemented function */ } return rc; } static int tztui_open(struct inode *inode, struct file *filp) { mutex_lock(&tui_mode_mutex); if (!tui_status) { tui_status = true; mutex_unlock(&tui_mode_mutex); return 0; } else { mutex_unlock(&tui_mode_mutex); ERR("TUI Device already used"); return -EBUSY; } } static int tztui_release(struct inode *inode, struct file *filp) { mutex_lock(&tui_mode_mutex); tui_status = false; mutex_unlock(&tui_mode_mutex); return 0; } static const struct file_operations tztui_fops = { .owner = THIS_MODULE, .open = tztui_open, .release = tztui_release, .unlocked_ioctl = tztui_ioctl, }; static struct tz_cdev tztui_cdev = { .name = "tztui", .fops = &tztui_fops, .owner = THIS_MODULE, }; static int __init tztui_init(void) { int rc; int cpu_num = 0; (void)cpu_num; (void)ts; (void)thread_handler_stop; (void)irq_wait_queue; wake_lock_init(&wakelock, WAKE_LOCK_SUSPEND, "tztui_wakelock"); ts = kthread_create(thread_handler, NULL, "per_cpu_thread"); kthread_bind(ts, cpu_num); if (!IS_ERR(ts)) wake_up_process(ts); else { ERR("Failed to bind thread to CPU %d", cpu_num); return -1; } init_completion(&irq_completion); rc = tz_cdev_register(&tztui_cdev); if (rc) { thread_handler_stop = 1; wake_up(&irq_wait_queue); kthread_stop(ts); ts = NULL; } return rc; } static void __exit tztui_exit(void) { tui_set_mode(TUI_OFFLINE); wake_lock_destroy(&wakelock); if (ts) { thread_handler_stop = 1; wake_up(&irq_wait_queue); kthread_stop(ts); ts = NULL; } tz_cdev_unregister(&tztui_cdev); } module_init(tztui_init); module_exit(tztui_exit);
23.034926
125
0.722448
fa1931f56f49c7385499483fff0a16981b111d48
1,701
h
C
errors.h
frp-2718/bf
b4ad8ee5642e42cb5b7e17b872531deb2db681f5
[ "X11" ]
null
null
null
errors.h
frp-2718/bf
b4ad8ee5642e42cb5b7e17b872531deb2db681f5
[ "X11" ]
null
null
null
errors.h
frp-2718/bf
b4ad8ee5642e42cb5b7e17b872531deb2db681f5
[ "X11" ]
null
null
null
/* * Copyright (c) 2013, frp * * 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. * * Except as contained in this notice, the name of the copyright holders shall * not be used in advertising or otherwise to promote the sale, use or other * dealings in this Software without prior written authorization from the * copyright holders. */ #ifndef INC_ERRORS_H #define INC_ERRORS_H #define MEMORY 10 #define EMPTY_CODE 20 #define EMPTY_REFLIST 30 #define NO_CODE 21 #define NO_REFLIST 31 #define SYNTAX 40 #define NO_FILE 50 #define INPUT 60 void error(int, const char *); void usage(void); #endif /* INC_ERRORS_H */
38.659091
80
0.738389
9a67ed9bb9b41d2e3564515413668bfdce31a594
24,053
c
C
programs/Xserver/dix/main.c
sourcecode-reloaded/Xming
b9f2e99d00f9445a29803d622d24b5314ee35991
[ "X11", "MIT" ]
4
2020-08-21T04:21:14.000Z
2022-01-15T11:26:11.000Z
programs/Xserver/dix/main.c
sourcecode-reloaded/Xming
b9f2e99d00f9445a29803d622d24b5314ee35991
[ "X11", "MIT" ]
1
2020-02-23T19:22:52.000Z
2020-02-23T19:22:52.000Z
programs/Xserver/dix/main.c
talregev/Xming
e7a997e3c6441c572df6953468fd8e88ca9e07e7
[ "X11", "MIT" ]
3
2020-12-18T06:33:36.000Z
2022-02-22T16:25:50.000Z
/*********************************************************** Copyright 1987, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. 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 OPEN GROUP 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. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts. All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Digital not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ /* The panoramix components contained the following notice */ /***************************************************************** Copyright (c) 1991, 1997 Digital Equipment Corporation, Maynard, Massachusetts. 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. 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 DIGITAL EQUIPMENT CORPORATION BE LIABLE FOR ANY CLAIM, DAMAGES, INCLUDING, BUT NOT LIMITED TO CONSEQUENTIAL OR INCIDENTAL 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. Except as contained in this notice, the name of Digital Equipment Corporation shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Digital Equipment Corporation. ******************************************************************/ /* $TOG: main.c /main/86 1998/02/09 14:20:03 kaleb $ */ #define NEED_EVENTS #ifdef HAVE_DIX_CONFIG_H #include <dix-config.h> #endif #include <X11/X.h> #include <X11/Xos.h> /* for unistd.h */ #include <X11/Xproto.h> #include "scrnintstr.h" #include "misc.h" #include "os.h" #include "windowstr.h" #include "resource.h" #include "dixstruct.h" #include "gcstruct.h" #include "extension.h" #include "colormap.h" #include "colormapst.h" #include "cursorstr.h" #include <X11/fonts/font.h> #include "opaque.h" #include "servermd.h" #include "hotplug.h" #include "site.h" #include "dixfont.h" #include "extnsionst.h" #ifdef XPRINT #include "DiPrint.h" #endif #ifdef PANORAMIX #include "panoramiXsrv.h" #else #include "dixevents.h" /* InitEvents() */ #include "dispatch.h" /* InitProcVectors() */ #endif #ifdef DPMSExtension #define DPMS_SERVER #include <X11/extensions/dpms.h> #include "dpmsproc.h" #endif extern int InitClientPrivates(ClientPtr client); extern void Dispatch(void); char *ConnectionInfo; xConnSetupPrefix connSetupPrefix; extern FontPtr defaultFont; extern int screenPrivateCount; extern void InitProcVectors(void); extern Bool CreateGCperDepthArray(void); #ifndef PANORAMIX static #endif Bool CreateConnectionBlock(void); static void FreeScreen(ScreenPtr); _X_EXPORT PaddingInfo PixmapWidthPaddingInfo[33]; int connBlockScreenStart; static int restart = 0; _X_EXPORT void NotImplemented(xEvent *from, xEvent *to) { FatalError("Not implemented"); } /* * Dummy entry for ReplySwapVector[] */ void ReplyNotSwappd( ClientPtr pClient , int size , void * pbuf ) { FatalError("Not implemented"); } /* * This array encodes the answer to the question "what is the log base 2 * of the number of pixels that fit in a scanline pad unit?" * Note that ~0 is an invalid entry (mostly for the benefit of the reader). */ static int answer[6][4] = { /* pad pad pad pad*/ /* 8 16 32 64 */ { 3, 4, 5 , 6 }, /* 1 bit per pixel */ { 1, 2, 3 , 4 }, /* 4 bits per pixel */ { 0, 1, 2 , 3 }, /* 8 bits per pixel */ { ~0, 0, 1 , 2 }, /* 16 bits per pixel */ { ~0, ~0, 0 , 1 }, /* 24 bits per pixel */ { ~0, ~0, 0 , 1 } /* 32 bits per pixel */ }; /* * This array gives the answer to the question "what is the first index for * the answer array above given the number of bits per pixel?" * Note that ~0 is an invalid entry (mostly for the benefit of the reader). */ static int indexForBitsPerPixel[ 33 ] = { ~0, 0, ~0, ~0, /* 1 bit per pixel */ 1, ~0, ~0, ~0, /* 4 bits per pixel */ 2, ~0, ~0, ~0, /* 8 bits per pixel */ ~0,~0, ~0, ~0, 3, ~0, ~0, ~0, /* 16 bits per pixel */ ~0,~0, ~0, ~0, 4, ~0, ~0, ~0, /* 24 bits per pixel */ ~0,~0, ~0, ~0, 5 /* 32 bits per pixel */ }; /* * This array gives the bytesperPixel value for cases where the number * of bits per pixel is a multiple of 8 but not a power of 2. */ static int answerBytesPerPixel[ 33 ] = { ~0, 0, ~0, ~0, /* 1 bit per pixel */ 0, ~0, ~0, ~0, /* 4 bits per pixel */ 0, ~0, ~0, ~0, /* 8 bits per pixel */ ~0,~0, ~0, ~0, 0, ~0, ~0, ~0, /* 16 bits per pixel */ ~0,~0, ~0, ~0, 3, ~0, ~0, ~0, /* 24 bits per pixel */ ~0,~0, ~0, ~0, 0 /* 32 bits per pixel */ }; /* * This array gives the answer to the question "what is the second index for * the answer array above given the number of bits per scanline pad unit?" * Note that ~0 is an invalid entry (mostly for the benefit of the reader). */ static int indexForScanlinePad[ 65 ] = { ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, 0, ~0, ~0, ~0, /* 8 bits per scanline pad unit */ ~0, ~0, ~0, ~0, 1, ~0, ~0, ~0, /* 16 bits per scanline pad unit */ ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, 2, ~0, ~0, ~0, /* 32 bits per scanline pad unit */ ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, ~0, 3 /* 64 bits per scanline pad unit */ }; #ifndef MIN #define MIN(a,b) (((a) < (b)) ? (a) : (b)) #endif int main(int argc, char *argv[], char *envp[]) { int i, j, k, error; char *xauthfile; HWEventQueueType alwaysCheckForInput[2]; display = "0"; InitGlobals(); #ifdef XPRINT PrinterInitGlobals(); #endif /* Quartz support on Mac OS X requires that the Cocoa event loop be in * the main thread. This allows the X server main to be called again * from another thread. */ #if defined(__DARWIN__) && defined(DARWIN_WITH_QUARTZ) DarwinHandleGUI(argc, argv, envp); #endif /* Notice if we're restarted. Probably this is because we jumped through * an uninitialized pointer */ if (restart) FatalError("server restarted. Jumped through uninitialized pointer?\n"); else restart = 1; CheckUserParameters(argc, argv, envp); CheckUserAuthorization(); #ifdef COMMANDLINE_CHALLENGED_OPERATING_SYSTEMS ExpandCommandLine(&argc, &argv); #endif InitConnectionLimits(); /* These are needed by some routines which are called from interrupt * handlers, thus have no direct calling path back to main and thus * can't be passed argc, argv as parameters */ argcGlobal = argc; argvGlobal = argv; /* prep X authority file from environment; this can be overriden by a * command line option */ xauthfile = getenv("XAUTHORITY"); if (xauthfile) InitAuthorization (xauthfile); ProcessCommandLine(argc, argv); alwaysCheckForInput[0] = 0; alwaysCheckForInput[1] = 1; while(1) { serverGeneration++; ScreenSaverTime = defaultScreenSaverTime; ScreenSaverInterval = defaultScreenSaverInterval; ScreenSaverBlanking = defaultScreenSaverBlanking; ScreenSaverAllowExposures = defaultScreenSaverAllowExposures; #ifdef DPMSExtension DPMSStandbyTime = defaultDPMSStandbyTime; DPMSSuspendTime = defaultDPMSSuspendTime; DPMSOffTime = defaultDPMSOffTime; DPMSEnabled = defaultDPMSEnabled; DPMSPowerLevel = 0; #endif InitBlockAndWakeupHandlers(); /* Perform any operating system dependent initializations you'd like */ OsInit(); configInitialise(); if(serverGeneration == 1) { CreateWellKnownSockets(); InitProcVectors(); clients = (ClientPtr *)xalloc(MAXCLIENTS * sizeof(ClientPtr)); if (!clients) FatalError("couldn't create client array"); for (i=1; i<MAXCLIENTS; i++) clients[i] = NullClient; serverClient = (ClientPtr)xalloc(sizeof(ClientRec)); if (!serverClient) FatalError("couldn't create server client"); InitClient(serverClient, 0, (pointer)NULL); } else ResetWellKnownSockets (); clients[0] = serverClient; currentMaxClients = 1; if (!InitClientResources(serverClient)) /* for root resources */ FatalError("couldn't init server resources"); SetInputCheck(&alwaysCheckForInput[0], &alwaysCheckForInput[1]); screenInfo.arraySize = MAXSCREENS; screenInfo.numScreens = 0; screenInfo.numVideoScreens = -1; WindowTable = (WindowPtr *)xalloc(MAXSCREENS * sizeof(WindowPtr)); if (!WindowTable) FatalError("couldn't create root window table"); /* * Just in case the ddx doesnt supply a format for depth 1 (like qvss). */ j = indexForBitsPerPixel[ 1 ]; k = indexForScanlinePad[ BITMAP_SCANLINE_PAD ]; PixmapWidthPaddingInfo[1].padRoundUp = BITMAP_SCANLINE_PAD-1; PixmapWidthPaddingInfo[1].padPixelsLog2 = answer[j][k]; j = indexForBitsPerPixel[8]; /* bits per byte */ PixmapWidthPaddingInfo[1].padBytesLog2 = answer[j][k]; PixmapWidthPaddingInfo[1].bitsPerPixel = 1; InitAtoms(); InitEvents(); InitGlyphCaching(); ResetExtensionPrivates(); ResetClientPrivates(); ResetScreenPrivates(); ResetWindowPrivates(); ResetGCPrivates(); ResetPixmapPrivates(); ResetColormapPrivates(); ResetFontPrivateIndex(); ResetDevicePrivateIndex(); InitCallbackManager(); InitVisualWrap(); InitOutput(&screenInfo, argc, argv); #ifdef XPRINT PrinterInitOutput(&screenInfo, argc, argv); #endif if (screenInfo.numScreens < 1) FatalError("no screens found"); if (screenInfo.numVideoScreens < 0) screenInfo.numVideoScreens = screenInfo.numScreens; InitExtensions(argc, argv); if (!InitClientPrivates(serverClient)) FatalError("failed to allocate serverClient devprivates"); for (i = 0; i < screenInfo.numScreens; i++) { ScreenPtr pScreen = screenInfo.screens[i]; if (!CreateScratchPixmapsForScreen(i)) FatalError("failed to create scratch pixmaps"); if (pScreen->CreateScreenResources && !(*pScreen->CreateScreenResources)(pScreen)) FatalError("failed to create screen resources"); if (!CreateGCperDepth(i)) FatalError("failed to create scratch GCs"); if (!CreateDefaultStipple(i)) FatalError("failed to create default stipple"); if (!CreateRootWindow(pScreen)) FatalError("failed to create root window"); } InitCoreDevices(); InitInput(argc, argv); if (InitAndStartDevices() != Success) FatalError("failed to initialize core devices"); InitFonts(); #ifdef BUILTIN_FONTS defaultFontPath = "built-ins"; #else if (loadableFonts) { SetFontPath(0, 0, (unsigned char *)defaultFontPath, &error); } else #endif { if (SetDefaultFontPath(defaultFontPath) != Success) ErrorF("failed to set default font path '%s'", defaultFontPath); } if (!SetDefaultFont(defaultTextFont)) { FatalError("could not open default font '%s'", defaultTextFont); } #ifdef NULL_ROOT_CURSOR cm.width = 0; cm.height = 0; cm.xhot = 0; cm.yhot = 0; if (!(rootCursor = AllocCursor(NULL, NULL, &cm, 0, 0, 0, 0, 0, 0))) { FatalError("could not create empty root cursor"); } AddResource(FakeClientID(0), RT_CURSOR, (pointer)rootCursor); #else if (!(rootCursor = CreateRootCursor(defaultCursorFont, 0))) { FatalError("could not open default cursor font '%s'", defaultCursorFont); } #endif #ifdef DPMSExtension /* check all screens, looking for DPMS Capabilities */ DPMSCapableFlag = DPMSSupported(); if (!DPMSCapableFlag) DPMSEnabled = FALSE; #endif #ifdef PANORAMIX /* * Consolidate window and colourmap information for each screen */ if (!noPanoramiXExtension) PanoramiXConsolidate(); #endif for (i = 0; i < screenInfo.numScreens; i++) InitRootWindow(WindowTable[i]); DefineInitialRootWindow(WindowTable[0]); SaveScreens(SCREEN_SAVER_FORCER, ScreenSaverReset); #ifdef PANORAMIX if (!noPanoramiXExtension) { if (!PanoramiXCreateConnectionBlock()) { FatalError("could not create connection block info"); } } else #endif { if (!CreateConnectionBlock()) { FatalError("could not create connection block info"); } } Dispatch(); /* Now free up whatever must be freed */ if (screenIsSaved == SCREEN_SAVER_ON) SaveScreens(SCREEN_SAVER_OFF, ScreenSaverReset); FreeScreenSaverTimer(); CloseDownExtensions(); #ifdef PANORAMIX { Bool remember_it = noPanoramiXExtension; noPanoramiXExtension = TRUE; FreeAllResources(); noPanoramiXExtension = remember_it; } #else FreeAllResources(); #endif configFini(); CloseDownDevices(); for (i = screenInfo.numScreens - 1; i >= 0; i--) { FreeScratchPixmapsForScreen(i); FreeGCperDepth(i); FreeDefaultStipple(i); (* screenInfo.screens[i]->CloseScreen)(i, screenInfo.screens[i]); FreeScreen(screenInfo.screens[i]); screenInfo.numScreens = i; } CloseDownEvents(); xfree(WindowTable); WindowTable = NULL; FreeFonts(); FreeAuditTimer(); xfree(serverClient->devPrivates); serverClient->devPrivates = NULL; if (dispatchException & DE_TERMINATE) { CloseWellKnownConnections(); } OsCleanup((dispatchException & DE_TERMINATE) != 0); if (dispatchException & DE_TERMINATE) { ddxGiveUp(); break; } xfree(ConnectionInfo); ConnectionInfo = NULL; } return(0); } static int VendorRelease = VENDOR_RELEASE; static char *VendorString = VENDOR_STRING; void SetVendorRelease(int release) { VendorRelease = release; } void SetVendorString(char *string) { VendorString = string; } static int padlength[4] = {0, 3, 2, 1}; #ifndef PANORAMIX static #endif Bool CreateConnectionBlock(void) { xConnSetup setup; xWindowRoot root; xDepth depth; xVisualType visual; xPixmapFormat format; unsigned long vid; int i, j, k, lenofblock, sizesofar = 0; char *pBuf; /* Leave off the ridBase and ridMask, these must be sent with connection */ setup.release = VendorRelease; /* * per-server image and bitmap parameters are defined in Xmd.h */ setup.imageByteOrder = screenInfo.imageByteOrder; setup.bitmapScanlineUnit = screenInfo.bitmapScanlineUnit; setup.bitmapScanlinePad = screenInfo.bitmapScanlinePad; setup.bitmapBitOrder = screenInfo.bitmapBitOrder; setup.motionBufferSize = NumMotionEvents(); setup.numRoots = screenInfo.numScreens; setup.nbytesVendor = strlen(VendorString); setup.numFormats = screenInfo.numPixmapFormats; setup.maxRequestSize = MAX_REQUEST_SIZE; QueryMinMaxKeyCodes(&setup.minKeyCode, &setup.maxKeyCode); lenofblock = sizeof(xConnSetup) + ((setup.nbytesVendor + 3) & ~3) + (setup.numFormats * sizeof(xPixmapFormat)) + (setup.numRoots * sizeof(xWindowRoot)); ConnectionInfo = (char *) xalloc(lenofblock); if (!ConnectionInfo) return FALSE; memmove(ConnectionInfo, (char *)&setup, sizeof(xConnSetup)); sizesofar = sizeof(xConnSetup); pBuf = ConnectionInfo + sizeof(xConnSetup); memmove(pBuf, VendorString, (int)setup.nbytesVendor); sizesofar += setup.nbytesVendor; pBuf += setup.nbytesVendor; i = padlength[setup.nbytesVendor & 3]; sizesofar += i; while (--i >= 0) *pBuf++ = 0; for (i=0; i<screenInfo.numPixmapFormats; i++) { format.depth = screenInfo.formats[i].depth; format.bitsPerPixel = screenInfo.formats[i].bitsPerPixel; format.scanLinePad = screenInfo.formats[i].scanlinePad; memmove(pBuf, (char *)&format, sizeof(xPixmapFormat)); pBuf += sizeof(xPixmapFormat); sizesofar += sizeof(xPixmapFormat); } connBlockScreenStart = sizesofar; for (i=0; i<screenInfo.numScreens; i++) { ScreenPtr pScreen; DepthPtr pDepth; VisualPtr pVisual; pScreen = screenInfo.screens[i]; root.windowId = WindowTable[i]->drawable.id; root.defaultColormap = pScreen->defColormap; root.whitePixel = pScreen->whitePixel; root.blackPixel = pScreen->blackPixel; root.currentInputMask = 0; /* filled in when sent */ root.pixWidth = pScreen->width; root.pixHeight = pScreen->height; root.mmWidth = pScreen->mmWidth; root.mmHeight = pScreen->mmHeight; root.minInstalledMaps = pScreen->minInstalledCmaps; root.maxInstalledMaps = pScreen->maxInstalledCmaps; root.rootVisualID = pScreen->rootVisual; root.backingStore = pScreen->backingStoreSupport; root.saveUnders = pScreen->saveUnderSupport != NotUseful; root.rootDepth = pScreen->rootDepth; root.nDepths = pScreen->numDepths; memmove(pBuf, (char *)&root, sizeof(xWindowRoot)); sizesofar += sizeof(xWindowRoot); pBuf += sizeof(xWindowRoot); pDepth = pScreen->allowedDepths; for(j = 0; j < pScreen->numDepths; j++, pDepth++) { lenofblock += sizeof(xDepth) + (pDepth->numVids * sizeof(xVisualType)); pBuf = (char *)xrealloc(ConnectionInfo, lenofblock); if (!pBuf) { xfree(ConnectionInfo); return FALSE; } ConnectionInfo = pBuf; pBuf += sizesofar; depth.depth = pDepth->depth; depth.nVisuals = pDepth->numVids; memmove(pBuf, (char *)&depth, sizeof(xDepth)); pBuf += sizeof(xDepth); sizesofar += sizeof(xDepth); for(k = 0; k < pDepth->numVids; k++) { vid = pDepth->vids[k]; for (pVisual = pScreen->visuals; pVisual->vid != vid; pVisual++) ; visual.visualID = vid; visual.class = pVisual->class; visual.bitsPerRGB = pVisual->bitsPerRGBValue; visual.colormapEntries = pVisual->ColormapEntries; visual.redMask = pVisual->redMask; visual.greenMask = pVisual->greenMask; visual.blueMask = pVisual->blueMask; memmove(pBuf, (char *)&visual, sizeof(xVisualType)); pBuf += sizeof(xVisualType); sizesofar += sizeof(xVisualType); } } } connSetupPrefix.success = xTrue; connSetupPrefix.length = lenofblock/4; connSetupPrefix.majorVersion = X_PROTOCOL; connSetupPrefix.minorVersion = X_PROTOCOL_REVISION; return TRUE; } /* grow the array of screenRecs if necessary. call the device-supplied initialization procedure with its screen number, a pointer to its ScreenRec, argc, and argv. return the number of successfully installed screens. */ int AddScreen( Bool (* pfnInit)( int /*index*/, ScreenPtr /*pScreen*/, int /*argc*/, char ** /*argv*/ ), int argc, char **argv) { int i; int scanlinepad, format, depth, bitsPerPixel, j, k; ScreenPtr pScreen; i = screenInfo.numScreens; if (i == MAXSCREENS) return -1; pScreen = (ScreenPtr) xcalloc(1, sizeof(ScreenRec)); if (!pScreen) return -1; pScreen->devPrivates = (DevUnion *)xcalloc(sizeof(DevUnion), screenPrivateCount); if (!pScreen->devPrivates && screenPrivateCount) { xfree(pScreen); return -1; } pScreen->myNum = i; pScreen->WindowPrivateLen = 0; pScreen->WindowPrivateSizes = (unsigned *)NULL; pScreen->totalWindowSize = ((sizeof(WindowRec) + sizeof(long) - 1) / sizeof(long)) * sizeof(long); pScreen->GCPrivateLen = 0; pScreen->GCPrivateSizes = (unsigned *)NULL; pScreen->totalGCSize = ((sizeof(GC) + sizeof(long) - 1) / sizeof(long)) * sizeof(long); pScreen->PixmapPrivateLen = 0; pScreen->PixmapPrivateSizes = (unsigned *)NULL; pScreen->totalPixmapSize = BitmapBytePad(sizeof(PixmapRec)*8); pScreen->ClipNotify = 0; /* for R4 ddx compatibility */ pScreen->CreateScreenResources = 0; /* * This loop gets run once for every Screen that gets added, * but thats ok. If the ddx layer initializes the formats * one at a time calling AddScreen() after each, then each * iteration will make it a little more accurate. Worst case * we do this loop N * numPixmapFormats where N is # of screens. * Anyway, this must be called after InitOutput and before the * screen init routine is called. */ for (format=0; format<screenInfo.numPixmapFormats; format++) { depth = screenInfo.formats[format].depth; bitsPerPixel = screenInfo.formats[format].bitsPerPixel; scanlinepad = screenInfo.formats[format].scanlinePad; j = indexForBitsPerPixel[ bitsPerPixel ]; k = indexForScanlinePad[ scanlinepad ]; PixmapWidthPaddingInfo[ depth ].padPixelsLog2 = answer[j][k]; PixmapWidthPaddingInfo[ depth ].padRoundUp = (scanlinepad/bitsPerPixel) - 1; j = indexForBitsPerPixel[ 8 ]; /* bits per byte */ PixmapWidthPaddingInfo[ depth ].padBytesLog2 = answer[j][k]; PixmapWidthPaddingInfo[ depth ].bitsPerPixel = bitsPerPixel; if (answerBytesPerPixel[bitsPerPixel]) { PixmapWidthPaddingInfo[ depth ].notPower2 = 1; PixmapWidthPaddingInfo[ depth ].bytesPerPixel = answerBytesPerPixel[bitsPerPixel]; } else { PixmapWidthPaddingInfo[ depth ].notPower2 = 0; } } /* This is where screen specific stuff gets initialized. Load the screen structure, call the hardware, whatever. This is also where the default colormap should be allocated and also pixel values for blackPixel, whitePixel, and the cursor Note that InitScreen is NOT allowed to modify argc, argv, or any of the strings pointed to by argv. They may be passed to multiple screens. */ pScreen->rgf = ~0L; /* there are no scratch GCs yet*/ WindowTable[i] = NullWindow; screenInfo.screens[i] = pScreen; screenInfo.numScreens++; if (!(*pfnInit)(i, pScreen, argc, argv)) { FreeScreen(pScreen); screenInfo.numScreens--; return -1; } return i; } static void FreeScreen(ScreenPtr pScreen) { xfree(pScreen->WindowPrivateSizes); xfree(pScreen->GCPrivateSizes); xfree(pScreen->PixmapPrivateSizes); xfree(pScreen->devPrivates); xfree(pScreen); }
29.991272
79
0.688687
2c98cb366005e19367c2bd0c9843f9abced5c0ef
4,643
c
C
College/Multimedia/LZW Algorithm.c
OjeshManandhar/Code-Backup
67a395fe2439725f42ce0a18b4d2e2e65f00695d
[ "MIT" ]
2
2019-01-03T14:12:52.000Z
2019-03-22T16:13:16.000Z
College/Multimedia/LZW Algorithm.c
OjeshManandhar/Code-Backup
67a395fe2439725f42ce0a18b4d2e2e65f00695d
[ "MIT" ]
null
null
null
College/Multimedia/LZW Algorithm.c
OjeshManandhar/Code-Backup
67a395fe2439725f42ce0a18b4d2e2e65f00695d
[ "MIT" ]
1
2019-01-13T17:54:01.000Z
2019-01-13T17:54:01.000Z
#include <time.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define CHAR_SIZE 5 #define IP_BIT_SIZE 5 #define OP_BIT_SIZE 6 #define INPUT_SIZE 1001 struct dict { int code; char sequence[CHAR_SIZE]; } * dict; int dictLength = 0; void initDict(); void printDict(const char *); char *decode(int *, int); int *encode(const char *, int *); char *findInDict_decode(int, int); int findInDict_encode(char *, char, int); int main() { char *decodedData = ""; int i, opLen, *opCode = NULL; // Use either const string or generate random // Const string // const char str[INPUT_SIZE] = "TOBEORNOTTTTOBEORTOBEORNOT"; // Generate random string char str[INPUT_SIZE] = ""; srand(time(0)); for (i = 0; i < INPUT_SIZE - 1; i++) str[i] = 'A' + rand() % ('Z' - 'A' + 1); printf("Input string:\t %s\n", str); printf("Input size:\t %lu\n", strlen(str) * IP_BIT_SIZE); // ENCODE initDict(); opCode = encode(str, &opLen); printf("Encoded data:\t "); for (i = 0; i < opLen; i++) printf("%d %s", opCode[i], (i == opLen - 1) ? "\n" : "| "); printf("Encoded size:\t %u\n", opLen * OP_BIT_SIZE); // printDict("Encode"); // DECODE initDict(); decodedData = decode(opCode, opLen); printf("Decoded data:\t %s\n", decodedData); printf("Decoded size:\t %lu\n", strlen(decodedData) * IP_BIT_SIZE); // printDict("Decode"); printf("Compressed size: %lu%%\n", (opLen * OP_BIT_SIZE * 100) / (strlen(str) * IP_BIT_SIZE)); printf("Same:\t\t %s\n", strcmp(str, decodedData) == 0 ? "True" : "False"); return 0; } void initDict() { int i, code; unsigned char seq[2]; dictLength = 0; for (i = 'A', code = 1; i <= 'Z'; i++, code++) { dict = (struct dict *)realloc(dict, (++dictLength) * sizeof(struct dict)); seq[0] = i; seq[1] = 0; dict[i - 'A'].code = code; strcpy(dict[i - 'A'].sequence, seq); } } void printDict(const char *str) { int i; printf("%s Dictonary: \n", str); for (i = 0; i < dictLength; i++) printf("%d \t %s\n", dict[i].code, dict[i].sequence); printf("\n"); } char *decode(int *opCode, int len) { int i, opStrlen = 1; char *opStr = NULL, curSeq[CHAR_SIZE] = ""; opStr = (char *)calloc(opStrlen, sizeof(char)); for (i = 0; i < len; i++) { strcpy(curSeq, findInDict_decode(opCode[i], (i == 0) ? -1 : opCode[i - 1])); opStrlen += strlen(curSeq); opStr = (char *)realloc(opStr, opStrlen * sizeof(char)); strcat(opStr, curSeq); } return opStr; } int *encode(const char *str, int *_opLen) { const int len = strlen(str); int i, code, opCode, *_opCode = NULL; char cur[CHAR_SIZE] = "", next, seq[2] = ""; *_opLen = 0; for (i = 0; i < len; i++) { seq[0] = str[i]; strcat(cur, seq); next = str[i + 1]; opCode = findInDict_encode(cur, next, i == len - 1); if (opCode != -1) { _opCode = (int *)realloc(_opCode, (*_opLen + 1) * sizeof(int)); _opCode[*_opLen] = opCode; *_opLen += 1; strcpy(cur, ""); } } return _opCode; } char *findInDict_decode(int cur, int prev) { int i, flag = 0; char *curSeq = NULL, prevSeq[CHAR_SIZE] = "", combo[CHAR_SIZE + 1] = "", seq[2] = ""; curSeq = (char *)calloc(CHAR_SIZE, sizeof(char)); for (i = 0; i < dictLength; i++) { if (dict[i].code == cur) { flag = 1; strcpy(curSeq, dict[i].sequence); } if (prev != -1 && dict[i].code == prev) strcpy(prevSeq, dict[i].sequence); } if (flag == 0) { // Cur code in not in dict so make new curSeq // New encoded string = old encoded string + the first character of the old encoded string strcpy(curSeq, prevSeq); seq[0] = prevSeq[0]; strcat(curSeq, seq); } if (prev != -1) { strcpy(combo, prevSeq); seq[0] = curSeq[0]; strcat(combo, seq); dict = (struct dict *)realloc(dict, (dictLength + 1) * sizeof(struct dict)); dict[dictLength].code = dict[dictLength - 1].code + 1; strcpy(dict[dictLength].sequence, combo); dictLength++; } return curSeq; } int findInDict_encode(char *cur, char next, int last) { int i, pos = -1; char combo[CHAR_SIZE + 1] = "", seq[2] = {next, 0}; strcpy(combo, cur); strcat(combo, seq); for (i = 0; i < dictLength; i++) { if (strcmp(dict[i].sequence, combo) == 0) return (last == 1) ? dict[i].code : -1; if (strcmp(dict[i].sequence, cur) == 0) pos = i; } dict = (struct dict *)realloc(dict, (dictLength + 1) * sizeof(struct dict)); dict[dictLength].code = dict[dictLength - 1].code + 1; strcpy(dict[dictLength].sequence, combo); dictLength++; return dict[pos].code; }
22.109524
96
0.580444
d0f845fa129eb5161aab50b6ffb59d9a0e6ae517
3,945
c
C
PIC18F4550/Home Automation System/Home Automation.c
anirudha-ani/Microcontroller
5bc003ed914963a4fc26872fa3914347cf19eecf
[ "Apache-2.0" ]
null
null
null
PIC18F4550/Home Automation System/Home Automation.c
anirudha-ani/Microcontroller
5bc003ed914963a4fc26872fa3914347cf19eecf
[ "Apache-2.0" ]
null
null
null
PIC18F4550/Home Automation System/Home Automation.c
anirudha-ani/Microcontroller
5bc003ed914963a4fc26872fa3914347cf19eecf
[ "Apache-2.0" ]
null
null
null
//program #pragma config PLLDIV = 5 #pragma config CPUDIV = OSC1_PLL2 #pragma config USBDIV = 2 #pragma config FOSC = INTOSCIO_EC #pragma config FCMEN = OFF #pragma config IESO = OFF #pragma config PWRT = OFF #pragma config BOR = OFF #pragma config BORV = 3 #pragma config VREGEN = OFF #pragma config WDT = OFF #pragma config WDTPS = 32768 #pragma config CCP2MX = ON #pragma config PBADEN = OFF #pragma config LPT1OSC = OFF #pragma config MCLRE = OFF #pragma config STVREN = ON #pragma config LVP = OFF #pragma config ICPRT = OFF #pragma config XINST = OFF #pragma config DEBUG = OFF #pragma config CP0 = OFF,CP1 = OFF,CP2 = OFF,CP3 = OFF #pragma config CPB = OFF #pragma config CPD = OFF #pragma config WRT0 = OFF,WRT1 = OFF,WRT2 = OFF,WRT3 = OFF #pragma config WRTB = OFF #pragma config WRTD = OFF #pragma config EBTR0 = OFF,EBTR1 = OFF,EBTR2 = OFF,EBTR3 = OFF #pragma config EBTRB = OFF #include <p18f4550.h> typedef unsigned char BYTE; //#define FLEX0 PORTAbits.RA0 //#define LED0 PORTBbits.RB3 //#define LED1 PORTBbits.RB2 //#define LED2 PORTBbits.RB1 //#define LED3 PORTBbits.RB0 //#define LED4 PORTDbits.RD7 //#define LED5 PORTDbits.RD6 //#define LED6 PORTDbits.RD5 //#define LED7 PORTDbits.RD4 #define LED0 PORTBbits.RB0 #define LED1 PORTBbits.RB1 void delay(void); void showByteOnLEDs(BYTE byteToShow); void main(void){ int a ; unsigned int t; //setting registers OSCCONbits.IRCF2 = 1;//IRCF = Set internal clock speed to 8mhz so set IRCF0,1,2 bits in ISCCOn register to 1 OSCCONbits.IRCF1 = 1; OSCCONbits.IRCF0 = 1; TRISAbits.RA0 = 1; //set analog pin as input and led as output TRISAbits.RA1 = 1; TRISBbits.RB0 = 0; //set led as output TRISBbits.RB1 = 0; //TRISBbits.RB2 = 0; //TRISBbits.RB3 = 0; //TRISDbits.RD7 = 0; //TRISDbits.RD6 = 0; //TRISDbits.RD5 = 0; //TRISDbits.RD4 = 0; //Making AN0/RA0 as Analog Input ADCON0bits.CHS3 = 0; //setting analog channel to RA0 ADCON0bits.CHS2 = 0; ADCON0bits.CHS1 = 0; ADCON0bits.CHS0 = 0; ADCON1bits.VCFG1 = 0; //setting range for the analog input here vcfg1 = lowerbound = GND, vcf0 = upperbound = 5v from vdd(power from usb) // set A/D converter negative reference Ground as low ADCON1bits.VCFG0 = 0; // set A/D converter positive reference VCC as high ADCON1bits.PCFG3 = 1; //setting which input pins will acts as analog or digital in this case only 1 analog input so this combination will make AN0+AN1 as analog and rest AN3-12 to digital ADCON1bits.PCFG2 = 1; ADCON1bits.PCFG1 = 0; ADCON1bits.PCFG0 = 1; ADCON2bits.ADFM = 0; //ADC results will be left justified (8 bit result) in ADRESH ADCON2bits.ACQT2 = 1; // set adc aquision time ADCON2bits.ACQT1 = 0; ADCON2bits.ACQT0 = 1; ADCON2bits.ADCS2 = 1; // set adc conversion clock ADCON2bits.ADCS1 = 0; ADCON2bits.ADCS0 = 1; ADCON0bits.ADON = 1; // turn adc on while(1){ //LDR input in RA0/AN0 //Making AN0/RA0 as Analog Input ADCON0bits.CHS3 = 0; //setting analog channel to RA0 ADCON0bits.CHS2 = 0; ADCON0bits.CHS1 = 0; ADCON0bits.CHS0 = 0; ADCON0bits.GO_DONE = 1; // perform A-D Conversion while(ADCON0bits.GO_DONE == 1){}; // wait for conversion a = ADRESH; if(a < 100)LED0 = 1; // Light sensor trigger value else LED0 = 0 ; //Temparature Sensor input in RA1/AN1 //Making AN1/RA1 as Analog Input ADCON0bits.CHS3 = 0; //setting analog channel to RA1 ADCON0bits.CHS2 = 0; ADCON0bits.CHS1 = 0; ADCON0bits.CHS0 = 1; delay(); ADCON0bits.GO_DONE = 1; // perform A-D Conversion while(ADCON0bits.GO_DONE == 1){}; // wait for conversion a = ADRESH; t = (((int)a/255.0) * 500); if(t > 26 )LED1 = 1; //Temparature sensor trigger value else LED1 = 0 ; } } void delay(void){ int i,j; for(i = 0; i < 1000; i ++)for(j = 0; j < 2; j++); }
26.47651
193
0.664639
cf7fee44992fc44b3fcfbfdead38167220983674
695
h
C
PrivateFrameworks/QuickLookSupport/QLZipArchive.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
17
2018-11-13T04:02:58.000Z
2022-01-20T09:27:13.000Z
PrivateFrameworks/QuickLookSupport/QLZipArchive.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
3
2018-04-06T02:02:27.000Z
2018-10-02T01:12:10.000Z
PrivateFrameworks/QuickLookSupport/QLZipArchive.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
1
2018-09-28T13:54:23.000Z
2018-09-28T13:54:23.000Z
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "NSObject.h" @class NSData, NSFileWrapper, NSURL; @interface QLZipArchive : NSObject { struct archive *_archive; NSURL *_url; NSData *_data; NSFileWrapper *_fileWrapper; } - (void).cxx_destruct; - (void)dealloc; - (id)fileWrapper; - (void)enumerateEntriesWithHandler:(CDUnknownBlockType)arg1; - (id)readCurrentDataWithEntry:(struct archive_entry *)arg1 error:(id *)arg2; - (BOOL)_reopenWithError:(id *)arg1; - (id)initWithData:(id)arg1 error:(id *)arg2; - (id)initWithURL:(id)arg1 error:(id *)arg2; - (id)libarchiveError; @end
22.419355
83
0.696403
65afcabdc328c3e159257bc012f31d5ea5c8b185
2,489
h
C
modules/aos/include/scene/node.h
Omnirobotic/godot
d50b5d047bbf6c68fc458c1ad097321ca627185d
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
modules/aos/include/scene/node.h
Omnirobotic/godot
d50b5d047bbf6c68fc458c1ad097321ca627185d
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
3
2019-11-14T12:20:06.000Z
2020-08-07T13:51:10.000Z
modules/aos/include/scene/node.h
Omnirobotic/godot
d50b5d047bbf6c68fc458c1ad097321ca627185d
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
#ifndef _NODE_H #define _NODE_H #include "object_class.h" #include "Vector7.h" #include <vector> #include <memory> namespace omni { namespace scene { // As we are using shared pointer everywhere, this class MUST be instancied using std::make_shared class node : public object, public std::enable_shared_from_this<node> { private: std::string _name; int pos; std::weak_ptr<node> _parent; std::vector<std::shared_ptr<node>> _children; bool _collidable = false; SCENE_CLASS(node, object) public: node(); virtual ~node(); inline std::string get_name() const { return _name; } std::string get_path_name(); const std::string get_path_name() const; std::vector<std::string> get_descendants_path_name(); inline void set_name(const std::string& name) { _name = name; } void add_child(std::shared_ptr<node> child); //void add_child_below_node(std::shared_ptr<node> node, std::shared_ptr<node> child); std::vector<std::shared_ptr<node>> get_children(); const std::vector<std::shared_ptr<node>> get_children() const; std::shared_ptr<node> find_child(const std::string& name, bool recursive = true); std::shared_ptr<node> get_parent(); const std::shared_ptr<node> get_parent() const; void remove_child(std::shared_ptr<node> child); size_t get_children_count() const; void set_collidable(bool collidable); bool get_collidable(); std::shared_ptr<node> move_to(const CppMath::Vector7& transform, const std::string& name = ""); private: void _validate_child_name(std::shared_ptr<node> child) const; void _generate_serial_child_name(const std::shared_ptr<node> child, std::string& name) const; inline std::string _get_name_num_separator() const { return "_"; } static std::string _increase_numeric_string(const std::string &s); void _add_child_nocheck(std::shared_ptr<node> child, const std::string& name); void _get_descendants_path_name_recursive(std::vector<std::string>& descendants_vector, std::string current_name); std::shared_ptr<node> _find_child(const std::string& name, bool recursive) const; }; } } #endif
37.712121
126
0.620329
65e3dd113800e8d4da9cc69f7008075047e7fc85
2,195
c
C
src/runsvchdir.c
NuTyX/runyx
5cabdbdad0bc8ff67c4c2d09a4507d3e4d5af708
[ "BSD-3-Clause" ]
4
2020-04-04T14:17:41.000Z
2021-11-09T17:58:13.000Z
src/runsvchdir.c
NuTyX/runyx
5cabdbdad0bc8ff67c4c2d09a4507d3e4d5af708
[ "BSD-3-Clause" ]
1
2020-04-02T14:17:40.000Z
2020-05-27T12:54:58.000Z
src/runsvchdir.c
NuTyX/runyx
5cabdbdad0bc8ff67c4c2d09a4507d3e4d5af708
[ "BSD-3-Clause" ]
null
null
null
#include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdio.h> #include "strerr.h" #include "error.h" #include "buffer.h" #define USAGE " dir" #define SVDIR "/etc/init" #define VERSION "$Id: 9bf17f77e33c6b961e060aacffa3c8abd38fc64a $" char *progname; char *new; void usage () { strerr_die4x(1, "usage: ", progname, USAGE, "\n"); } void fatal(char *m1, char *m2) { strerr_die5sys(111, progname, ": fatal: ", m1, m2, ": "); } void fatalx(char *m1, char *m2) { strerr_die4x(111, progname, ": fatal: ", m1, m2); } void warn(char *m1, char *m2) { strerr_warn5(progname, ": fatal: ", m1, m2, ": ", &strerr_sys); } int main (int argc, char **argv) { struct stat s; int dev; int ino; progname =*argv++; if (! argv || ! *argv) usage(); new =*argv; if (new[0] == '.') fatalx(new, ": must not start with a dot."); if (chdir(SVDIR) == -1) fatal("unable to chdir: ", SVDIR); if (stat(new, &s) == -1) { if (errno == error_noent) fatal(new, 0); fatal("unable to stat: ", new); } if (! S_ISDIR(s.st_mode)) fatalx(new, "not a directory."); ino =s.st_ino; dev =s.st_dev; if (stat("current", &s) == -1) fatal("unable to stat: ", "current"); if ((s.st_ino == ino) && (s.st_dev == dev)) { buffer_puts(buffer_1, "runsvchdir: "); buffer_puts(buffer_1, new); buffer_puts(buffer_1, ": current.\n"); buffer_flush(buffer_1); _exit(0); } if (unlink("current.new") == -1) if (errno != error_noent) fatal("unable to unlink: ", "current.new"); if (symlink(new, "current.new") == -1) fatal("unable to create: current.new -> ", new); if (unlink("previous") == -1) if (errno != error_noent) fatal("unable to unlink: ", "previous"); if (rename("current", "previous") == -1) fatal("unable to copy: current to ", "previous"); if (rename("current.new", "current") == -1) { warn("unable to move: current.new to ", "current"); if (rename("previous", "current") == -1) fatal("unable to move previous back to ", "current"); _exit(111); } buffer_puts(buffer_1, "runsvchdir: "); buffer_puts(buffer_1, new); buffer_puts(buffer_1, ": now current.\n"); buffer_flush(buffer_1); _exit(0); }
28.506494
73
0.603645
d0be3f5a8fe1b66f8a473f4c192e808864effe64
7,381
c
C
marshal/tpml-types.c
shruthi-ravi/tpm2-tss
c3a8fdc48371df79d527cb57b32aa7c13fe1edb0
[ "BSD-2-Clause" ]
null
null
null
marshal/tpml-types.c
shruthi-ravi/tpm2-tss
c3a8fdc48371df79d527cb57b32aa7c13fe1edb0
[ "BSD-2-Clause" ]
null
null
null
marshal/tpml-types.c
shruthi-ravi/tpm2-tss
c3a8fdc48371df79d527cb57b32aa7c13fe1edb0
[ "BSD-2-Clause" ]
null
null
null
/*********************************************************************** * Copyright (c) 2015 - 2017, Intel Corporation * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ #include <inttypes.h> #include <string.h> #include "sapi/marshal.h" #include "sapi/tpm20.h" #include "tss2_endian.h" #include "log.h" #define ADDR & #define VAL #define TAB_SIZE(tab) (sizeof(tab) / sizeof(tab[0])) #define TPML_MARSHAL(type, marshal_func, buf_name, op) \ TSS2_RC type##_Marshal(type const *src, uint8_t buffer[], \ size_t buffer_size, size_t *offset) \ { \ size_t local_offset = 0; \ UINT32 i, count = 0; \ TSS2_RC ret = TSS2_RC_SUCCESS; \ uint8_t *buf_ptr = buffer; \ uint8_t local_buffer[buffer_size]; \ \ if (offset != NULL) { \ LOG (INFO, "offset non-NULL, initial value: %zu", *offset); \ local_offset = *offset; \ } \ \ if (src == NULL) { \ LOG (WARNING, "src is NULL"); \ return TSS2_TYPES_RC_BAD_REFERENCE; \ } \ \ if (buffer == NULL && offset == NULL) { \ LOG (WARNING, "buffer and offset parameter are NULL"); \ return TSS2_TYPES_RC_BAD_REFERENCE; \ } else if (buffer_size < local_offset || \ buffer_size - local_offset < sizeof(count)) { \ LOG (WARNING, \ "buffer_size: %zu with offset: %zu are insufficient for object " \ "of size %zu", \ buffer_size, \ local_offset, \ sizeof(count)); \ return TSS2_TYPES_RC_INSUFFICIENT_BUFFER; \ } \ \ if (src->count > TAB_SIZE(src->buf_name)) { \ LOG (WARNING, "count too big"); \ return TSS2_SYS_RC_BAD_VALUE; \ } \ \ if (buf_ptr == NULL) \ buf_ptr = local_buffer; \ \ LOG (DEBUG, \ "Marshalling " #type " from 0x%" PRIxPTR " to buffer 0x%" PRIxPTR \ " at index 0x%zx", \ (uintptr_t)&src, \ (uintptr_t)buf_ptr, \ local_offset); \ \ ret = UINT32_Marshal(src->count, buf_ptr, buffer_size, &local_offset); \ if (ret) \ return ret; \ \ for (i = 0; i < src->count; i++) \ { \ ret = marshal_func(op src->buf_name[i], buf_ptr, buffer_size, &local_offset); \ if (ret) \ return ret; \ } \ if (offset != NULL) { \ *offset = local_offset; \ LOG (DEBUG, "offset parameter non-NULL updated to %zu", *offset); \ } \ \ return TSS2_RC_SUCCESS; \ } #define TPML_UNMARSHAL(type, unmarshal_func, buf_name) \ TSS2_RC type##_Unmarshal(uint8_t const buffer[], size_t buffer_size, \ size_t *offset, type *dest) \ { \ size_t local_offset = 0; \ UINT32 i, count = 0; \ TSS2_RC ret = TSS2_RC_SUCCESS; \ type local_dst; \ \ if (offset != NULL) { \ LOG (INFO, "offset non-NULL, initial value: %zu", *offset); \ local_offset = *offset; \ } \ \ if (buffer == NULL || (dest == NULL && offset == NULL)) { \ LOG (WARNING, "buffer or dest and offset parameter are NULL"); \ return TSS2_TYPES_RC_BAD_REFERENCE; \ } else if (buffer_size < local_offset || \ sizeof(count) > buffer_size - local_offset) \ { \ LOG (WARNING, \ "buffer_size: %zu with offset: %zu are insufficient for object " \ "of size %zu", \ buffer_size, \ local_offset, \ sizeof(count)); \ return TSS2_TYPES_RC_INSUFFICIENT_BUFFER; \ } \ \ LOG (DEBUG, \ "Unmarshalling " #type " from 0x%" PRIxPTR " to buffer 0x%" PRIxPTR \ " at index 0x%zx", \ (uintptr_t)buffer, \ (uintptr_t)dest, \ local_offset); \ \ if (dest == NULL) \ dest = &local_dst; \ \ ret = UINT32_Unmarshal(buffer, buffer_size, &local_offset, &count); \ if (ret) \ return ret; \ \ if (count > TAB_SIZE(dest->buf_name)) { \ LOG (WARNING, "count too big"); \ return TSS2_SYS_RC_MALFORMED_RESPONSE; \ } \ \ dest->count = count; \ \ for (i = 0; i < count; i++) \ { \ ret = unmarshal_func(buffer, buffer_size, &local_offset, &dest->buf_name[i]); \ if (ret) \ return ret; \ } \ \ if (offset != NULL) { \ *offset = local_offset; \ LOG (DEBUG, "offset parameter non-NULL, updated to %zu", *offset); \ } \ \ return TSS2_RC_SUCCESS; \ } /* * These macros expand to (un)marshal functions for each of the TPML types * the specification part 2. */ TPML_MARSHAL(TPML_CC, TPM_CC_Marshal, commandCodes, VAL) TPML_UNMARSHAL(TPML_CC, TPM_CC_Unmarshal, commandCodes) TPML_MARSHAL(TPML_CCA, TPMA_CC_Marshal, commandAttributes, VAL) TPML_UNMARSHAL(TPML_CCA, TPMA_CC_Unmarshal, commandAttributes) TPML_MARSHAL(TPML_ALG, UINT16_Marshal, algorithms, VAL) TPML_UNMARSHAL(TPML_ALG, UINT16_Unmarshal, algorithms) TPML_MARSHAL(TPML_HANDLE, UINT32_Marshal, handle, VAL) TPML_UNMARSHAL(TPML_HANDLE, UINT32_Unmarshal, handle) TPML_MARSHAL(TPML_DIGEST, TPM2B_DIGEST_Marshal, digests, ADDR) TPML_UNMARSHAL(TPML_DIGEST, TPM2B_DIGEST_Unmarshal, digests) TPML_MARSHAL(TPML_ALG_PROPERTY, TPMS_ALG_PROPERTY_Marshal, algProperties, ADDR) TPML_UNMARSHAL(TPML_ALG_PROPERTY, TPMS_ALG_PROPERTY_Unmarshal, algProperties) TPML_MARSHAL(TPML_ECC_CURVE, UINT16_Marshal, eccCurves, VAL) TPML_UNMARSHAL(TPML_ECC_CURVE, UINT16_Unmarshal, eccCurves) TPML_MARSHAL(TPML_TAGGED_TPM_PROPERTY, TPMS_TAGGED_PROPERTY_Marshal, tpmProperty, ADDR) TPML_UNMARSHAL(TPML_TAGGED_TPM_PROPERTY, TPMS_TAGGED_PROPERTY_Unmarshal, tpmProperty) TPML_MARSHAL(TPML_TAGGED_PCR_PROPERTY, TPMS_TAGGED_PCR_SELECT_Marshal, pcrProperty, ADDR) TPML_UNMARSHAL(TPML_TAGGED_PCR_PROPERTY, TPMS_TAGGED_PCR_SELECT_Unmarshal, pcrProperty) TPML_MARSHAL(TPML_PCR_SELECTION, TPMS_PCR_SELECTION_Marshal, pcrSelections, ADDR) TPML_UNMARSHAL(TPML_PCR_SELECTION, TPMS_PCR_SELECTION_Unmarshal, pcrSelections) TPML_MARSHAL(TPML_DIGEST_VALUES, TPMT_HA_Marshal, digests, ADDR) TPML_UNMARSHAL(TPML_DIGEST_VALUES, TPMT_HA_Unmarshal, digests)
37.090452
89
0.649776